Skip to content

Commit

Permalink
Bugfix when passing empty list to where
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieuprog committed Aug 31, 2023
1 parent 4db96f0 commit c426d66
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/query_builder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,10 @@ defmodule QueryBuilder do
"""
def where(query, assoc_fields, filters, or_filters \\ [])

def where(%QueryBuilder.Query{} = query, _assoc_fields, [], []) do
query
end

def where(%QueryBuilder.Query{} = query, assoc_fields, filters, or_filters) do
%{query | operations: [%{type: :where, assocs: assoc_fields, args: [filters, or_filters]} | query.operations]}
end
Expand Down Expand Up @@ -293,6 +297,10 @@ defmodule QueryBuilder do
QueryBuilder.order_by(query, :articles, asc: :title@articles)
```
"""
def order_by(%QueryBuilder.Query{} = query, _assoc_fields, []) do
query
end

def order_by(%QueryBuilder.Query{} = query, assoc_fields, value) do
%{query | operations: [%{type: :order_by, assocs: assoc_fields, args: [value]} | query.operations]}
end
Expand Down
25 changes: 25 additions & 0 deletions test/query_builder_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,22 @@ defmodule QueryBuilderTest do
assert 2 == length(articles_excluding_tags)
end

test "empty where" do
all_users =
User
|> QueryBuilder.where([])
|> Repo.all()

assert 9 == length(all_users)

result =
User
|> QueryBuilder.where([], [], or: [name: "Bob", deleted: false])
|> Repo.all()

assert 1 == length(result)
end

test "where with or groups" do
result =
User
Expand Down Expand Up @@ -426,6 +442,15 @@ defmodule QueryBuilderTest do
assert hd(alice.authored_articles).title == "MINT, A NEW HTTP CLIENT FOR ELIXIR"
end

test "empty order_by" do
all_users =
User
|> QueryBuilder.order_by([])
|> Repo.all()

assert 9 == length(all_users)
end

test "order_by with fragment" do
character_length = fn (field, get_binding_fun) ->
{field, binding} = get_binding_fun.(field)
Expand Down

0 comments on commit c426d66

Please sign in to comment.