jackc / surus

PostgreSQL extensions for ActiveRecord
MIT License
395 stars 35 forks source link

Quote association names #11

Closed rurabe closed 10 years ago

rurabe commented 10 years ago

I have a model named Row, which seems to be giving me errors.

TicketData::Section.find_json(30035,include: :rows)

which results in:

select row_to_json(t) 
from (
  SELECT id, names, zone_name, configuration_id, created_at, updated_at, stubhub_id, stubhub_zone_id, value_override, value, calculated_value, general_seating, area, center, path, angle, distance, (
    select array_to_json(coalesce(array_agg(row_to_json(t)), '{}')) 
    from (
      SELECT id, name, position, section_id, configuration_id, created_at, updated_at, center, area, path, angle, distance, value, value_override, calculated_value 
      FROM "ticket_data_rows"  
      WHERE ("ticket_data_sections"."id"="section_id")  
      ORDER BY "ticket_data_rows"."position" ASC
    ) t
  ) rows 
  FROM "ticket_data_sections"  
  WHERE "ticket_data_sections"."id" = 30035
) t

which gives:

PG::SyntaxError: ERROR:  syntax error at or near "rows"
LINE 1: ...)  ORDER BY "ticket_data_rows"."position" ASC) t) rows FROM ...
                                                             ^

If I manually edit the sql to put quotes around "rows":

select row_to_json(t) from (
  SELECT id, names, zone_name, configuration_id, created_at, updated_at, stubhub_id, stubhub_zone_id, value_override, value, calculated_value, general_seating, area, center, path, angle, distance, (
    select array_to_json(coalesce(array_agg(row_to_json(t)), '{}'))
    from (
      SELECT id, name, position, section_id, configuration_id, created_at, updated_at, center, area, path, angle, distance, value, value_override, calculated_value 
      FROM "ticket_data_rows"  
      WHERE ("ticket_data_sections"."id"="section_id")  
      ORDER BY "ticket_data_rows"."position" ASC
    ) t
  ) "rows"
  FROM "ticket_data_sections"
  WHERE "ticket_data_sections"."id" = 30035
) t

then it works as expected.

I'm not very familiar with how AR works under the hood, so I poked around in the code but couldn't find where this is getting generated. Is this a surus issue? Or is it in AR?

rurabe commented 10 years ago

Note that rows seems to be the only thing that sets this off, when I do sections as an association it works fine. I think rows is a keyword in postgres. But quoting the string allows for columns of any name.

rurabe commented 10 years ago

I went to create a test for this and it passes, was this fixed by 7c06bee3cd4a34158db458d3cdd2ad2d4aa3f724 ? Is that why I can't find where the probem is haha?

If so, any plans on releasing soon? Or should I point to github?

jackc commented 10 years ago

Yes, it looks like it was fixed by 7c06bee. But it did reveal a potential issue in the code path where association names should be quoted. So I made that change and added a test.

I've released a new version to rubygems.com.