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
11 changes: 11 additions & 0 deletions src/backend/mysql/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,17 @@ impl QueryBuilder for MysqlQueryBuilder {

fn prepare_returning(&self, _returning: &Option<ReturningClause>, _sql: &mut dyn SqlWriter) {}

fn prepare_exception_statement(&self, exception: &ExceptionStatement, sql: &mut dyn SqlWriter) {
let mut quoted_exception_message = String::new();
self.write_string_quoted(&exception.message, &mut quoted_exception_message);
write!(
sql,
"SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = {}",
quoted_exception_message
)
.unwrap();
}

fn random_function(&self) -> &str {
"RAND"
}
Expand Down
6 changes: 6 additions & 0 deletions src/backend/postgres/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,12 @@ impl QueryBuilder for PostgresQueryBuilder {
sql.push_param(value.clone(), self as _);
}

fn prepare_exception_statement(&self, exception: &ExceptionStatement, sql: &mut dyn SqlWriter) {
let mut quoted_exception_message = String::new();
self.write_string_quoted(&exception.message, &mut quoted_exception_message);
write!(sql, "RAISE EXCEPTION {}", quoted_exception_message).unwrap();
}

fn write_string_quoted(&self, string: &str, buffer: &mut String) {
let escaped = self.escape_string(string);
let string = if escaped.find('\\').is_some() {
Expand Down
12 changes: 12 additions & 0 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,9 @@ pub trait QueryBuilder:
SimpleExpr::Constant(val) => {
self.prepare_constant(val, sql);
}
SimpleExpr::Exception(val) => {
self.prepare_exception_statement(val, sql);
}
}
}

Expand Down Expand Up @@ -1051,6 +1054,15 @@ pub trait QueryBuilder:
}
}

// Translate [`Exception`] into SQL statement.
fn prepare_exception_statement(
&self,
_exception: &ExceptionStatement,
_sql: &mut dyn SqlWriter,
) {
panic!("Exception handling not implemented for this backend");
}
Comment on lines +1057 to +1064
Copy link
Member

@Expurple Expurple May 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, this doesn't look good to me. Why make it a provided method if you don't, in fact... provide it?

To me, such a provided method would look OK if it returned Result<(), ExceptionsNotImplemented> instead of panicking. But I see that the calling prepare_simple_expr_common doesn't return a Result anyway. Perhaps, we've hit some problem/limitation of the sea_query design that I don't fully understand yet. Perhaps, we shouldn't even try to pretend that exceptions are a portable and universally-supported feature (see #829 (comment))


/// Convert a SQL value into syntax-specific string
fn value_to_string(&self, v: &Value) -> String {
self.value_to_string_common(v)
Expand Down
6 changes: 6 additions & 0 deletions src/backend/sqlite/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ impl QueryBuilder for SqliteQueryBuilder {
"MIN"
}

fn prepare_exception_statement(&self, exception: &ExceptionStatement, sql: &mut dyn SqlWriter) {
let mut quoted_exception_message = String::new();
self.write_string_quoted(&exception.message, &mut quoted_exception_message);
write!(sql, "SELECT RAISE(ABORT, {})", quoted_exception_message).unwrap();
}

fn char_length_function(&self) -> &str {
"LENGTH"
}
Expand Down
46 changes: 46 additions & 0 deletions src/exception.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//! Custom SQL exceptions and errors
use inherent::inherent;

use crate::backend::SchemaBuilder;

/// SQL Exceptions
#[derive(Debug, Clone, PartialEq)]
pub struct ExceptionStatement {
pub(crate) message: String,
}
Comment on lines +6 to +10
Copy link
Member

@Expurple Expurple May 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I look at the PostgreSQL docs, I'd rather have a powerful Postgres-specific PgRaiseStatement with an explicit

#[non_exhaustive]
pub enum PgRaiseLevel {
    Exception,
    ..
}

where later we could extend PgRaiseStatement in a backwards-compatible way and add methods for format args, SQLSTATE and USING (I'm not asking to contribute everything under the sun in this one PR).

We can keep your minimal "portable" API too, if you document that it's not a portable SQL feature, but an "artifitial" shortcut for the common subset of database-specific exception features. Which all seem very different from each other, judging by the SQL you generate in the implementation. And obviously, it'd switch the implementation to just delegate to the database-specific query builder: PgRaiseStatement, etc.

Personally, I develop against Postgres and don't care about portability. But I'm not sure how much the SeaQL community cares in general


impl ExceptionStatement {
pub fn new(message: String) -> Self {
Self { message }
}
}

pub trait ExceptionStatementBuilder {
/// Build corresponding SQL statement for certain database backend and return SQL string
fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String;

/// Build corresponding SQL statement for certain database backend and return SQL string
fn build_any(&self, schema_builder: &dyn SchemaBuilder) -> String;

/// Build corresponding SQL statement for certain database backend and return SQL string
fn to_string<T: SchemaBuilder>(&self, schema_builder: T) -> String {
self.build(schema_builder)
}
}

#[inherent]
impl ExceptionStatementBuilder for ExceptionStatement {
pub fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String {
let mut sql = String::with_capacity(256);
schema_builder.prepare_exception_statement(self, &mut sql);
sql
}

pub fn build_any(&self, schema_builder: &dyn SchemaBuilder) -> String {
let mut sql = String::with_capacity(256);
schema_builder.prepare_exception_statement(self, &mut sql);
sql
}

pub fn to_string<T: SchemaBuilder>(&self, schema_builder: T) -> String;
}
3 changes: 2 additions & 1 deletion src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//!
//! [`SimpleExpr`] is the expression common among select fields, where clauses and many other places.

use crate::{func::*, query::*, types::*, value::*};
use crate::{exception::ExceptionStatement, func::*, query::*, types::*, value::*};

/// Helper to build a [`SimpleExpr`].
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -35,6 +35,7 @@ pub enum SimpleExpr {
AsEnum(DynIden, Box<SimpleExpr>),
Case(Box<CaseStatement>),
Constant(Value),
Exception(ExceptionStatement),
}

/// "Operator" methods for building expressions.
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -809,6 +809,7 @@

pub mod backend;
pub mod error;
pub mod exception;
pub mod expr;
pub mod extension;
pub mod foreign_key;
Expand All @@ -827,6 +828,7 @@ pub mod value;
pub mod tests_cfg;

pub use backend::*;
pub use exception::*;
pub use expr::*;
pub use foreign_key::*;
pub use func::*;
Expand Down
20 changes: 20 additions & 0 deletions tests/mysql/exception.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use super::*;
use pretty_assertions::assert_eq;

#[test]
fn signal_sqlstate() {
let message = "Some error occurred";
assert_eq!(
ExceptionStatement::new(message.to_string()).to_string(MysqlQueryBuilder),
format!("SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '{message}'")
);
}

#[test]
fn escapes_message() {
let unescaped_message = "Does this 'break'?";
assert_eq!(
ExceptionStatement::new(unescaped_message.to_string()).to_string(MysqlQueryBuilder),
format!("SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Does this \\'break\\'?'")
);
}
1 change: 1 addition & 0 deletions tests/mysql/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use sea_query::{extension::mysql::*, tests_cfg::*, *};

mod exception;
mod foreign_key;
mod index;
mod query;
Expand Down
20 changes: 20 additions & 0 deletions tests/postgres/exception.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use super::*;
use pretty_assertions::assert_eq;

#[test]
fn raise_exception() {
let message = "Some error occurred";
assert_eq!(
ExceptionStatement::new(message.to_string()).to_string(PostgresQueryBuilder),
format!("RAISE EXCEPTION '{message}'")
);
}

#[test]
fn escapes_message() {
let unescaped_message = "Does this 'break'?";
assert_eq!(
ExceptionStatement::new(unescaped_message.to_string()).to_string(PostgresQueryBuilder),
format!("RAISE EXCEPTION E'Does this \\'break\\'?'")
);
}
1 change: 1 addition & 0 deletions tests/postgres/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use sea_query::{tests_cfg::*, *};

mod exception;
mod foreign_key;
mod index;
mod query;
Expand Down
21 changes: 21 additions & 0 deletions tests/sqlite/exception.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use super::*;
use pretty_assertions::assert_eq;

#[test]
fn select_raise_abort() {
let message = "Some error occurred here";
assert_eq!(
ExceptionStatement::new(message.to_string()).to_string(SqliteQueryBuilder),
format!("SELECT RAISE(ABORT, '{}')", message)
);
}

#[test]
fn escapes_message() {
let unescaped_message = "Does this 'break'?";
let escaped_message = "Does this ''break''?";
assert_eq!(
ExceptionStatement::new(unescaped_message.to_string()).to_string(SqliteQueryBuilder),
format!("SELECT RAISE(ABORT, '{}')", escaped_message)
);
}
1 change: 1 addition & 0 deletions tests/sqlite/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use sea_query::{tests_cfg::*, *};

mod exception;
mod foreign_key;
mod index;
mod query;
Expand Down
Loading