Best Style for Queries on column depending on id

I have a flow where if the “id” is an 8 digit number, assume it’s a date of a concert we want to look up. Otherwise, use the “id” as normal:

show_query = if String.length(id) == 8 do
 # performed_on is created from the "id" param

  from c in Concert,
     where: c.performed_on == ^performed_on
   from c in Concert,
      where: c.concert_id == ^id

show =

# Now, look up the tracks played on that concert
tracks_query = from ct in ConcertTrack,
    where: ct.concert_id == show.concert_id

Is this a good pattern to do? The query is repeated, except for the where clause.

Thank you!

This feels like a trap :stuck_out_tongue:

Usually if you’re going to overload a parameter like this with two meanings, it’s better if they are distinguishable - for instance, using 2023-12-26 instead of 20231226 for a date.

It’s hard to judge the usefulness of this code in isolation, but some thoughts:

  • the specifics of ...... are important for making do something useful, otherwise this is a complicated way to pass id to tracks_query for inputs not of length 8.
  • is show used subsequently in this function? If not, you might consider adding some additional code to tracks_query to handle that lookup
  • conversely, could show be an argument to whatever function this is? Then a separate function could translate idshow
  • I can’t speak to your specific domain, but having known some very busy session musicians you may want to consider if “exactly one concert per calendar date” is a safe constraint on your data :stuck_out_tongue: