robinkwilson
Best way to get all entries for one day, or date range, using Ecto.Query?
Hi! I spent a long time trying to figure out the best way to get all entries in a specific date range. So wanted to share my solution and see if there’s a better way.
Is this the best way to go about it? Set all NaiveDateTime’s time to 00:00:00.0000 for today and tomorrow, then get today >= and < tomorrow’s entries.
@seconds_in_a_day 24 * 60 * 60
def get_list_of_today_values(utc_date) do
{:ok, time} = Time.new(0, 0, 0, 0)
{:ok, today_date} = \
utc_date \
|> NaiveDateTime.to_date() \
|> NaiveDateTime.new(time)
next_day_date = today_date |> NaiveDateTime.add(@seconds_in_a_day, :second)
from(ss in StorageStat, where: ss.measured_at >= ^today_date and ss.measured_at < ^next_day_date)
|> Repo.all()
end
Most Liked
Eiji
If you want to return all entries from said date then how about simply converting PostgreSQL’s timestamp to date?
Here is an example script:
Mix.install([:ecto_sql, :postgrex])
defmodule Migration do
use Ecto.Migration
def change do
create table("tests") do
add(:timestamp, :naive_datetime)
end
end
end
defmodule Repo do
use Ecto.Repo, adapter: Ecto.Adapters.Postgres, otp_app: :my_app
end
defmodule Test do
use Ecto.Schema
schema "tests" do
field(:timestamp, :naive_datetime_usec)
end
end
defmodule Example do
alias Ecto.Query
require Query
def cleanup do
Repo.stop()
end
def prepare do
Application.put_env(:my_app, Repo,
database: "example",
password: "postgres",
username: "postgres"
)
_ = Repo.__adapter__().storage_down(Repo.config())
:ok = Repo.__adapter__().storage_up(Repo.config())
{:ok, _} = Supervisor.start_link([Repo], strategy: :one_for_one)
Ecto.Migrator.up(Repo, 0, Migration)
end
def sample do
now = NaiveDateTime.utc_now()
Test
|> Query.from(as: :test)
|> Query.where(
[test: test],
fragment("?::date = ?::date", test.timestamp, type(^now, :naive_datetime))
)
|> Query.select([test: test], test.timestamp)
|> Repo.all()
|> IO.inspect()
end
def seed do
seconds_in_day = 24 * 60 * 60
now = NaiveDateTime.utc_now()
yesterday = NaiveDateTime.add(now, seconds_in_day * -1, :second)
tomorrow = NaiveDateTime.add(now, seconds_in_day, :second)
Repo.insert(%Test{timestamp: yesterday})
Repo.insert(%Test{timestamp: now})
Repo.insert(%Test{timestamp: tomorrow})
end
end
Example.prepare()
Example.seed()
Example.sample()
Example.cleanup()
1
Popular in Questions
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
How to bind a phoenix app to a specific ip address?
could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Hello everyone,
I try to use an Javascript Event Handler in my root.html.leex file.
Therefore I created a function in the app.js file: ...
New
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
I have VueJS GUIs with the project generated using Webpack.
I have Elixir modules that will need to be used by the VueJS GUIs.
I forese...
New
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
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this
"1000"
What is the ...
New
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function:
-dialyzer...
New
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
Other popular topics
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1]
15:22:35.803 [error] gen_event {lager_file_backend...
New
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
Using vs code and installed ElixirLS: support and debugger.
And I got an error popped up on start up says
Failed to run ‘elixir’ comma...
New
Hello guys,
I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
Hey,
Just curious what are the main benefits of Elixir compared to Clojure?
When is Elixir more useful than Clojure and vice versa?
Th...
New
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
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
Hi everyone,
I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
Hi!
Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









