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
5 changes: 5 additions & 0 deletions src/backend/mysql/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,11 @@ impl QueryBuilder for MysqlQueryBuilder {
fn insert_default_keyword(&self) -> &str {
"()"
}

/// Prefix of the ELSEIF (MySQL)
fn elseif_keyword_prefix(&self) -> &str {
"ELSE"
}
}

impl MysqlQueryBuilder {
Expand Down
5 changes: 5 additions & 0 deletions src/backend/postgres/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,11 @@ impl QueryBuilder for PostgresQueryBuilder {
fn if_null_function(&self) -> &str {
"COALESCE"
}

/// Prefix of the ELSIF (Postgres)
fn elseif_keyword_prefix(&self) -> &str {
"ELS"
}
}

fn is_pg_comparison(b: &BinOper) -> bool {
Expand Down
27 changes: 27 additions & 0 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,9 +387,36 @@ pub trait QueryBuilder:
SimpleExpr::Constant(val) => {
self.prepare_constant(val, sql);
}
SimpleExpr::IfElse(val) => {
self.prepare_if_else_statement(val, sql);
}
}
}

/// Prefix of the ELSEIF (MySQL) vs ELSIF (Postgres) keyword
fn elseif_keyword_prefix(&self) -> &str {
panic!("ELSEIF/ELSIF keyword prefix not implemented for this backend");
}
Comment on lines +396 to +399
Copy link
Member

Choose a reason for hiding this comment

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

I don't like this panic. See #829 (comment). Although, I don't know anything about the backend design in sea_query. Maybe that's just how we do things here.

Maybe, SimpleExpr just shouldn't contain non-portable variants and we should come up with a different way of handling IfElseStatement.

@tyt2y3 @Huliiiiii, do you have any thoughts?

Copy link
Member

Choose a reason for hiding this comment

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

Yes, our usual approach is to panic when features are not supported.

There are two ways to solve this problem:

  1. Make IfElseStatement behind the feature gate
  2. Modify these kind of functions to return result (breaking)

Copy link
Member

Choose a reason for hiding this comment

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

Make IfElseStatement behind the feature gate

I think, it doesn't solve all the issues. It's nice that you won't be able to use if-else if you activate only sqlite backend. But if you activate e.g. sqlite+postgres backends, then this syntax becomes available and you can pass it to the sqlite backend and hit a runtime panic.

Ideally, it should be impossible to pass. But I'm not sure how achievable for us and convenient for the user is that. Someone needs to experiment and document the results.

Modify these kind of functions to return result (breaking)

This is a more achievable route that we could explore and see if it's annoying for the user. Sadly, I don't have time for this right now

Copy link
Author

Choose a reason for hiding this comment

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

We could implement backend specific features, closely resembling local specifics. Later then we could build a general IfElseStatement that normalizes the expression of logic and polyfills for each backend.

My personal use case for If-Else statements are triggers. Triggers could be made conditional on SQLite with WHEN clauses by splitting up the one trigger into multiple. Elsewhere our conditions could break down to CASE expressions. Would love to hear whether that would be a general direction to consider.

Meanwhile we could prepare such step by building backend specific features that only later become available globally. It would be nice to avoid panicking, but it would also be possible to solve that later by introducing a polyfill.


fn prepare_if_else_statement(&self, val: &Box<IfElseStatement>, sql: &mut dyn SqlWriter) {
write!(sql, "IF ").unwrap();
self.prepare_simple_expr(&val.when, sql);
write!(sql, " THEN\n").unwrap();
self.prepare_simple_expr(&val.then, sql);
match &val.otherwise {
Some(SimpleExpr::IfElse(value)) => {
write!(sql, "\n{}", self.elseif_keyword_prefix()).unwrap();
self.prepare_if_else_statement(value, sql);
}
Some(otherwise) => {
write!(sql, "\nELSE\n").unwrap();
self.prepare_simple_expr(otherwise, sql);
write!(sql, "\nEND IF").unwrap();
}
None => write!(sql, "\nEND IF").unwrap(),
};
}

/// Translate [`CaseStatement`] into SQL statement.
fn prepare_case_statement(&self, stmts: &CaseStatement, sql: &mut dyn SqlWriter) {
write!(sql, "(CASE").unwrap();
Expand Down
4 changes: 4 additions & 0 deletions src/backend/sqlite/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,8 @@ impl QueryBuilder for SqliteQueryBuilder {
// SQLite doesn't support inserting multiple rows with default values
write!(sql, "DEFAULT VALUES").unwrap()
}

fn prepare_if_else_statement(&self, _val: &Box<IfElseStatement>, _sql: &mut dyn SqlWriter) {
panic!("Sqlite doesn't support if-else statements")
}
}
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::{func::*, if_else::*, 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),
IfElse(Box<IfElseStatement>),
}

/// "Operator" methods for building complex expressions.
Expand Down
33 changes: 33 additions & 0 deletions src/if_else.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use crate::{QueryBuilder, SimpleExpr};

#[derive(Debug, Clone, PartialEq)]
pub struct IfElseStatement {
pub when: SimpleExpr,
pub then: SimpleExpr,
pub otherwise: Option<SimpleExpr>,
}

impl IfElseStatement {
pub fn new(when: SimpleExpr, then: SimpleExpr, otherwise: Option<SimpleExpr>) -> Self {
Self {
when,
then,
otherwise,
}
}

pub fn to_string<T: QueryBuilder>(&self, query_builder: T) -> String {
let mut sql = String::with_capacity(256);
query_builder.prepare_if_else_statement(&Box::new(self.clone()), &mut sql);
sql
}
}
pub trait IfElseStatementBuilder {
/// Build corresponding SQL statement for certain database backend and return SQL string
fn build<T: QueryBuilder>(&self, query_builder: T) -> String;

/// Build corresponding SQL statement for certain database backend and return SQL string
fn to_string<T: QueryBuilder>(&self, query_builder: T) -> String {
self.build(query_builder)
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,7 @@ pub mod expr;
pub mod extension;
pub mod foreign_key;
pub mod func;
pub mod if_else;
pub mod index;
pub mod prepare;
pub mod query;
Expand All @@ -835,6 +836,7 @@ pub use backend::*;
pub use expr::*;
pub use foreign_key::*;
pub use func::*;
pub use if_else::*;
pub use index::*;
pub use prepare::*;
pub use query::*;
Expand Down
99 changes: 99 additions & 0 deletions tests/mysql/if_else.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
use super::*;
use pretty_assertions::assert_eq;

#[rustfmt::skip]
#[test]
fn if_without_else() {
let query = Query::select().column(Asterisk).from(Glyph::Table).take();
let then = SimpleExpr::SubQuery(None, Box::new(query.into_sub_query_statement()));
let if_statement = IfElseStatement::new(
Expr::col(Glyph::Id).eq(1),
then,
None
);
assert_eq!(
if_statement.to_string(MysqlQueryBuilder),
[
"IF `id` = 1 THEN",
"(SELECT * FROM `glyph`)",
"END IF"
].join("\n")
)
}

#[rustfmt::skip]
#[test]
fn if_with_else() {
let query = Query::select().column(Asterisk).from(Glyph::Table).take();
let then = SimpleExpr::SubQuery(None, Box::new(query.into_sub_query_statement()));
let if_statement = IfElseStatement::new(
Expr::col(Glyph::Id).eq(1),
then,
Some(Expr::val("23").into()),
);
assert_eq!(
if_statement.to_string(MysqlQueryBuilder),
[
"IF `id` = 1 THEN",
"(SELECT * FROM `glyph`)",
"ELSE",
"'23'",
"END IF"
]
.join("\n")
)
}

#[test]
fn if_with_elseif() {
let query = Query::select().column(Asterisk).from(Glyph::Table).take();
let then = SimpleExpr::SubQuery(None, Box::new(query.into_sub_query_statement()));
let if_statement = IfElseStatement::new(
Expr::col(Glyph::Id).eq(1),
then,
Some(SimpleExpr::IfElse(Box::new(IfElseStatement::new(
Expr::col(Glyph::Id).eq(2),
Expr::val("42").into(),
None,
)))),
);
assert_eq!(
if_statement.to_string(MysqlQueryBuilder),
[
"IF `id` = 1 THEN",
"(SELECT * FROM `glyph`)",
"ELSEIF `id` = 2 THEN",
"'42'",
"END IF"
]
.join("\n")
)
}

#[test]
fn if_with_elseif_and_else() {
let query = Query::select().column(Asterisk).from(Glyph::Table).take();
let then = SimpleExpr::SubQuery(None, Box::new(query.into_sub_query_statement()));
let if_statement = IfElseStatement::new(
Expr::col(Glyph::Id).eq(1),
then,
Some(SimpleExpr::IfElse(Box::new(IfElseStatement::new(
Expr::col(Glyph::Id).eq(2),
Expr::val("42").into(),
Some(Expr::val("9000").into()),
)))),
);
assert_eq!(
if_statement.to_string(MysqlQueryBuilder),
[
"IF `id` = 1 THEN",
"(SELECT * FROM `glyph`)",
"ELSEIF `id` = 2 THEN",
"'42'",
"ELSE",
"'9000'",
"END IF"
]
.join("\n")
);
}
1 change: 1 addition & 0 deletions tests/mysql/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use sea_query::{extension::mysql::*, tests_cfg::*, *};

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

#[test]
#[rustfmt::skip]
fn if_without_else() {
let query = Query::select().column(Asterisk).from(Glyph::Table).take();
let then = SimpleExpr::SubQuery(None, Box::new(query.into_sub_query_statement()));
let if_statement = IfElseStatement::new(
Expr::col(Glyph::Id).eq(1),
then,
None
);
assert_eq!(
if_statement.to_string(MysqlQueryBuilder),
[
"IF `id` = 1 THEN",
"(SELECT * FROM `glyph`)",
"END IF"
].join("\n")
)
}

#[test]
#[rustfmt::skip]
fn if_with_else() {
let query = Query::select().column(Asterisk).from(Glyph::Table).take();
let then = SimpleExpr::SubQuery(None, Box::new(query.into_sub_query_statement()));
let if_statement = IfElseStatement::new(
Expr::col(Glyph::Id).eq(1),
then,
Some(Expr::val("23").into())
);
assert_eq!(
if_statement.to_string(PostgresQueryBuilder),
[
"IF \"id\" = 1 THEN",
"(SELECT * FROM \"glyph\")",
"ELSE",
"'23'",
"END IF"
].join("\n")
)
}

#[test]
#[rustfmt::skip]
fn if_with_elseif() {
let query = Query::select().column(Asterisk).from(Glyph::Table).take();
let then = SimpleExpr::SubQuery(None, Box::new(query.into_sub_query_statement()));
let if_statement = IfElseStatement::new(
Expr::col(Glyph::Id).eq(1),
then,
Some(SimpleExpr::IfElse(Box::new(IfElseStatement::new(
Expr::col(Glyph::Id).eq(2),
Expr::val("123").into(),
None
))))
);
assert_eq!(
if_statement.to_string(PostgresQueryBuilder),
[
"IF \"id\" = 1 THEN",
"(SELECT * FROM \"glyph\")",
"ELSIF \"id\" = 2 THEN",
"'123'",
"END IF"
].join("\n")
)
}
1 change: 1 addition & 0 deletions tests/postgres/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use sea_query::{tests_cfg::*, *};

mod foreign_key;
mod if_else;
mod index;
mod query;
mod table;
Expand Down
1 change: 1 addition & 0 deletions tests/sqlite/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod foreign_key;
mod index;
mod query;
mod table;
mod unsupported;

#[path = "../common.rs"]
mod common;
Expand Down
13 changes: 13 additions & 0 deletions tests/sqlite/unsupported.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use super::*;

#[test]
#[should_panic]
#[rustfmt::skip]
fn if_else_statement_is_unsupported() {
let if_statement = IfElseStatement::new(
Expr::col(Glyph::Id).eq(1),
Expr::val("23").into(),
None
);
if_statement.to_string(SqliteQueryBuilder);
}