Skip to content

Changes the where clause behavior #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 26, 2023
Merged
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ let mut select = sql::Select::new()
let is_admin = true;

if is_admin {
select = select.and("is_admin = true");
select = select.where_clause("is_admin = true");
}

let query = select.as_string();
Expand Down Expand Up @@ -141,7 +141,7 @@ fn relations(select: sql::Select) -> sql::Select {
fn conditions(select: sql::Select) -> sql::Select {
select
.where_clause("u.login = $1")
.and("o.id = $2")
.where_clause("o.id = $2")
}

fn as_string(select: sql::Select) -> String {
Expand Down
22 changes: 19 additions & 3 deletions src/behavior.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::fmt;
#[cfg(feature = "sqlite")]
use crate::structure::{InsertClause, InsertVars, UpdateClause, UpdateVars};
use crate::{fmt, structure::LogicalOperator};
use std::cmp::PartialEq;

pub trait Concat {
Expand Down Expand Up @@ -66,11 +66,17 @@ pub trait ConcatSqlStandard<Clause: PartialEq> {
query: String,
fmts: &fmt::Formatter,
clause: Clause,
items: &Vec<String>,
items: &Vec<(LogicalOperator, String)>,
) -> String {
let fmt::Formatter { lb, space, indent, .. } = fmts;
let sql = if items.is_empty() == false {
let conditions = items.join(&format!("{space}{lb}{indent}AND{space}"));
let ((_, cond), tail) = items.split_first().unwrap();

let first_condition = format!("{lb}{indent}{cond}");
let conditions = tail.iter().fold(first_condition, |acc, (log_op, condition)| {
format!("{acc}{space}{lb}{indent}{log_op}{space}{condition}")
});

format!("WHERE{space}{conditions}{space}{lb}")
} else {
"".to_owned()
Expand Down Expand Up @@ -247,6 +253,16 @@ pub trait TransactionQuery: Concat {}
/// Represents all commands that can be used inside the with method
pub trait WithQuery: Concat {}

impl std::fmt::Display for LogicalOperator {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let v = match self {
LogicalOperator::And => "AND",
LogicalOperator::Or => "OR",
};
write!(f, "{}", v)
}
}

pub fn concat_raw_before_after<Clause: PartialEq>(
items_before: &Vec<(Clause, String)>,
items_after: &Vec<(Clause, String)>,
Expand Down
74 changes: 46 additions & 28 deletions src/delete/delete.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,14 @@
use crate::{
behavior::{push_unique, Concat, TransactionQuery, WithQuery},
fmt,
structure::{Delete, DeleteClause},
structure::{Delete, DeleteClause, LogicalOperator},
};

impl WithQuery for Delete {}

impl TransactionQuery for Delete {}

impl Delete {
/// The same as [where_clause](Delete::where_clause) method, useful to write more idiomatic SQL query
///
/// # Example
///
/// ```
/// # use sql_query_builder as sql;
/// let delete = sql::Delete::new()
/// .delete_from("users")
/// .where_clause("created_at < $1")
/// .and("active = false");
///
/// # let expected = "DELETE FROM users WHERE created_at < $1 AND active = false";
/// # assert_eq!(delete.to_string(), expected);
/// ```
pub fn and(mut self, condition: &str) -> Self {
self = self.where_clause(condition);
self
}

/// Gets the current state of the [Delete] and returns it as string
///
/// # Example
Expand Down Expand Up @@ -197,22 +178,59 @@ impl Delete {
self
}

/// The `where` clause
/// The `where` clause, this method will concatenate mulltiples calls using the `and` operator.
/// If you intended to use the `or` operator you should use the [where_or](Delete::where_or) method
///
/// # Example
///
/// ```
/// # use sql_query_builder as sql;
/// let delete = sql::Delete::new()
/// .delete_from("users")
/// .where_clause("login = 'foo'")
/// .where_clause("name = 'Foo'");
/// let delete_query = sql::Delete::new()
/// .where_clause("login = $1")
/// .where_clause("status = 'deactivated'")
/// .as_string();
///
/// # let expected = "DELETE FROM users WHERE login = 'foo' AND name = 'Foo'";
/// # assert_eq!(delete.to_string(), expected);
/// # let expected = "WHERE login = $1 AND status = 'deactivated'";
/// # assert_eq!(delete_query, expected);
/// ```
///
/// Outputs
///
/// ```sql
/// WHERE
/// login = $1
/// AND status = 'deactivated'
/// ```
pub fn where_clause(mut self, condition: &str) -> Self {
push_unique(&mut self._where, condition.trim().to_owned());
push_unique(&mut self._where, (LogicalOperator::And, condition.trim().to_owned()));
self
}

/// The `where` clause that concatenate multiples calls using the OR operator.
/// If you intended to use the `and` operator you should use the [where_clause](Delete::where_clause) method
///
/// # Example
///
/// ```
/// # use sql_query_builder as sql;
/// let delete_query = sql::Delete::new()
/// .where_clause("login = 'foo'")
/// .where_or("login = 'bar'")
/// .as_string();
///
/// # let expected = "WHERE login = 'foo' OR login = 'bar'";
/// # assert_eq!(delete_query, expected);
/// ```
///
/// Output
///
/// ```sql
/// WHERE
/// login = 'foo'
/// OR login = 'bar'
/// ```
pub fn where_or(mut self, condition: &str) -> Self {
push_unique(&mut self._where, (LogicalOperator::Or, condition.trim().to_owned()));
self
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/insert/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,19 +277,19 @@ impl Insert {
/// ```
/// # use sql_query_builder as sql;
/// let query = sql::Insert::new()
/// .insert_into("users (login)")
/// .insert_into("users (login, name)")
/// .values("('foo', 'Foo')")
/// .values("('bar', 'Bar')")
/// .as_string();
///
/// # let expected = "INSERT INTO users (login) VALUES ('foo', 'Foo'), ('bar', 'Bar')";
/// # let expected = "INSERT INTO users (login, name) VALUES ('foo', 'Foo'), ('bar', 'Bar')";
/// # assert_eq!(query, expected);
/// ```
///
/// Output
///
/// ```sql
/// INSERT INTO users (login) VALUES ('foo', 'Foo'), ('bar', 'Bar')
/// INSERT INTO users (login, name) VALUES ('foo', 'Foo'), ('bar', 'Bar')
/// ```
pub fn values(mut self, value: &str) -> Self {
push_unique(&mut self._values, value.trim().to_owned());
Expand Down
125 changes: 98 additions & 27 deletions src/select/select.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,14 @@
use crate::{
behavior::{push_unique, Concat, TransactionQuery, WithQuery},
fmt,
structure::{Select, SelectClause},
structure::{LogicalOperator, Select, SelectClause},
};

impl TransactionQuery for Select {}

impl WithQuery for Select {}

impl Select {
/// The same as [where_clause](Select::where_clause) method, useful to write more idiomatic SQL query
///
/// # Example
///
/// ```
/// # use sql_query_builder as sql;
/// let select = sql::Select::new()
/// .where_clause("login = 'foo'")
/// .and("active = true");
///
/// # let expected = "WHERE login = 'foo' AND active = true";
/// # assert_eq!(select.as_string(), expected);
/// ```
pub fn and(mut self, condition: &str) -> Self {
self = self.where_clause(condition);
self
}

/// Gets the current state of the [Select] and returns it as string
///
/// # Example
Expand Down Expand Up @@ -64,7 +46,7 @@ impl Select {
/// .select("*")
/// .from("users")
/// .where_clause("login = foo")
/// .and("active = true")
/// .where_clause("active = true")
/// .debug();
/// ```
///
Expand All @@ -89,7 +71,7 @@ impl Select {
/// .from("users")
/// .debug()
/// .where_clause("login = foo")
/// .and("active = true")
/// .where_clause("active = true")
/// .as_string();
/// ```
///
Expand Down Expand Up @@ -411,20 +393,109 @@ impl Select {
self
}

/// The `where` clause
/// The `where` clause, this method will concatenate mulltiples calls using the `and` operator.
/// If you intended to use the `or` operator you should use the [where_or](Select::where_or) method
///
/// # Example
///
/// ```
/// # use sql_query_builder as sql;
/// let select = sql::Select::new()
/// .where_clause("login = $1");
/// let select_query = sql::Select::new()
/// .where_clause("login = $1")
/// .where_clause("status = 'active'")
/// .as_string();
///
/// # let expected = "WHERE login = $1";
/// # assert_eq!(select.as_string(), expected);
/// # let expected = "WHERE login = $1 AND status = 'active'";
/// # assert_eq!(select_query, expected);
/// ```
///
/// Outputs
///
/// ```sql
/// WHERE
/// login = $1
/// AND status = 'active'
/// ```
pub fn where_clause(mut self, condition: &str) -> Self {
push_unique(&mut self._where, condition.trim().to_owned());
push_unique(&mut self._where, (LogicalOperator::And, condition.trim().to_owned()));
self
}

/// The `where` clause that concatenate multiples calls using the OR operator.
/// If you intended to use the `and` operator you should use the [where_clause](Select::where_clause) method
///
/// # Example
///
/// ```
/// # use sql_query_builder as sql;
/// let select_query = sql::Select::new()
/// .where_clause("login = 'foo'")
/// .where_or("login = 'bar'")
/// .as_string();
///
/// # let expected = "WHERE login = 'foo' OR login = 'bar'";
/// # assert_eq!(select_query, expected);
/// ```
///
/// Output
///
/// ```sql
/// WHERE
/// login = 'foo'
/// OR login = 'bar'
/// ```
///
/// # Example
///
/// ```
/// # use sql_query_builder as sql;
/// let select_query = sql::Select::new()
/// .where_clause("login = 'foo'")
/// .where_or("login = 'bar'")
/// .where_clause("login = 'joe'")
/// .as_string();
///
/// # let expected = "\
/// # WHERE \
/// # login = 'foo' \
/// # OR login = 'bar' \
/// # AND login = 'joe'\
/// # ";
/// # assert_eq!(select_query, expected);
/// ```
/// Output
///
/// ```sql
/// WHERE
/// login = 'foo'
/// OR login = 'bar'
/// AND login = 'joe'
/// ```
///
/// # Example
///
/// If the `where_or` was the first clause then the operator will be ignored
///
/// ```
/// # use sql_query_builder as sql;
/// let select_query = sql::Select::new()
/// .where_or("login = 'joe'")
/// .where_clause("login = 'foo'")
/// .as_string();
///
/// # let expected = "WHERE login = 'joe' AND login = 'foo'";
/// # assert_eq!(select_query, expected);
/// ```
///
/// Output
///
/// ```sql
/// WHERE
/// login = 'joe'
/// AND login = 'foo'
/// ```
pub fn where_or(mut self, condition: &str) -> Self {
push_unique(&mut self._where, (LogicalOperator::Or, condition.trim().to_owned()));
self
}
}
Expand Down
12 changes: 9 additions & 3 deletions src/structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,20 @@ pub enum Combinator {
Union,
}

#[derive(Clone, PartialEq)]
pub enum LogicalOperator {
And,
Or,
}

/// Builder to contruct a [Delete] command
#[derive(Default, Clone)]
pub struct Delete {
pub(crate) _delete_from: String,
pub(crate) _raw_after: Vec<(DeleteClause, String)>,
pub(crate) _raw_before: Vec<(DeleteClause, String)>,
pub(crate) _raw: Vec<String>,
pub(crate) _where: Vec<String>,
pub(crate) _where: Vec<(LogicalOperator, String)>,

#[cfg(any(feature = "postgresql", feature = "sqlite"))]
pub(crate) _returning: Vec<String>,
Expand Down Expand Up @@ -127,7 +133,7 @@ pub struct Select {
pub(crate) _raw_before: Vec<(SelectClause, String)>,
pub(crate) _raw: Vec<String>,
pub(crate) _select: Vec<String>,
pub(crate) _where: Vec<String>,
pub(crate) _where: Vec<(LogicalOperator, String)>,

#[cfg(any(feature = "postgresql", feature = "sqlite"))]
pub(crate) _except: Vec<Self>,
Expand Down Expand Up @@ -223,7 +229,7 @@ pub struct Update {
pub(crate) _raw_before: Vec<(UpdateClause, String)>,
pub(crate) _raw: Vec<String>,
pub(crate) _set: Vec<String>,
pub(crate) _where: Vec<String>,
pub(crate) _where: Vec<(LogicalOperator, String)>,

#[cfg(any(feature = "postgresql", feature = "sqlite"))]
pub(crate) _from: Vec<String>,
Expand Down
Loading