sergio

sergio

Doing a postgresql coalesce with custom type in Ecto

I’m trying to find the total amount of winnings for a specific backer in my database.

    query =
      from b in Gaming.Stakes.Backer,
        left_join: bwt in assoc(b, :wallet_transactions),
        left_join: bpwt in assoc(b, :backer_promotional_wallet_transactions),
        where: b.id == ^backer.id,
        where: bwt.type == "winnings" or bpwt.type == "winnings",
        group_by: b.id

    from e in subquery(query),
      select: [e.backer_id, e.wallet_sums + e.promotional_wallet_sums]

I’m a bit stuck on how to do the coalesce, and the nested select. Ultimately what I need a single value to come back from the database.

This is the raw SQL query that works as intended and give me the data I need. I’m trying to get this into Ecto code.

     SELECT
       backer_id,
       wallet_sums + promotional_wallet_sums AS total
     FROM
       (
         SELECT
           backers.id AS backer_id,
           SUM( COALESCE( wallet_transactions.amount,
           (
             'USD',
             0
           )
           :: money_with_currency ) ) AS wallet_sums,
           SUM( COALESCE( promotional_wallet_transactions.amount,
           (
             'USD',
             0
           )
           :: money_with_currency ) ) AS promotional_wallet_sums
         FROM
           backers
           LEFT JOIN
             backer_wallet_transactions
             ON backer_wallet_transactions.backer_id = backers.id
           LEFT JOIN
             wallet_transactions
             ON wallet_transactions.id = backer_wallet_transactions.wallet_transaction_id
           LEFT JOIN
             backer_promotional_wallet_transactions
             ON backer_promotional_wallet_transactions.backer_id = backers.id
           LEFT JOIN
             promotional_wallet_transactions
             ON promotional_wallet_transactions.id = baker_promotional_wallet_transactions.promotional_wallet_transaction_id
         WHERE
           backers.id = 'c9ffd955-3333-3333-3333-578346b33333'
           AND
           (
             wallet_transactions.type = 'winnings'
             OR promotional_wallet_transactions.type = 'winnings'
           )
         GROUP BY
           backers.id
       )
       sums

Marked As Solved

sergio

sergio

I managed to figure it out.

The tricky part was to use the ? fragment to reference the relationship because of it’s indirect in sql -vs- direct in ecto relationship magic nature.

query =
      from b in Gaming.Stakes.Backer,
        left_join: wt in assoc(b, :wallet_transactions),
        left_join: pwt in assoc(b, :promotional_wallet_transactions),
        where: b.id == ^backer.id,
        where: wt.type == ^"winnings" or pwt.type == ^"winnings",
        group_by: b.id,
        select: %{
          backer_id: b.id,
          wallet_sums:
            fragment(
              """
              SUM( COALESCE( ?.amount,
              (
                'USD',
                0
              )
              :: money_with_currency ) )
              """,
              wt
            ),
          promotional_wallet_sums:
            fragment(
              """
              SUM( COALESCE( ?.amount,
              (
                'USD',
                0
              )
              :: money_with_currency ) )
              """,
              pwt
            )
        }

    query =
      from e in subquery(query),
        select: e.wallet_sums + e.promotional_wallet_sums

    Repo.one(query)

Also Liked

LostKobrakai

LostKobrakai

In my opinion sum for money should work exactly as sum works on numeric/decimal columns would, granted all currencies are the same. Any different behavior should be a custom and separately documented aggregation function.

kip

kip

ex_cldr Core Team

Do I understand correctly that the intent is to sum :money_with_currency amounts, but treat NULL amounts as 0 amounts in the currently aggregating currency (USD for your example?). That might be possible and reasonable to implement as an additional aggregate function and I’ll take a look (I’m the author of ex_money which it appears you may be using).

Where Next?

Popular in Questions Top

marius95
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
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
nobody
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
stefanchrobot
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
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
freewebwithme
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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
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
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 47930 226
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement