salomvary

salomvary

Hi folks, I am very new to Elixir and Ecto and struggling to express an SQL query in Ecto where I have to select computed values from a CTE into virtual fields.

Schema and query look like this (simplified for readability):

schema "readings" do
  field :read_at, :naive_datetime
  field :value, :integer
  field :previous_value, :integer, virtual: true
  field :current_value, :integer, virtual: true
end

current_values_query =
  Reading
  |> select_merge([r], %{
    current_value:
      coalesce(
        r.value,
        lag(r.value)
        |> over(order_by: r.read_at)
      ),
  })

query = { "current_values", Reading }
  |> with_cte("current_values", as: ^current_values_query)
  |> select_merge([r], %{
    previous_value:
      lag(r.value)
      |> over(order_by: r.read_at),

  })
  |> order_by([r], [asc: r.read_at])

In a nutshell, I am querying a timeseries of current and previous values, and there might be gaps in values, in which which case the effective current value (current_velue) is the value from the previous row.

Because PostgreSQL does not allow values from window functions within window functions, I have to resort to a CTE.

The above query compiles and executs fine, but current_value is always nil.

The generated SQL looks like this, which seems correct, except missing c0.current_value in the second SELECT:

WITH "current_values"
         AS (SELECT sr0."id"                                                 AS "id",
                    sr0."read_at"                                            AS "read_at",
                    sr0."value"                                              AS "value",
                    sr0."gas"                                                AS "gas",
                    sr0."water"                                              AS "water",
                    sr0."inserted_at"                                        AS "inserted_at",
                    sr0."updated_at"                                         AS "updated_at",
                    COALESCE(sr0."value",
                             LAG(sr0."value") OVER (ORDER BY sr0."read_at")) AS "current_value"
             FROM "readings" AS sr0)
SELECT c0."id",
       c0."read_at",
       c0."value",
       c0."gas",
       c0."water",
       c0."inserted_at",
       c0."updated_at",
       LAG(c0."value") OVER (ORDER BY c0."read_at")
FROM "current_values" AS c0
ORDER BY c0."read_at";

Am I doing it wrong? Is this a limitation? Is this a bug?

Showing Posts 1 to 3

LostKobrakai

LostKobrakai

Virtual fields are not selected by default based in the schema, so you need to explicitly select/select merge it in the last query.

salomvary

salomvary OP

I’ve tried selecting current_value in in the second query with current_value: r.current_value:

query = { "current_values", Reading }
  |> with_cte("current_values", as: ^current_values_query)
  |> select_merge([r], %{
    current_value: r.current_value,
    previous_value:
      lag(r.value)
      |> over(order_by: r.read_at),

  })
  |> order_by([r], [asc: r.read_at])

But that results in an Ecto.QueryError:

field `current_electricity` in `select` is a virtual field in schema Reading in query

Maybe there is another syntax for selecting current_value I am not aware of?

salomvary

salomvary OP

All right, I managed to get this working using fragment in the second select_merge:

current_value: fragment("current_value")

Suggestions for a more elegant approach are still welcome :slight_smile:

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews