From c426d6665eb1e7ec4497004814caf4dc2c0725e2 Mon Sep 17 00:00:00 2001 From: mathieuprog <5883963+mathieuprog@users.noreply.github.com> Date: Thu, 31 Aug 2023 10:56:38 +0200 Subject: [PATCH] Bugfix when passing empty list to where --- lib/query_builder.ex | 8 ++++++++ test/query_builder_test.exs | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/lib/query_builder.ex b/lib/query_builder.ex index b787a37..72516bf 100644 --- a/lib/query_builder.ex +++ b/lib/query_builder.ex @@ -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 @@ -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 diff --git a/test/query_builder_test.exs b/test/query_builder_test.exs index 82ed2c3..12edbb1 100644 --- a/test/query_builder_test.exs +++ b/test/query_builder_test.exs @@ -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 @@ -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)