Skip to content
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

Fix accumulator methods #33

Merged
merged 14 commits into from
Oct 30, 2024
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ description = "Write SQL queries in a simple and composable way"
documentation = "https://docs.rs/sql_query_builder"
repository = "https://github.com/belchior/sql_query_builder"
authors = ["Belchior Oliveira <[email protected]>"]
version = "2.4.0"
version = "2.4.1"
edition = "2021"
rust-version = "1.62"
license = "MIT"
keywords = ["sql", "query", "postgres", "sqlite"]
keywords = ["sql", "query", "database", "postgres", "sqlite"]

[features]
postgresql = []
Expand All @@ -20,4 +20,4 @@ rustdoc-args = ["--cfg", "docsrs"]
features = ["postgresql", "sqlite"]

[dev-dependencies]
pretty_assertions = "1.4.0"
pretty_assertions = "=1.4.0"
1 change: 1 addition & 0 deletions src/alter_table/alter_table_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ impl AlterTable {
let actions = self
._ordered_actions
.iter()
.filter(|item| item.1.is_empty() == false)
.map(|item| {
let AlterTableActionItem(action, content) = item;
match action {
Expand Down
37 changes: 27 additions & 10 deletions src/behavior.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ pub(crate) trait ConcatSqlStandard<Clause: PartialEq> {
) -> String {
let fmt::Formatter { comma, lb, space, .. } = fmts;
let sql = if items.is_empty() == false {
let tables = items.join(comma);
let tables = items
.iter()
.filter(|item| item.is_empty() == false)
.map(|item| item.as_str())
.collect::<Vec<_>>()
.join(comma);
format!("FROM{space}{tables}{space}{lb}")
} else {
"".to_string()
Expand All @@ -40,7 +45,7 @@ pub(crate) trait ConcatSqlStandard<Clause: PartialEq> {
return query;
}
let fmt::Formatter { lb, space, .. } = fmts;
let raw_sql = items.join(space);
let raw_sql = items.join(space).trim().to_string();

format!("{query}{raw_sql}{space}{lb}")
}
Expand All @@ -56,14 +61,17 @@ pub(crate) trait ConcatSqlStandard<Clause: PartialEq> {
) -> String {
let fmt::Formatter { lb, space, indent, .. } = fmts;
let sql = if items.is_empty() == false {
let ((_, cond), tail) = items.split_first().unwrap();

let first_condition = format!("{lb}{indent}{cond}");
let filtered_items = items
.iter()
.filter(|item| item.1.is_empty() == false)
.collect::<Vec<_>>();
let ((_, cond), tail) = filtered_items.split_first().unwrap();
let first_condition = format!("{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}")
format!("WHERE{lb}{space}{conditions}{space}{lb}")
} else {
"".to_string()
};
Expand All @@ -85,7 +93,12 @@ pub(crate) trait ConcatCommon<Clause: PartialEq> {
) -> String {
let fmt::Formatter { lb, space, comma, .. } = fmts;
let sql = if items.is_empty() == false {
let output_names = items.join(comma);
let output_names = items
.iter()
.filter(|item| item.is_empty() == false)
.map(|item| item.as_str())
.collect::<Vec<_>>()
.join(comma);
format!("RETURNING{space}{output_names}{space}{lb}")
} else {
"".to_string()
Expand Down Expand Up @@ -123,7 +136,11 @@ pub(crate) trait ConcatCommon<Clause: PartialEq> {
};
let query_string = query.concat(&inner_fmts);

format!("{acc}{name}{space}AS{space}({lb}{indent}{query_string}{lb}){comma}{lb}")
if query_string.is_empty() == false {
format!("{acc}{name}{space}AS{space}({lb}{indent}{query_string}{lb}){comma}{lb}")
} else {
acc
}
});
let with = &with[..with.len() - comma.len() - lb.len()];

Expand Down Expand Up @@ -228,8 +245,8 @@ pub(crate) fn concat_raw_before_after<Clause: PartialEq>(
sql: String,
) -> String {
let fmt::Formatter { space, .. } = fmts;
let raw_before = raw_queries(items_before, &clause).join(space);
let raw_after = raw_queries(items_after, &clause).join(space);
let raw_before = raw_queries(items_before, &clause).join(space).trim().to_string();
let raw_after = raw_queries(items_after, &clause).join(space).trim().to_string();
let space_after = if raw_after.is_empty() == false { space } else { "" };
let space_before = if raw_before.is_empty() == false { space } else { "" };

Expand Down
3 changes: 3 additions & 0 deletions src/create_table/create_table_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ impl CreateTable {
let columns = self
._column
.iter()
.filter(|column| column.is_empty() == false)
.map(|column| format!("{lb}{indent}{column}"))
.collect::<Vec<_>>()
.join(comma)
Expand Down Expand Up @@ -60,6 +61,7 @@ impl CreateTable {
let constraints = self
._constraint
.iter()
.filter(|constraint| constraint.is_empty() == false)
.map(|constraint| format!("{lb}{indent}CONSTRAINT{space}{constraint}"))
.collect::<Vec<_>>()
.join(comma);
Expand All @@ -80,6 +82,7 @@ impl CreateTable {
let foreign_keys = self
._foreign_key
.iter()
.filter(|foreign_key| foreign_key.is_empty() == false)
.map(|foreign_key| format!("{lb}{indent}FOREIGN KEY{foreign_key}"))
.collect::<Vec<_>>()
.join(comma);
Expand Down
10 changes: 8 additions & 2 deletions src/drop_index/drop_index_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,21 @@ impl DropIndex {
fn concat_drop_index(&self, query: String, fmts: &fmt::Formatter) -> String {
let fmt::Formatter { comma, lb, space, .. } = fmts;

let sql = if self._drop_index.len() != 0 {
let sql = if self._drop_index.is_empty() == false {
let if_exists = if self._if_exists {
format!("IF EXISTS{space}")
} else {
"".to_string()
};

let index_names = if cfg!(any(feature = "postgresql")) {
self._drop_index.join(comma)
self
._drop_index
.iter()
.filter(|item| item.is_empty() == false)
.map(|item| item.as_str())
.collect::<Vec<_>>()
.join(comma)
} else {
self._drop_index.last().unwrap().to_string()
};
Expand Down
10 changes: 8 additions & 2 deletions src/drop_table/drop_table_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,21 @@ impl DropTable {
fn concat_drop_table(&self, query: String, fmts: &fmt::Formatter) -> String {
let fmt::Formatter { comma, lb, space, .. } = fmts;

let sql = if self._drop_table.len() != 0 {
let sql = if self._drop_table.is_empty() == false {
let if_exists = if self._if_exists {
format!("IF EXISTS{space}")
} else {
"".to_string()
};

let table_names = if cfg!(any(feature = "postgresql")) {
self._drop_table.join(comma)
self
._drop_table
.iter()
.filter(|item| item.is_empty() == false)
.map(|item| item.as_str())
.collect::<Vec<_>>()
.join(comma)
} else {
self._drop_table.last().unwrap().to_string()
};
Expand Down
8 changes: 7 additions & 1 deletion src/insert/insert_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,13 @@ impl Insert {
(InsertClause::DefaultValues, format!("DEFAULT VALUES{space}{lb}"))
} else if self._values.is_empty() == false {
let sep = format!("{comma}{lb}");
let values = self._values.join(&sep);
let values = self
._values
.iter()
.filter(|item| item.is_empty() == false)
.map(|item| item.as_str())
.collect::<Vec<_>>()
.join(&sep);
(InsertClause::Values, format!("VALUES{space}{lb}{values}{space}{lb}"))
} else {
(InsertClause::Values, "".to_string())
Expand Down
24 changes: 16 additions & 8 deletions src/select/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,10 @@ impl Select {
/// ```
pub fn cross_join(mut self, table: &str) -> Self {
let table = table.trim();
let table = format!("CROSS JOIN {table}");
push_unique(&mut self._join, table);
if table.is_empty() == false {
let table = format!("CROSS JOIN {table}");
push_unique(&mut self._join, table);
}
self
}

Expand All @@ -195,8 +197,10 @@ impl Select {
/// ```
pub fn inner_join(mut self, table: &str) -> Self {
let table = table.trim();
let table = format!("INNER JOIN {table}");
push_unique(&mut self._join, table);
if table.is_empty() == false {
let table = format!("INNER JOIN {table}");
push_unique(&mut self._join, table);
}
self
}

Expand All @@ -222,8 +226,10 @@ impl Select {
/// ```
pub fn left_join(mut self, table: &str) -> Self {
let table = table.trim();
let table = format!("LEFT JOIN {table}");
push_unique(&mut self._join, table);
if table.is_empty() == false {
let table = format!("LEFT JOIN {table}");
push_unique(&mut self._join, table);
}
self
}

Expand All @@ -249,8 +255,10 @@ impl Select {
/// ```
pub fn right_join(mut self, table: &str) -> Self {
let table = table.trim();
let table = format!("RIGHT JOIN {table}");
push_unique(&mut self._join, table);
if table.is_empty() == false {
let table = format!("RIGHT JOIN {table}");
push_unique(&mut self._join, table);
}
self
}

Expand Down
44 changes: 37 additions & 7 deletions src/select/select_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,13 @@ impl Select {
fn concat_group_by(&self, query: String, fmts: &fmt::Formatter) -> String {
let fmt::Formatter { comma, lb, space, .. } = fmts;
let sql = if self._group_by.is_empty() == false {
let columns = self._group_by.join(comma);
let columns = self
._group_by
.iter()
.filter(|column| column.is_empty() == false)
.map(|column| column.as_str())
.collect::<Vec<_>>()
.join(comma);
format!("GROUP BY{space}{columns}{space}{lb}")
} else {
"".to_string()
Expand All @@ -90,7 +96,13 @@ impl Select {
fn concat_having(&self, query: String, fmts: &fmt::Formatter) -> String {
let fmt::Formatter { lb, space, .. } = fmts;
let sql = if self._having.is_empty() == false {
let conditions = self._having.join(" AND ");
let conditions = self
._having
.iter()
.filter(|item| item.is_empty() == false)
.map(|item| item.as_str())
.collect::<Vec<_>>()
.join(" AND ");
format!("HAVING{space}{conditions}{space}{lb}")
} else {
"".to_string()
Expand Down Expand Up @@ -128,7 +140,13 @@ impl Select {
fn concat_order_by(&self, query: String, fmts: &fmt::Formatter) -> String {
let fmt::Formatter { comma, lb, space, .. } = fmts;
let sql = if self._order_by.is_empty() == false {
let columns = self._order_by.join(comma);
let columns = self
._order_by
.iter()
.filter(|item| item.is_empty() == false)
.map(|item| item.as_str())
.collect::<Vec<_>>()
.join(comma);
format!("ORDER BY{space}{columns}{space}{lb}")
} else {
"".to_string()
Expand All @@ -147,7 +165,13 @@ impl Select {
fn concat_select(&self, query: String, fmts: &fmt::Formatter) -> String {
let fmt::Formatter { comma, lb, space, .. } = fmts;
let sql = if self._select.is_empty() == false {
let columns = self._select.join(comma);
let columns = self
._select
.iter()
.filter(|item| item.is_empty() == false)
.map(|item| item.as_str())
.collect::<Vec<_>>()
.join(comma);
format!("SELECT{space}{columns}{space}{lb}")
} else {
"".to_string()
Expand All @@ -166,7 +190,13 @@ impl Select {
fn concat_window(&self, query: String, fmts: &fmt::Formatter) -> String {
let fmt::Formatter { comma, lb, space, .. } = fmts;
let sql = if self._window.is_empty() == false {
let columns = self._window.join(comma);
let columns = self
._window
.iter()
.filter(|item| item.is_empty() == false)
.map(|item| item.as_str())
.collect::<Vec<_>>()
.join(comma);
format!("WINDOW{space}{columns}{space}{lb}")
} else {
"".to_string()
Expand Down Expand Up @@ -204,8 +234,8 @@ impl Select {
Combinator::Union => (SelectClause::Union, "UNION", &self._union),
};

let raw_before = raw_queries(&self._raw_before, &clause).join(space);
let raw_after = raw_queries(&self._raw_after, &clause).join(space);
let raw_before = raw_queries(&self._raw_before, &clause).join(space).trim().to_string();
let raw_after = raw_queries(&self._raw_after, &clause).join(space).trim().to_string();

let space_before = if raw_before.is_empty() {
"".to_string()
Expand Down
7 changes: 6 additions & 1 deletion src/transaction/transaction_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,12 @@ impl Transaction {
fn concat_ordered_commands(&self, query: String, fmts: &fmt::Formatter) -> String {
let fmt::Formatter { lb, space, .. } = fmts;
let sql = self._ordered_commands.iter().fold("".to_string(), |acc, cmd| {
format!("{acc}{0};{space}{lb}", cmd.concat(fmts))
let inner_cmd = cmd.concat(fmts);
if inner_cmd.is_empty() == false {
format!("{acc}{inner_cmd};{space}{lb}")
} else {
acc
}
});

format!("{query}{sql}")
Expand Down
Loading
Loading