Skip to content

Commit

Permalink
combined queries
Browse files Browse the repository at this point in the history
  • Loading branch information
inoas committed Apr 29, 2024
1 parent 3eeaf5e commit 06befd2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
7 changes: 4 additions & 3 deletions src/cake/internal/query.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ pub type CombinedKind {
IntersectAll
}

// List of SQL parts that will be used to build a union query.
// List of SQL parts that will be used to build a combined query
// such as UNION queries.
pub type CombinedQuery {
CombinedQuery(
kind: CombinedKind,
Expand Down Expand Up @@ -113,9 +114,9 @@ pub fn combined_intersect_all_query_new(
}

pub fn combined_get_select_queries(
combined_query uq: CombinedQuery,
combined_query cq: CombinedQuery,
) -> List(SelectQuery) {
uq.select_queries
cq.select_queries
}

pub fn combined_query_set_limit(
Expand Down
16 changes: 8 additions & 8 deletions src/cake/prepared_statement_builder/union_builder.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@ import cake/prepared_statement_builder/select_builder
import gleam/list

pub fn build(
select uq: CombinedQuery,
select cq: CombinedQuery,
prepared_statement_prefix prp_stm_prfx: String,
) -> PreparedStatement {
// TODO: what happens if multiple select queries have different type signatures for their columns?
// -> In prepared statements we can already check this and return either an OK() or an Error()
// The error would return that the column types missmatch
// The user probably let assets this then?
prp_stm_prfx |> prepared_statement.new() |> apply_sql(uq)
prp_stm_prfx |> prepared_statement.new() |> apply_sql(cq)
}

pub fn apply_sql(
prepared_statement prp_stm: PreparedStatement,
select uq: CombinedQuery,
select cq: CombinedQuery,
) -> PreparedStatement {
let union_keyword = case uq.kind {
let combination = case cq.kind {
Union -> "UNION"
UnionAll -> "UNION ALL"
Except -> "EXCEPT"
Expand All @@ -32,20 +32,20 @@ pub fn apply_sql(
IntersectAll -> "INTERSECT ALL"
}

uq.select_queries
cq.select_queries
|> list.fold(
prp_stm,
fn(acc: PreparedStatement, sq: SelectQuery) -> PreparedStatement {
case acc == prp_stm {
True -> acc |> select_builder.apply_sql(sq)
False -> {
acc
|> prepared_statement.with_sql(" " <> union_keyword <> " ")
|> prepared_statement.with_sql(" " <> combination <> " ")
|> select_builder.apply_sql(sq)
}
}
},
)
|> query.limit_offset_apply(uq.limit_offset)
|> query.epilog_apply(uq.epilog)
|> query.limit_offset_apply(cq.limit_offset)
|> query.epilog_apply(cq.epilog)
}

0 comments on commit 06befd2

Please sign in to comment.