Skip to content

Commit 12c2986

Browse files
committed
Postgres: reduce database calls in query macro's
1 parent 819f189 commit 12c2986

File tree

1 file changed

+26
-22
lines changed

1 file changed

+26
-22
lines changed

sqlx-postgres/src/connection/describe.rs

+26-22
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@ use crate::types::Oid;
1111
use crate::HashMap;
1212
use crate::{PgColumn, PgConnection, PgTypeInfo};
1313
use futures_core::future::BoxFuture;
14+
use futures_util::TryFutureExt;
1415
use smallvec::SmallVec;
15-
use sqlx_core::acquire::Acquire;
1616
use sqlx_core::executor::Executor;
17+
use sqlx_core::from_row::FromRow;
1718
use sqlx_core::query_builder::QueryBuilder;
19+
use sqlx_core::raw_sql::raw_sql;
1820
use std::sync::Arc;
1921

2022
/// Describes the type of the `pg_type.typtype` column
@@ -521,25 +523,25 @@ WHERE rngtypid = $1
521523
.display()
522524
.ok_or_else(|| err_protocol!("cannot EXPLAIN unnamed statement: {stmt_id:?}"))?;
523525

524-
let mut explain = format!("EXPLAIN (VERBOSE, FORMAT JSON) EXECUTE {stmt_id_display}");
526+
let mut explain = format!(
527+
"
528+
BEGIN;
529+
DO $$
530+
BEGIN
531+
IF EXISTS (
532+
SELECT 1
533+
FROM pg_settings
534+
WHERE name = 'plan_cache_mode'
535+
) THEN
536+
SET LOCAL plan_cache_mode = 'force_generic_plan';
537+
END IF;
538+
END $$;
539+
EXPLAIN (VERBOSE, FORMAT JSON) EXECUTE {stmt_id_display}
540+
"
541+
);
525542
let mut comma = false;
526-
let mut tx = self.begin().await?;
527543

528544
if params_len > 0 {
529-
tx.execute(
530-
" DO $$
531-
BEGIN
532-
IF EXISTS (
533-
SELECT 1
534-
FROM pg_settings
535-
WHERE name = 'plan_cache_mode'
536-
) THEN
537-
SET LOCAL plan_cache_mode = 'force_generic_plan';
538-
END IF;
539-
END $$;",
540-
)
541-
.await?;
542-
543545
explain += "(";
544546

545547
// fill the arguments list with NULL, which should theoretically be valid
@@ -552,13 +554,15 @@ WHERE rngtypid = $1
552554
comma = true;
553555
}
554556

555-
explain += ")";
557+
explain += ");
558+
ROLLBACK;
559+
";
556560
}
557561

558-
let (Json(explains),): (Json<SmallVec<[Explain; 1]>>,) =
559-
query_as(&explain).fetch_one(&mut *tx).await?;
560-
561-
tx.rollback().await?;
562+
let (Json(explains),): (Json<SmallVec<[Explain; 1]>>,) = self
563+
.fetch_one(raw_sql(&explain))
564+
.map_ok(|row| FromRow::from_row(&row))
565+
.await??;
562566

563567
let mut nullables = Vec::new();
564568

0 commit comments

Comments
 (0)