1use std::sync::{Arc, Mutex};
55use std::task::{Context, Poll};
56use std::time::Instant;
57
58use futures_core::Stream;
59use futures_core::stream::BoxStream;
60
61use crate::record::{self, Analysis, Call, Failure, UNKNOWN};
62
63#[cfg(feature = "sqlx-0.8")]
64pub mod v0_8;
65#[cfg(feature = "sqlx-0.9")]
66pub mod v0_9;
67
68fn system_of(name: &str) -> &'static str {
70 match name {
71 "PostgreSQL" => "postgresql",
72 "MySQL" => "mysql",
73 "SQLite" => "sqlite",
74 _ => "other_sql",
75 }
76}
77
78fn has_url(name: &str) -> bool {
82 matches!(name, "PostgreSQL" | "MySQL" | "SQLite")
83}
84
85#[derive(Debug)]
88pub(crate) struct Target {
89 system: &'static str,
90 namespace: Option<String>,
91 server: Option<(String, u16)>,
92 pub(crate) pool_name: Arc<str>,
93}
94
95impl Target {
96 fn new(name: &str, url: Option<(Option<&str>, Option<u16>, &str)>) -> Self {
100 let system = system_of(name);
101 let (namespace, server) = match url {
102 Some((host, port, path)) if system != "sqlite" => {
103 let namespace = path.trim_start_matches('/');
104 let namespace = (!namespace.is_empty()).then(|| namespace.to_string());
105 let default_port = if system == "mysql" { 3306 } else { 5432 };
106 let server = host
107 .filter(|h| !h.is_empty())
108 .map(|h| (h.to_string(), port.unwrap_or(default_port)));
109 (namespace, server)
110 }
111 _ => (None, None),
112 };
113 let pool_name = crate::pool::default_name(
114 system,
115 namespace.as_deref(),
116 server.as_ref().map(|(a, p)| (a.as_str(), *p)),
117 );
118 Target {
119 system,
120 namespace,
121 server,
122 pool_name: pool_name.into(),
123 }
124 }
125
126 fn call<'a>(&'a self, analysis: &'a Analysis) -> Call<'a> {
127 Call {
128 system: self.system,
129 namespace: self.namespace.as_deref(),
130 server: self.server.as_ref().map(|(a, p)| (a.as_str(), *p)),
131 analysis,
132 }
133 }
134
135 fn with_pool_name(&self, name: &str) -> Self {
136 Target {
137 system: self.system,
138 namespace: self.namespace.clone(),
139 server: self.server.clone(),
140 pool_name: name.into(),
141 }
142 }
143}
144
145pub(crate) type Statement = Arc<Mutex<Option<Arc<Analysis>>>>;
148
149fn statement(analysis: Option<Arc<Analysis>>) -> Statement {
150 Arc::new(Mutex::new(analysis))
151}
152
153pub(crate) struct Fail {
155 error_type: String,
156 code: Option<String>,
157}
158
159impl Fail {
160 fn new(code: Option<String>, kind: Option<&str>) -> Self {
163 let error_type = match (&code, kind) {
164 (Some(code), _) => code.clone(),
165 (None, Some(kind)) => format!("sqlx::Error::{kind}"),
166 (None, None) => "sqlx::Error".to_string(),
167 };
168 Fail { error_type, code }
169 }
170}
171
172pub(crate) struct QueryCall {
175 target: Arc<Target>,
176 span: tracing::Span,
177 started: Instant,
178 rows: u64,
179 statement: Statement,
180 done: bool,
181}
182
183impl QueryCall {
184 fn start(target: &Arc<Target>, statement: Statement) -> Self {
185 let span = record::open_span(
186 target.system,
187 target.namespace.as_deref(),
188 target.server.as_ref().map(|(a, p)| (a.as_str(), *p)),
189 );
190 QueryCall {
191 target: Arc::clone(target),
192 span,
193 started: Instant::now(),
194 rows: 0,
195 statement,
196 done: false,
197 }
198 }
199
200 fn finish(&mut self, failure: Option<Fail>) {
201 if std::mem::replace(&mut self.done, true) {
202 return;
203 }
204 let seconds = self.started.elapsed().as_secs_f64();
205 let analysis = self
206 .statement
207 .lock()
208 .unwrap_or_else(|e| e.into_inner())
209 .take();
210 let analysis = analysis.as_deref().unwrap_or(&UNKNOWN);
211 record::describe(&self.span, analysis);
212 let failure = failure.as_ref().map(|f| Failure {
213 error_type: &f.error_type,
214 status_code: f.code.as_deref(),
215 });
216 match &failure {
217 Some(failure) => failure.record(&self.span),
218 None => {
219 self.span.record("db.response.returned_rows", self.rows);
220 }
221 }
222 let _entered = self.span.enter();
224 self.target
225 .call(analysis)
226 .record_duration(seconds, failure.as_ref());
227 }
228}
229
230impl Drop for QueryCall {
231 fn drop(&mut self) {
232 self.finish(None);
234 }
235}
236
237pub(crate) struct Recorded<'e, T, E> {
239 inner: BoxStream<'e, Result<T, E>>,
240 call: QueryCall,
241 is_row: fn(&T) -> bool,
242 fail: fn(&E) -> Fail,
243}
244
245impl<'e, T, E> Recorded<'e, T, E> {
246 fn new(
247 inner: BoxStream<'e, Result<T, E>>,
248 call: QueryCall,
249 is_row: fn(&T) -> bool,
250 fail: fn(&E) -> Fail,
251 ) -> Self {
252 Recorded {
253 inner,
254 call,
255 is_row,
256 fail,
257 }
258 }
259}
260
261impl<T, E> Stream for Recorded<'_, T, E> {
262 type Item = Result<T, E>;
263
264 fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
265 let this = self.get_mut();
266 let span = this.call.span.clone();
267 let _entered = span.enter();
268 let poll = this.inner.as_mut().poll_next(cx);
269 match &poll {
270 Poll::Ready(Some(Ok(item))) if (this.is_row)(item) => this.call.rows += 1,
271 Poll::Ready(Some(Ok(_))) | Poll::Pending => {}
272 Poll::Ready(Some(Err(error))) => this.call.finish(Some((this.fail)(error))),
273 Poll::Ready(None) => this.call.finish(None),
274 }
275 poll
276 }
277}
278
279async fn record_one<R, E>(
281 mut call: QueryCall,
282 operation: impl std::future::Future<Output = Result<R, E>>,
283 rows: fn(&R) -> u64,
284 fail: fn(&E) -> Fail,
285) -> Result<R, E> {
286 use tracing::Instrument;
287 let result = operation.instrument(call.span.clone()).await;
288 match &result {
289 Ok(value) => {
290 call.rows = rows(value);
291 call.finish(None);
292 }
293 Err(error) => call.finish(Some(fail(error))),
294 }
295 result
296}