From 0abb8e58545709fc4b63fcb41eb528e43fbbe1f8 Mon Sep 17 00:00:00 2001 From: exAspArk Date: Thu, 17 Jan 2019 15:40:58 -0500 Subject: [PATCH] Fix finding the correct value for limit and offset with where arrays --- lib/mongo_ecto/normalized_query.ex | 37 +++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/lib/mongo_ecto/normalized_query.ex b/lib/mongo_ecto/normalized_query.ex index 6d20576..e23e919 100644 --- a/lib/mongo_ecto/normalized_query.ex +++ b/lib/mongo_ecto/normalized_query.ex @@ -345,8 +345,19 @@ defmodule Mongo.Ecto.NormalizedQuery do defp offset_limit(nil, _params, _pk, _query, _where), do: nil - defp offset_limit(%Query.QueryExpr{expr: expr}, params, pk, query, where), - do: value(expr, params, pk, query, where) + defp offset_limit(%Query.QueryExpr{expr: expr}, params, pk, %Query{wheres: wheres} = query, where) do + if {:^, l, [idx]} = expr do + param_offset = + Enum.reduce(wheres, 0, fn %Query.BooleanExpr{expr: expr}, acc -> + _from..to = pair_param_range(expr) + acc + to + end) + + value({:^, l, [idx + param_offset]}, params, pk, query, where) + else + value(expr, params, pk, query, where) + end + end defp primary_key(nil), do: nil @@ -466,9 +477,10 @@ defmodule Mongo.Ecto.NormalizedQuery do {field(left, pk, query, place), ["$in": []]} end - defp pair({:in, _, [left, {:^, _, [ix, len]}]}, params, pk, query, place) do + defp pair({:in, _, [left, _]} = expr, params, pk, query, place) do args = - ix..(ix + len - 1) + expr + |> pair_param_range() |> Enum.map(&elem(params, &1)) |> Enum.map(&value(&1, params, pk, query, place)) @@ -483,9 +495,10 @@ defmodule Mongo.Ecto.NormalizedQuery do {field(left, pk, query, place), [{binary_op(op), value(right, params, pk, query, place)}]} end - defp pair({:not, _, [{:in, _, [left, {:^, _, [ix, len]}]}]}, params, pk, query, place) do + defp pair({:not, _, [{:in, _, [left, _]}]} = expr, params, pk, query, place) do args = - ix..(ix + len - 1) + expr + |> pair_param_range() |> Enum.map(&elem(params, &1)) |> Enum.map(&value(&1, params, pk, query, place)) @@ -545,4 +558,16 @@ defmodule Mongo.Ecto.NormalizedQuery do defp error(place) do raise ArgumentError, "Invalid expression for MongoDB adapter in #{place}" end + + defp pair_param_range({:in, _, [_, {:^, _, [ix, len]}]}) do + ix..(ix + len - 1) + end + + defp pair_param_range({:not, _, [{:in, _, [_, {:^, _, [ix, len]}]}]}) do + ix..(ix + len - 1) + end + + defp pair_param_range(expr) do + 0..0 + end end