hanami / model

Ruby persistence framework with entities and repositories

Home Page:http://hanamirb.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to get a raw result(no Hanami::Entity) from a query.

wuarmin opened this issue · comments

commented

Hello,

I have following query:

def identifier_register
  fr_cost_notes.select_group(:identifier).
  select_append {
    `array_agg(distinct "month") "months"`
  }.
  where(company_id: company_id, profit_center_id: profit_center_ids) {
    (month >= month_from) & (month <= month_until)
  }.to_a
end

and expect a unmapped result like

[
   {
        :identifier => "BALBOA",
        :months => [201601, 201602]
    },
    {
        :identifier => "ROCKY",
        :months => [201601, 201602, 201801]
    }
]

but get an array of Hanami::Entities without "months", because it is not defined at entity-schema.
I think this worked in previous hanami-versions, but I'm not sure.

Just for info: To workaround the issue, I ended with a hack like this.

def identifier_register
  sql = fr_cost_notes.select_group(:identifier).
  select_append {
    `array_agg(distinct "month") "months"`
  }.
  where(company_id: company_id, profit_center_id: profit_center_ids) {
    (month >= month_from) & (month <= month_until)
  }.dataset.sql

  fetch(sql, false)
end

best regards

It's one of those cases where the POLS bites back at you. We make sure that everything that a repository returns is turned into an Entity. But entities have schemas and aren't really all that a repository can return.

What I can offer you, so you can get rid of the fetch call, is calling #map over the relation you get on your example.

fr_cost_notes.select_group(:identifier).
 select_append {
   `array_agg(distinct "month") "months"`
 }.
 where(company_id: company_id, profit_center_id: profit_center_ids) {
   (month >= month_from) & (month <= month_until)
 }.map.to_a

That will skip the mapper and should return you an array of hashes.

BTW sorry for taking so long to get back at you, @wuarmin =(

commented

@mereghost thank you for your investigation! I like your suggestion. (What do you think about mentioning this at the guides for other users?)

@wuarmin it's a good idea - specially in case somebody needs only skinny API. I tried to find it somewhere in the docs, but without success, so a guide extension is a great idea.