Skip to content

Commit

Permalink
Postgres: set generic execution plan only in query macro
Browse files Browse the repository at this point in the history
  • Loading branch information
joeydewaal committed Oct 10, 2024
1 parent 12c2986 commit 0e2ec96
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 28 deletions.
22 changes: 21 additions & 1 deletion sqlx-macros-core/src/database/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,27 @@ impl<DB: DatabaseExt> CachingDescribeBlocking<DB> {
let conn = match cache.entry(database_url.to_string()) {
hash_map::Entry::Occupied(hit) => hit.into_mut(),
hash_map::Entry::Vacant(miss) => {
miss.insert(DB::Connection::connect(database_url).await?)
let conn = miss.insert(DB::Connection::connect(database_url).await?);

#[cfg(feature = "postgres")]
if DB::NAME == sqlx_postgres::Postgres::NAME {
conn.execute(
"
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM pg_settings
WHERE name = 'plan_cache_mode'
) THEN
SET SESSION plan_cache_mode = 'force_generic_plan';
END IF;
END $$;
",
)
.await?;
}
conn
}
};

Expand Down
31 changes: 4 additions & 27 deletions sqlx-postgres/src/connection/describe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,8 @@ use crate::types::Oid;
use crate::HashMap;
use crate::{PgColumn, PgConnection, PgTypeInfo};
use futures_core::future::BoxFuture;
use futures_util::TryFutureExt;
use smallvec::SmallVec;
use sqlx_core::executor::Executor;
use sqlx_core::from_row::FromRow;
use sqlx_core::query_builder::QueryBuilder;
use sqlx_core::raw_sql::raw_sql;
use std::sync::Arc;

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

let mut explain = format!(
"
BEGIN;
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM pg_settings
WHERE name = 'plan_cache_mode'
) THEN
SET LOCAL plan_cache_mode = 'force_generic_plan';
END IF;
END $$;
EXPLAIN (VERBOSE, FORMAT JSON) EXECUTE {stmt_id_display}
"
);
let mut explain = format!("EXPLAIN (VERBOSE, FORMAT JSON) EXECUTE {stmt_id_display}");
let mut comma = false;

if params_len > 0 {
Expand All @@ -554,15 +535,11 @@ WHERE rngtypid = $1
comma = true;
}

explain += ");
ROLLBACK;
";
explain += ")";
}

let (Json(explains),): (Json<SmallVec<[Explain; 1]>>,) = self
.fetch_one(raw_sql(&explain))
.map_ok(|row| FromRow::from_row(&row))
.await??;
let (Json(explains),): (Json<SmallVec<[Explain; 1]>>,) =
query_as(&explain).fetch_one(self).await?;

let mut nullables = Vec::new();

Expand Down

0 comments on commit 0e2ec96

Please sign in to comment.