Skip to content

Commit 0e2ec96

Browse files
committed
Postgres: set generic execution plan only in query macro
1 parent 12c2986 commit 0e2ec96

File tree

2 files changed

+25
-28
lines changed

2 files changed

+25
-28
lines changed

sqlx-macros-core/src/database/mod.rs

+21-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,27 @@ impl<DB: DatabaseExt> CachingDescribeBlocking<DB> {
5454
let conn = match cache.entry(database_url.to_string()) {
5555
hash_map::Entry::Occupied(hit) => hit.into_mut(),
5656
hash_map::Entry::Vacant(miss) => {
57-
miss.insert(DB::Connection::connect(database_url).await?)
57+
let conn = miss.insert(DB::Connection::connect(database_url).await?);
58+
59+
#[cfg(feature = "postgres")]
60+
if DB::NAME == sqlx_postgres::Postgres::NAME {
61+
conn.execute(
62+
"
63+
DO $$
64+
BEGIN
65+
IF EXISTS (
66+
SELECT 1
67+
FROM pg_settings
68+
WHERE name = 'plan_cache_mode'
69+
) THEN
70+
SET SESSION plan_cache_mode = 'force_generic_plan';
71+
END IF;
72+
END $$;
73+
",
74+
)
75+
.await?;
76+
}
77+
conn
5878
}
5979
};
6080

sqlx-postgres/src/connection/describe.rs

+4-27
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,8 @@ 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;
1514
use smallvec::SmallVec;
16-
use sqlx_core::executor::Executor;
17-
use sqlx_core::from_row::FromRow;
1815
use sqlx_core::query_builder::QueryBuilder;
19-
use sqlx_core::raw_sql::raw_sql;
2016
use std::sync::Arc;
2117

2218
/// Describes the type of the `pg_type.typtype` column
@@ -523,22 +519,7 @@ WHERE rngtypid = $1
523519
.display()
524520
.ok_or_else(|| err_protocol!("cannot EXPLAIN unnamed statement: {stmt_id:?}"))?;
525521

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-
);
522+
let mut explain = format!("EXPLAIN (VERBOSE, FORMAT JSON) EXECUTE {stmt_id_display}");
542523
let mut comma = false;
543524

544525
if params_len > 0 {
@@ -554,15 +535,11 @@ WHERE rngtypid = $1
554535
comma = true;
555536
}
556537

557-
explain += ");
558-
ROLLBACK;
559-
";
538+
explain += ")";
560539
}
561540

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??;
541+
let (Json(explains),): (Json<SmallVec<[Explain; 1]>>,) =
542+
query_as(&explain).fetch_one(self).await?;
566543

567544
let mut nullables = Vec::new();
568545

0 commit comments

Comments
 (0)