1use std::future::Future;
39use std::ops::{Deref, DerefMut};
40use std::sync::Arc;
41use std::time::Instant;
42
43use tokio_postgres::error::SqlState;
44use tokio_postgres::types::ToSql;
45use tokio_postgres::{Error, Row, SimpleQueryMessage};
46use tracing::Instrument;
47
48use crate::record::{Analysis, Call, Failure, analyze};
49
50const POSTGRESQL: &str = "postgresql";
51
52const CLIENT_ERROR: &str = "tokio_postgres::Error";
55
56#[derive(Clone, Debug, Default)]
59pub struct Database(Arc<Target>);
60
61#[derive(Debug, Default)]
62struct Target {
63 namespace: Option<String>,
64 server: Option<(String, u16)>,
65}
66
67impl Database {
68 pub fn new(config: &tokio_postgres::Config) -> Self {
72 crate::record::describe_metrics();
73 let server = match config.get_hosts() {
74 [host] => {
75 let address = match host {
76 tokio_postgres::config::Host::Tcp(name) => name.clone(),
77 #[cfg(unix)]
78 tokio_postgres::config::Host::Unix(path) => path.display().to_string(),
79 };
80 let port = config.get_ports().first().copied().unwrap_or(5432);
81 Some((address, port))
82 }
83 _ => None,
84 };
85 Database(Arc::new(Target {
86 namespace: config.get_dbname().map(str::to_owned),
87 server,
88 }))
89 }
90
91 fn call<'a>(&'a self, analysis: &'a Analysis) -> Call<'a> {
92 Call {
93 system: POSTGRESQL,
94 namespace: self.0.namespace.as_deref(),
95 server: self.0.server.as_ref().map(|(a, p)| (a.as_str(), *p)),
96 analysis,
97 }
98 }
99}
100
101async fn record<R>(
104 database: &Database,
105 analysis: &Analysis,
106 operation: impl Future<Output = Result<R, Error>>,
107) -> Result<R, Error> {
108 let call = database.call(analysis);
109 let span = call.span();
110 let started = Instant::now();
111 let result = operation.instrument(span.clone()).await;
112 let seconds = started.elapsed().as_secs_f64();
113 let _entered = span.enter();
115 match &result {
116 Ok(_) => call.record_duration(seconds, None),
117 Err(error) => {
118 let code = error.code().map(SqlState::code);
119 let failure = Failure {
120 error_type: code.unwrap_or(CLIENT_ERROR),
121 status_code: code,
122 };
123 failure.record(&span);
124 call.record_duration(seconds, Some(&failure));
125 }
126 }
127 result
128}
129
130#[derive(Clone)]
134pub struct Statement {
135 inner: tokio_postgres::Statement,
136 analysis: Arc<Analysis>,
137}
138
139impl Statement {
140 pub fn into_inner(self) -> tokio_postgres::Statement {
142 self.inner
143 }
144}
145
146impl Deref for Statement {
147 type Target = tokio_postgres::Statement;
148
149 fn deref(&self) -> &tokio_postgres::Statement {
150 &self.inner
151 }
152}
153
154impl std::fmt::Debug for Statement {
155 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156 f.debug_struct("Statement")
157 .field("summary", &self.analysis.summary)
158 .finish_non_exhaustive()
159 }
160}
161
162pub trait Query: sealed::Query + Sync {}
166
167impl Query for str {}
168impl Query for String {}
169impl Query for Statement {}
170impl Query for tokio_postgres::Statement {}
171
172mod sealed {
173 use crate::record::Analysis;
174
175 pub enum Target<'a> {
176 Text(&'a str),
177 Prepared(Prepared<'a>),
178 }
179
180 pub struct Prepared<'a> {
182 pub(crate) statement: &'a tokio_postgres::Statement,
183 pub(crate) analysis: &'a Analysis,
184 }
185
186 pub trait Query {
187 fn target(&self) -> Target<'_>;
188 }
189
190 impl Query for str {
191 fn target(&self) -> Target<'_> {
192 Target::Text(self)
193 }
194 }
195
196 impl Query for String {
197 fn target(&self) -> Target<'_> {
198 Target::Text(self)
199 }
200 }
201
202 impl Query for super::Statement {
203 fn target(&self) -> Target<'_> {
204 Target::Prepared(Prepared {
205 statement: &self.inner,
206 analysis: &self.analysis,
207 })
208 }
209 }
210
211 impl Query for tokio_postgres::Statement {
212 fn target(&self) -> Target<'_> {
213 Target::Prepared(Prepared {
214 statement: self,
215 analysis: &crate::record::UNKNOWN,
216 })
217 }
218 }
219}
220
221use sealed::Target as Run;
222
223macro_rules! calls {
227 () => {
228 pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
231 let inner = self.pg().prepare(query).await?;
232 Ok(Statement {
233 inner,
234 analysis: analyze(query),
235 })
236 }
237
238 pub async fn query<T>(
240 &self,
241 statement: &T,
242 params: &[&(dyn ToSql + Sync)],
243 ) -> Result<Vec<Row>, Error>
244 where
245 T: ?Sized + Query,
246 {
247 match statement.target() {
248 Run::Text(sql) => {
249 record(&self.database, &analyze(sql), self.pg().query(sql, params)).await
250 }
251 Run::Prepared(p) => {
252 record(
253 &self.database,
254 p.analysis,
255 self.pg().query(p.statement, params),
256 )
257 .await
258 }
259 }
260 }
261
262 pub async fn query_one<T>(
264 &self,
265 statement: &T,
266 params: &[&(dyn ToSql + Sync)],
267 ) -> Result<Row, Error>
268 where
269 T: ?Sized + Query,
270 {
271 match statement.target() {
272 Run::Text(sql) => {
273 record(
274 &self.database,
275 &analyze(sql),
276 self.pg().query_one(sql, params),
277 )
278 .await
279 }
280 Run::Prepared(p) => {
281 record(
282 &self.database,
283 p.analysis,
284 self.pg().query_one(p.statement, params),
285 )
286 .await
287 }
288 }
289 }
290
291 pub async fn query_opt<T>(
293 &self,
294 statement: &T,
295 params: &[&(dyn ToSql + Sync)],
296 ) -> Result<Option<Row>, Error>
297 where
298 T: ?Sized + Query,
299 {
300 match statement.target() {
301 Run::Text(sql) => {
302 record(
303 &self.database,
304 &analyze(sql),
305 self.pg().query_opt(sql, params),
306 )
307 .await
308 }
309 Run::Prepared(p) => {
310 record(
311 &self.database,
312 p.analysis,
313 self.pg().query_opt(p.statement, params),
314 )
315 .await
316 }
317 }
318 }
319
320 pub async fn execute<T>(
322 &self,
323 statement: &T,
324 params: &[&(dyn ToSql + Sync)],
325 ) -> Result<u64, Error>
326 where
327 T: ?Sized + Query,
328 {
329 match statement.target() {
330 Run::Text(sql) => {
331 record(
332 &self.database,
333 &analyze(sql),
334 self.pg().execute(sql, params),
335 )
336 .await
337 }
338 Run::Prepared(p) => {
339 record(
340 &self.database,
341 p.analysis,
342 self.pg().execute(p.statement, params),
343 )
344 .await
345 }
346 }
347 }
348
349 pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
352 record(
353 &self.database,
354 &analyze(query),
355 self.pg().batch_execute(query),
356 )
357 .await
358 }
359
360 pub async fn simple_query(&self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
362 record(
363 &self.database,
364 &analyze(query),
365 self.pg().simple_query(query),
366 )
367 .await
368 }
369 };
370}
371
372pub struct Client<C = tokio_postgres::Client> {
376 inner: C,
377 database: Database,
378 _lease: Option<Lease>,
381}
382
383#[cfg(feature = "deadpool-postgres")]
385use crate::pool::Lease;
386#[cfg(not(feature = "deadpool-postgres"))]
387type Lease = std::convert::Infallible;
388
389pub trait AsClient {
392 fn as_client(&self) -> &tokio_postgres::Client;
394 fn as_client_mut(&mut self) -> &mut tokio_postgres::Client;
396}
397
398impl AsClient for tokio_postgres::Client {
399 fn as_client(&self) -> &tokio_postgres::Client {
400 self
401 }
402
403 fn as_client_mut(&mut self) -> &mut tokio_postgres::Client {
404 self
405 }
406}
407
408impl<C: AsClient> Client<C> {
409 pub fn new(client: C, config: &tokio_postgres::Config) -> Self {
411 Self::with_database(client, &Database::new(config))
412 }
413
414 pub fn with_database(client: C, database: &Database) -> Self {
418 Client {
419 inner: client,
420 database: database.clone(),
421 _lease: None,
422 }
423 }
424
425 pub fn get_ref(&self) -> &C {
427 &self.inner
428 }
429
430 pub fn into_inner(self) -> C {
433 self.inner
434 }
435
436 fn pg(&self) -> &tokio_postgres::Client {
437 self.inner.as_client()
438 }
439
440 calls!();
441
442 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
444 let database = self.database.clone();
445 let inner = record(
446 &database,
447 &analyze("BEGIN"),
448 self.inner.as_client_mut().transaction(),
449 )
450 .await?;
451 Ok(Transaction { inner, database })
452 }
453}
454
455impl<C: AsClient> Deref for Client<C> {
456 type Target = tokio_postgres::Client;
457
458 fn deref(&self) -> &tokio_postgres::Client {
459 self.inner.as_client()
460 }
461}
462
463impl<C: AsClient> DerefMut for Client<C> {
464 fn deref_mut(&mut self) -> &mut tokio_postgres::Client {
465 self.inner.as_client_mut()
466 }
467}
468
469impl<C> std::fmt::Debug for Client<C> {
470 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
471 f.debug_struct("Client")
472 .field("database", &self.database)
473 .finish_non_exhaustive()
474 }
475}
476
477pub struct Transaction<'a> {
482 inner: tokio_postgres::Transaction<'a>,
483 database: Database,
484}
485
486impl<'a> Transaction<'a> {
487 fn pg(&self) -> &tokio_postgres::Transaction<'a> {
488 &self.inner
489 }
490
491 calls!();
492
493 pub async fn commit(self) -> Result<(), Error> {
495 record(&self.database, &analyze("COMMIT"), self.inner.commit()).await
496 }
497
498 pub async fn rollback(self) -> Result<(), Error> {
500 record(&self.database, &analyze("ROLLBACK"), self.inner.rollback()).await
501 }
502
503 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
505 let database = self.database.clone();
506 let inner = record(&database, &analyze("SAVEPOINT"), self.inner.transaction()).await?;
507 Ok(Transaction { inner, database })
508 }
509}
510
511impl<'a> Deref for Transaction<'a> {
512 type Target = tokio_postgres::Transaction<'a>;
513
514 fn deref(&self) -> &tokio_postgres::Transaction<'a> {
515 &self.inner
516 }
517}
518
519impl std::fmt::Debug for Transaction<'_> {
520 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
521 f.debug_struct("Transaction")
522 .field("database", &self.database)
523 .finish_non_exhaustive()
524 }
525}
526
527pub trait GenericClient: Sync {
530 fn prepare(&self, query: &str) -> impl Future<Output = Result<Statement, Error>> + Send;
532
533 fn query<T>(
535 &self,
536 statement: &T,
537 params: &[&(dyn ToSql + Sync)],
538 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
539 where
540 T: ?Sized + Query;
541
542 fn query_one<T>(
544 &self,
545 statement: &T,
546 params: &[&(dyn ToSql + Sync)],
547 ) -> impl Future<Output = Result<Row, Error>> + Send
548 where
549 T: ?Sized + Query;
550
551 fn query_opt<T>(
553 &self,
554 statement: &T,
555 params: &[&(dyn ToSql + Sync)],
556 ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
557 where
558 T: ?Sized + Query;
559
560 fn execute<T>(
562 &self,
563 statement: &T,
564 params: &[&(dyn ToSql + Sync)],
565 ) -> impl Future<Output = Result<u64, Error>> + Send
566 where
567 T: ?Sized + Query;
568
569 fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send;
571}
572
573macro_rules! generic_client {
575 () => {
576 fn prepare(&self, query: &str) -> impl Future<Output = Result<Statement, Error>> + Send {
577 Self::prepare(self, query)
578 }
579
580 fn query<T>(
581 &self,
582 statement: &T,
583 params: &[&(dyn ToSql + Sync)],
584 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
585 where
586 T: ?Sized + Query,
587 {
588 Self::query(self, statement, params)
589 }
590
591 fn query_one<T>(
592 &self,
593 statement: &T,
594 params: &[&(dyn ToSql + Sync)],
595 ) -> impl Future<Output = Result<Row, Error>> + Send
596 where
597 T: ?Sized + Query,
598 {
599 Self::query_one(self, statement, params)
600 }
601
602 fn query_opt<T>(
603 &self,
604 statement: &T,
605 params: &[&(dyn ToSql + Sync)],
606 ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
607 where
608 T: ?Sized + Query,
609 {
610 Self::query_opt(self, statement, params)
611 }
612
613 fn execute<T>(
614 &self,
615 statement: &T,
616 params: &[&(dyn ToSql + Sync)],
617 ) -> impl Future<Output = Result<u64, Error>> + Send
618 where
619 T: ?Sized + Query,
620 {
621 Self::execute(self, statement, params)
622 }
623
624 fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send {
625 Self::batch_execute(self, query)
626 }
627 };
628}
629
630impl<C: AsClient + Sync> GenericClient for Client<C> {
631 generic_client!();
632}
633
634impl GenericClient for Transaction<'_> {
635 generic_client!();
636}
637
638#[cfg(feature = "deadpool-postgres")]
639mod pool {
640 use super::*;
641
642 impl AsClient for deadpool_postgres::Object {
643 fn as_client(&self) -> &tokio_postgres::Client {
644 self
645 }
646
647 fn as_client_mut(&mut self) -> &mut tokio_postgres::Client {
648 self
649 }
650 }
651
652 impl Client<deadpool_postgres::Object> {
653 pub async fn prepare_cached(&self, query: &str) -> Result<Statement, Error> {
656 let inner = self.inner.prepare_cached(query).await?;
657 Ok(Statement {
658 inner,
659 analysis: analyze(query),
660 })
661 }
662 }
663
664 #[derive(Clone)]
683 pub struct Pool {
684 inner: deadpool_postgres::Pool,
685 database: Database,
686 name: Arc<str>,
687 }
688
689 impl Pool {
690 pub fn new(pool: deadpool_postgres::Pool, config: &tokio_postgres::Config) -> Self {
694 crate::pool::describe_metrics();
695 let database = Database::new(config);
696 let name = crate::pool::default_name(
697 POSTGRESQL,
698 database.0.namespace.as_deref(),
699 database.0.server.as_ref().map(|(a, p)| (a.as_str(), *p)),
700 );
701 Pool {
702 inner: pool,
703 database,
704 name: name.into(),
705 }
706 }
707
708 pub fn with_name(mut self, name: impl Into<String>) -> Self {
710 self.name = name.into().into();
711 self
712 }
713
714 pub async fn get(
716 &self,
717 ) -> Result<Client<deadpool_postgres::Object>, deadpool_postgres::PoolError> {
718 let waiting = crate::pool::Waiting::start(&self.name);
719 let started = Instant::now();
720 let result = self.inner.get().await;
721 drop(waiting);
722 let timed_out = matches!(&result, Err(deadpool_postgres::PoolError::Timeout(_)));
723 crate::pool::record_wait(&self.name, started, timed_out);
724 sample(&self.inner, &self.name);
725 let client = result?;
726 let (pool, name) = (self.inner.clone(), Arc::clone(&self.name));
727 Ok(Client {
728 inner: client,
729 database: self.database.clone(),
730 _lease: Some(Lease::start(&self.name, move || sample(&pool, &name))),
731 })
732 }
733 }
734
735 fn sample(pool: &deadpool_postgres::Pool, name: &str) {
737 let status = pool.status();
738 crate::pool::record_counts(
739 name,
740 status.available,
741 status.size.saturating_sub(status.available),
742 status.max_size,
743 );
744 }
745
746 impl Deref for Pool {
747 type Target = deadpool_postgres::Pool;
748
749 fn deref(&self) -> &deadpool_postgres::Pool {
750 &self.inner
751 }
752 }
753
754 impl std::fmt::Debug for Pool {
755 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
756 f.debug_struct("Pool")
757 .field("database", &self.database)
758 .finish_non_exhaustive()
759 }
760 }
761}
762
763#[cfg(feature = "deadpool-postgres")]
764pub use pool::Pool;