jihantoro

jihantoro

Conditional in Ecto.query

my original syntax :

result =
  Enum.map(
    from(Repo, where: ^whitelisted_params)
    |> where([schema], like(schema.nama, ^"#{nama}%"))
    |> limit(^query_limit)
    |> Repo.all(),
    fn elem ->
      elem |> Map.from_struct() |> Map.delete(:__meta__)
    end
  )

i want to add where([schema], like(schema.tgl, ^tgl)) if a conditional are true

tried :

result =
  Enum.map(
    from(Repo, where: ^whitelisted_params)
    |> where([schema], like(schema.nama, ^"#{nama}%"))
    |> (fn(n) -> tgl != "" |> where([schema], like(schema.tgl, ^tgl)) || "" end).()
    |> limit(^query_limit)
    |> Repo.all(),
    fn elem ->
      elem |> Map.from_struct() |> Map.delete(:__meta__)
    end
  )

error :

protocol Ecto.Queryable not implemented for true, the given module does not exist. This protocol is implemented for: Atom, BitString, Ecto.Query, Ecto.SubQuery, Tuple

thank you !

Most Liked

peerreynders

peerreynders

|> (fn(n) -> tgl != "" |> where([schema], like(schema.tgl, ^tgl)) || "" end).()``

looks to me that you were trying to do something like this

|> (fn(query) -> 
     case tgl do
        "" -> query 
        _ -> where(query, [schema], like(schema.tgl, ^tgl))
     end
   end).()
tme_317

tme_317

Whenever I have a conditional in a pipeline (which happens all the time) I just write a separate private function, so in your pipeline it would look like this:

|> maybe_filter_by_tgl(schema, tgl)

Then a separate function:

defp maybe_filter_by_tgl(query, schema, tgl) do
  if tgl != "", do: where(query, [schema], like(schema.tgl, ^tgl)), else: query
end

This is exactly the same as the anonymous function technique from @peerreynders response… for some reason I just find it easier to read (personal preference).

OvermindDL1

OvermindDL1

Yep, this is a pattern I use super often. I keep meaning to find a way to pipeline it better, but I just tend to have long repeated sets of this small ‘mutation’ chunks (copy/pasted from my sources):

    query =
      case refine do
        [pidm: pidm] when is_integer(pidm) -> where(query, [s], s.spriden_pidm == ^pidm)
        [pidm: pidms] when is_list(pidms) ->  where(query, [s], s.spriden_pidm in ^pidms)
        [cnum: cnum] when is_binary(cnum) ->  where(query, [s], s.spriden_id == ^cnum)
        [cnum: cnums] when is_list(cnums) ->  where(query, [s], s.spriden_id in ^cnums)
        [id: id] when is_binary(id) ->        where(query, [s], s.spriden_id == ^id)
        [id: ids] when is_list(ids) ->        where(query, [s], s.spriden_id in ^ids)
        [] -> query
      end

Obviously I don’t use the formatter because it absolutely destroys the readability of these… I wish it could be fixed… :frowning:

LostKobrakai

LostKobrakai

I often have code like that:

Enum.reduce(opts, base_query, fn 
  {:category, category}, query -> from a in query, where: a.category == ^category
  {:tag, tag}, query -> from a in query, where: a.tag == ^tag
  _, query -> query
end)
peerreynders

peerreynders

Personally I’m solidly in the private function camp - however in this case only a nudge seemed to be asked for - not a possible lecture from the “style police”.

I find discontinuities in the pipe chain increase the cognitive load when reading the code.

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement