Skip to content

Commit

Permalink
add tracing to query execution
Browse files Browse the repository at this point in the history
  • Loading branch information
rkusa committed Dec 2, 2023
1 parent 17ef501 commit 58b6a29
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
1 change: 1 addition & 0 deletions postgres/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ sqlm-postgres-macros = { path = "../postgres-macros", default-features = false }
time = { version = "0.3", optional = true }
tokio-postgres = "0.7"
tokio-postgres-rustls = "0.10"
tracing = "0.1"
uuid = { version = "1.4", optional = true }

[dev-dependencies]
Expand Down
39 changes: 27 additions & 12 deletions postgres/src/future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ use std::future::{Future, IntoFuture};
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;

use tracing::Instrument;

use crate::query::Query;
use crate::{Error, Sql};
Expand All @@ -15,22 +18,34 @@ where
type IntoFuture = SqlFuture<'a, T>;

fn into_future(self) -> Self::IntoFuture {
let span =
tracing::debug_span!("sql query", query = self.query, parameters = ?self.parameters);
let start = Instant::now();

SqlFuture {
future: Box::pin(async move {
let mut i = 1;
loop {
match T::query(&self).await {
Ok(r) => return Ok(r),
Err(Error::Postgres(err)) if err.is_closed() && i <= 5 => {
// retry pool size + 1 times if connection is closed (might have
// received a closed one from the connection pool)
i += 1;
continue;
future: Box::pin(
async move {
let mut i = 1;
loop {
match T::query(&self).await {
Ok(r) => {
let elapsed = start.elapsed();
tracing::debug!(?elapsed, "sql query finished");
return Ok(r);
}
Err(Error::Postgres(err)) if err.is_closed() && i <= 5 => {
// retry pool size + 1 times if connection is closed (might have
// received a closed one from the connection pool)
i += 1;
tracing::debug!("retry due to connection closed error");
continue;
}
Err(err) => return Err(err),
}
Err(err) => return Err(err),
}
}
}),
.instrument(span),
),
marker: PhantomData,
}
}
Expand Down

0 comments on commit 58b6a29

Please sign in to comment.