bglusman

bglusman

So I have a gnarly query in my open source Phoenix app I was trying to make dramatically more efficient.. in its current form it brings in a lot of unnecessary data over the wire, so I managed to get a raw SQL form that only gets the data I need, and tried translating it into Ecto, and got stuck with some errors related to group_by vs select I think… the purpose is to get the data we need, which is stocks that have a “path” to any of the credit_types in the database, grouped by which credit type(s) they have a path to (most only have one path, but some have 2, and in that case we want the stock duplicated and to appear in a column for both credit types)… in it’s current form (in Ecto, before attempted refactor) it works but it pulls every food in the database also, because they all relate to one or more credit types, but we only care about “stocked” foods. Current form goes from credit_type “toward” stocks, the refactor works by going from stocks “toward” credit type, and grouping stocks by credit type…

Here is the raw SQL version:

    select stock.id, food.long_desc, food.manufacturer_name, food_group.foodgroup_desc,
      credit_type.name
      from facilities facility
      inner join stocks stock on stock.facility_id = facility.id
      inner join foods food on food.id = stock.food_id
      inner join credit_type_memberships ctm on ctm.food_group_id = food.food_group_id
      inner join credit_types credit_type on credit_type.id = ctm.credit_type_id
    where facility.id = 1
    group by stock.id, food.long_desc, food.manufacturer_name, food_group.foodgroup_desc,
      credit_type.name

And rather than paste the non-working ecto-translation of it here, I’ll link in context to my best/closest attempt I think I got to, in the branch I was playing with it on… the play function here was accidentally committed ages ago while trying to solve the same problem, before I had a working SQL version of it, just to make it easy to test the query in iex… the stock_by_type function above it is the actual query from the app as currently used. You can probably answer any question from the code in the link there, (and original form of that query before the WIP/play commit above is actually changed here for reference) but also happy to provide context if anything is unclear/harder to find an answer to than you’d like, but you’re otherwise interested in helping with the refactor… Thanks all!

Showing Posts 1 to 10

bglusman

bglusman OP

So I see a bunch of people have looked at this but no responses… anyone confused over what I’m asking? Possibly the answer is to just use one or more fragments to translate the pieces, which is a valid answer I’ve already considered, but wouldn’t mind advice on the best pattern/seams to tackle that, vs just making it one gigantic fragment, but welcome any thoughts or questions at all… not urgent, just been bugging me and want to find a way to resolve the question so I can stop scratching at the itch of what to do about it :slight_smile:

OvermindDL1

OvermindDL1

More rather it is a non-small SQL statement and it is not formatted in proper markdown code tags so it is very hard to read. ^.^

I’ll fix your post to use proper markdown so it looks better. :slight_smile:

EDIT: And edited, I do not have time to mentally parse and convert the size of that SQL just yet, but if no one else does soonish then poke me with @OvermindDL1 and I’ll take a look when I can. :slight_smile:

bglusman

bglusman OP

Thank you! I thought it didn’t look right, but it looked ok and was a code block in the preview box, but then looked rather… flat and un-codeish on the page, appreciate the pointer though, suspected there might be a better way!

kip

kip

ex_cldr Core Team

Its interesting that you’re using group_by when you aren’t aggregating anything. Which means the query is basically the same as:

    SELECT DISTINCT stock.id, food.long_desc, food.manufacturer_name, food_group.foodgroup_desc,
      credit_type.name
      FROM facilities facility
      INNER JOIN stocks stock on stock.facility_id = facility.id
      INNER JOIN foods food on food.id = stock.food_id
      INNER JOIN credit_type_memberships ctm on ctm.food_group_id = food.food_group_id
      INNER JOIN credit_types credit_type on credit_type.id = ctm.credit_type_id
    WHERE facility.id = 1;

Which might simplify your Ecto work. Personally, for SQL that has this much complexity, I would probably create a view in the database. That way I can separate DB level optimisations from application processing.

brightball

brightball

Might not be the solution that you are looking for, but I find that complex queries are sometimes best represented as a function. Assuming that’s Postgres, here is an example of how I wrapped a search results function in Phoenix a while back.

It’s not updated for more recent versions, but same idea might be a good fit for the “don’t overthink it” approach. I think something similar would translate well with the schema/context approach.

outlog

outlog

this presentation especially from ~14 minutes mark, will empower your ecto skills a lot (schemaless queries - whole presentation is great!) - also gives you a way to compose these big queries from smaller ones..

bglusman

bglusman OP

I am not super experienced at SQL so you may be right, I got some help crafting this SQL query, but the reason for the group_by is that I want to display all the stocks that connect to a particular credit_type together… the current query starts from credit type and credit_type has_many stocks through foods, which is joined through food_groups and food_group_memberships… I guess though I wouldn’t think in terms of aggregations per se, I am kind of aggragating which stocks are reachable from which credit types, and duplicate stocks in each credit type are possible and need to be treated as seperate instances for purposes of this query, if that explains anything… the surrounding context of the Elixir code may make this clearer, but the idea is this is a pure refactor of the function as it exists on master or in the second git sha link in the before version, so that no other code needs to change… Does that help explain/understand?

bglusman

bglusman OP

Will keep that in mind @brightball, though I have some reluctance/resistance to splitting actual application logic across code and database stored functions… I know it can be efficient, and I like Ecto’s philosophy of trusting the database for constraints, which arguably verges into application logic in some cases, but constraints are pretty simple compared to stored procedures.. not ruling it out, but I don’t think the increase in complexity is justified at this point.

kip

kip

ex_cldr Core Team

I understand conceptually (but the domain isn’t immediately familiar to me). My intention was to say that the SQL you wrote and the SQL I wrote should produce identical results. When there are no aggregations on a select with a group by then the behaviour is to select distinct rows. Since you mentioned you think it was the group by that was giving you challenges in Ecto, this alternative form might help you get over the bump…

OvermindDL1

OvermindDL1

Sounds more like you want to ORDER BY instead of grouping. Grouping is primarily for aggregates only and it does not sound like it is what you want. :slight_smile:

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
subsaharancoder
I’ve followed the Phoenix LiveView file upload code here Uploads — Phoenix LiveView v1.0.0-rc.7 and so far everything works just fine wit...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews