Skip to content
Draft
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
47 changes: 47 additions & 0 deletions cot/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1906,6 +1906,53 @@ impl Database {
}
}

/// Executes a raw SQL query and maps the results to a model type.
///
/// Unlike [`Database::raw`], this method returns the rows as model objects
/// by applying the model's [`Model::from_db`] mapping.
///
/// # Safety
///
/// This method executes the raw SQL string without any sanitization.
/// Callers are responsible for ensuring the query is safe.
///
/// # Errors
///
/// Returns an error if the query is invalid, if the model doesn't exist in
/// the database, or if the database connection is lost.
pub async fn raw_as<T: Model>(&self, query: &str) -> Result<Vec<T>> {
let rows = self.fetch_all_raw(query).await?;
rows.into_iter().map(T::from_db).collect::<Result<_>>()
}

async fn fetch_all_raw(&self, sql: &str) -> Result<Vec<Row>> {
let result = match &*self.inner {
#[cfg(feature = "sqlite")]
DatabaseImpl::Sqlite(inner) => inner
.fetch_all_raw(sql)
.await?
.into_iter()
.map(Row::Sqlite)
.collect(),
#[cfg(feature = "postgres")]
DatabaseImpl::Postgres(inner) => inner
.fetch_all_raw(sql)
.await?
.into_iter()
.map(Row::Postgres)
.collect(),
#[cfg(feature = "mysql")]
DatabaseImpl::MySql(inner) => inner
.fetch_all_raw(sql)
.await?
.into_iter()
.map(Row::MySql)
.collect(),
};

Ok(result)
}

async fn fetch_all<T>(&self, statement: &T) -> Result<Vec<Row>>
where
T: SqlxBinder + Send + Sync,
Expand Down
15 changes: 15 additions & 0 deletions cot/src/db/sea_query_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,21 @@ macro_rules! impl_sea_query_db_backend {
self.execute_sqlx(Self::sqlx_query_with(sql, values)).await
}

pub(super) async fn fetch_all_raw(
&self,
sql: &str,
) -> crate::db::Result<Vec<$row_name>> {
tracing::debug!("Raw query: `{}`", sql);
let result = sqlx::query(sqlx::AssertSqlSafe(sql))
.fetch_all(&self.db_connection)
.await
.map_err(|err| crate::db::sea_query_db::map_sqlx_error(err))?
.into_iter()
.map($row_name::new)
.collect();
Ok(result)
}

async fn execute_sqlx<'a, A>(
&self,
sqlx_statement: sqlx::query::Query<'a, $sqlx_db_ty, A>,
Expand Down
Loading