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

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews