Morzaram

Morzaram

Filtering Events by attribute with Different Time Conditions

Hey y’all I’m trying to figure out how to write this more eloquently…

I need to query a table of events that are happening this month (including things that are happening from the start of today). I have 3 types of events based off of column :type and depending on what’s in that column will determing whether or not I check that starts_at or ends_at

I have 3 types of events, :event, :action, :other

How do I write this so I check the following
if e.type == event: :starts_at
if e.type == action: :ends_at
if e.type == other: :ends_at

This is what I have now for and as you can see it looks horrible and only queries the start time. I’m hoping to get it in one query, otherwise I’ll write it in two, but it’s not the most ideal obviously

def events_at_date(month, year) do
    timezone = "America/Los_Angeles"

    from(e in Event,
      where:
        fragment(
          "EXTRACT(YEAR FROM (starts_at AT TIME ZONE 'UTC' AT TIME ZONE ?)) = ?",
          ^timezone,
          ^year
        ),
      where:
        fragment(
          "EXTRACT(MONTH FROM (starts_at AT TIME ZONE 'UTC' AT TIME ZONE ?)) = ?",
          ^timezone,
          ^month
        )
    )
  end

The edge of my sql knowledge stops here. I’m super weak with times and timezones…

Any help would be appreciated

Most Liked

LostKobrakai

LostKobrakai

The simplest way to get this running would probably be something like this:

date_trunc('month', (CASE WHEN type = 'event' THEN starts_at
     WHEN type = 'action' THEN ends_at
     WHEN type = 'other' THEN ends_at
END AT TIME ZONE 'UTC' AT TIME ZONE ?)) == ?
LostKobrakai

LostKobrakai

There are a few things here:

  • You need to switch based on type → that requires a CASE expression with sql.

  • This is ugly because many of the functions you’re using are not in the default ecto query api, so you end up with a huge fragment. Extracting those fragments to named functions/macros can help with better composability as well as making those things more readable: Ecto.Query.API — Ecto v3.11.0

  • Given you’re filtering based on a bunch of functions you cannot simply use an index here. It would be better to figure out a way to have the information you need in the db in the first place (either as a column or an index using expressions) and query based on that index – at least if this will grow to more events than just a few (hundred).

LostKobrakai

LostKobrakai

I’d ignore the “month” part. What is a month changes by timezone. But you want a stable (indexable) column of what datetime is relevant for your filtering. Then you can do a “before x, after y” search in the index with x and y specific to the tz you’re interested in.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
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

Other popular topics Top

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
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
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
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
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

We're in Beta

About us Mission Statement