Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/database/db_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,42 @@ impl DatabaseConnection {
}
}

/// Set the default persistent prepared statement caching behavior
///
/// When set to Some(false), prepared statement caching will be disabled by default
/// unless explicitly enabled on individual queries.
/// When set to Some(true), prepared statement caching will be enabled by default.
/// When set to None, uses sqlx default behavior (enabled).
///
/// This is particularly useful when using `from_sqlx_*_pool` methods to create
/// a connection from an existing sqlx pool.
///
/// # Examples
///
/// ```ignore
/// let pool = MySqlPoolOptions::new().connect("mysql://...").await?;
/// let mut db = Database::connect_with_pool(pool);
/// db.with_default_persistent(false); // Disable statement caching by default
/// ```
pub fn with_default_persistent(&mut self, value: bool) -> &mut Self {
match self {
#[cfg(feature = "sqlx-mysql")]
DatabaseConnection::SqlxMySqlPoolConnection(conn) => {
conn.with_default_persistent(value);
}
#[cfg(feature = "sqlx-postgres")]
DatabaseConnection::SqlxPostgresPoolConnection(conn) => {
conn.with_default_persistent(value);
}
#[cfg(feature = "sqlx-sqlite")]
DatabaseConnection::SqlxSqlitePoolConnection(conn) => {
conn.with_default_persistent(value);
}
_ => {}
}
self
}

/// Checks if a connection to the database is still valid.
pub async fn ping(&self) -> Result<(), DbErr> {
match self {
Expand Down
28 changes: 28 additions & 0 deletions src/database/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ pub struct ConnectOptions {
/// be created using SQLx's [connect_lazy](https://docs.rs/sqlx/latest/sqlx/struct.Pool.html#method.connect_lazy)
/// method.
pub(crate) connect_lazy: bool,
/// Default value for prepared statement caching when not explicitly set on queries
/// None means use sqlx default (true), Some(false) disables by default, Some(true) enables by default
pub(crate) default_persistent: Option<bool>,
#[cfg(feature = "sqlx-mysql")]
#[debug(skip)]
pub(crate) mysql_opts_fn:
Expand Down Expand Up @@ -194,6 +197,7 @@ impl ConnectOptions {
schema_search_path: None,
test_before_acquire: true,
connect_lazy: false,
default_persistent: None,
#[cfg(feature = "sqlx-mysql")]
mysql_opts_fn: None,
#[cfg(feature = "sqlx-postgres")]
Expand Down Expand Up @@ -353,6 +357,30 @@ impl ConnectOptions {
self.connect_lazy
}

/// Set the default persistent prepared statement caching behavior
///
/// When set to Some(false), prepared statement caching will be disabled by default
/// unless explicitly enabled on individual queries.
/// When set to Some(true), prepared statement caching will be enabled by default.
/// When set to None, uses sqlx default behavior (enabled).
///
/// # Examples
///
/// ```
/// # use sea_orm::ConnectOptions;
/// let mut opt = ConnectOptions::new("protocol://localhost/database");
/// opt.default_persistent(false); // Disable statement caching by default
/// ```
pub fn default_persistent(&mut self, value: bool) -> &mut Self {
self.default_persistent = Some(value);
self
}

/// Get the default persistent prepared statement caching behavior
pub fn get_default_persistent(&self) -> Option<bool> {
self.default_persistent
}

#[cfg(feature = "sqlx-mysql")]
#[cfg_attr(docsrs, doc(cfg(feature = "sqlx-mysql")))]
/// Apply a function to modify the underlying [`MySqlConnectOptions`] before
Expand Down
5 changes: 5 additions & 0 deletions src/database/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ pub struct Statement {
/// The database backend this statement is constructed for.
/// The SQL dialect and values should be valid for the DbBackend.
pub db_backend: DbBackend,
/// Whether to use prepared statement caching (persistent prepared statements)
/// None means use the default behavior, Some(true) enables caching, Some(false) disables it
pub persistent: Option<bool>,
}

/// Any type that can build a [Statement]
Expand All @@ -31,6 +34,7 @@ impl Statement {
sql: stmt.into(),
values: None,
db_backend,
persistent: None,
}
}

Expand All @@ -52,6 +56,7 @@ impl Statement {
sql: stmt.0.into(),
values: Some(stmt.1),
db_backend,
persistent: None,
}
}
}
Expand Down
33 changes: 29 additions & 4 deletions src/database/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub struct DatabaseTransaction {
backend: DbBackend,
open: bool,
metric_callback: Option<crate::metric::Callback>,
default_persistent: Option<bool>,
}

impl std::fmt::Debug for DatabaseTransaction {
Expand All @@ -35,12 +36,14 @@ impl DatabaseTransaction {
metric_callback: Option<crate::metric::Callback>,
isolation_level: Option<IsolationLevel>,
access_mode: Option<AccessMode>,
default_persistent: Option<bool>,
) -> Result<DatabaseTransaction, DbErr> {
let res = DatabaseTransaction {
conn,
backend,
open: true,
metric_callback,
default_persistent,
};
match *res.conn.lock().await {
#[cfg(feature = "sqlx-mysql")]
Expand Down Expand Up @@ -246,9 +249,14 @@ impl ConnectionTrait for DatabaseTransaction {

#[instrument(level = "trace")]
#[allow(unused_variables)]
async fn execute(&self, stmt: Statement) -> Result<ExecResult, DbErr> {
async fn execute(&self, mut stmt: Statement) -> Result<ExecResult, DbErr> {
debug_print!("{}", stmt);

// Apply default persistent if not explicitly set
if stmt.persistent.is_none() {
stmt.persistent = self.default_persistent;
}

match &mut *self.conn.lock().await {
#[cfg(feature = "sqlx-mysql")]
InnerConnection::MySql(conn) => {
Expand Down Expand Up @@ -335,9 +343,14 @@ impl ConnectionTrait for DatabaseTransaction {

#[instrument(level = "trace")]
#[allow(unused_variables)]
async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, DbErr> {
async fn query_one(&self, mut stmt: Statement) -> Result<Option<QueryResult>, DbErr> {
debug_print!("{}", stmt);

// Apply default persistent if not explicitly set
if stmt.persistent.is_none() {
stmt.persistent = self.default_persistent;
}

match &mut *self.conn.lock().await {
#[cfg(feature = "sqlx-mysql")]
InnerConnection::MySql(conn) => {
Expand Down Expand Up @@ -380,9 +393,14 @@ impl ConnectionTrait for DatabaseTransaction {

#[instrument(level = "trace")]
#[allow(unused_variables)]
async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, DbErr> {
async fn query_all(&self, mut stmt: Statement) -> Result<Vec<QueryResult>, DbErr> {
debug_print!("{}", stmt);

// Apply default persistent if not explicitly set
if stmt.persistent.is_none() {
stmt.persistent = self.default_persistent;
}

match &mut *self.conn.lock().await {
#[cfg(feature = "sqlx-mysql")]
InnerConnection::MySql(conn) => {
Expand Down Expand Up @@ -436,9 +454,14 @@ impl StreamTrait for DatabaseTransaction {
#[instrument(level = "trace")]
fn stream<'a>(
&'a self,
stmt: Statement,
mut stmt: Statement,
) -> Pin<Box<dyn Future<Output = Result<Self::Stream<'a>, DbErr>> + 'a + Send>> {
Box::pin(async move {
// Apply default persistent if not explicitly set
if stmt.persistent.is_none() {
stmt.persistent = self.default_persistent;
}

let conn = self.conn.lock().await;
Ok(crate::TransactionStream::build(
conn,
Expand All @@ -459,6 +482,7 @@ impl TransactionTrait for DatabaseTransaction {
self.metric_callback.clone(),
None,
None,
self.default_persistent,
)
.await
}
Expand All @@ -475,6 +499,7 @@ impl TransactionTrait for DatabaseTransaction {
self.metric_callback.clone(),
isolation_level,
access_mode,
self.default_persistent,
)
.await
}
Expand Down
1 change: 1 addition & 0 deletions src/driver/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ impl crate::DatabaseTransaction {
metric_callback,
None,
None,
None,
)
.await
}
Expand Down
1 change: 1 addition & 0 deletions src/driver/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ impl crate::DatabaseTransaction {
metric_callback,
None,
None,
None,
)
.await
}
Expand Down
Loading
Loading