rails / arel

A Relational Algebra
2.06k stars 390 forks source link

wrong type for results of average #504

Closed nekogami closed 6 years ago

nekogami commented 6 years ago

ruby version: 2.4.1p111 psql version: Psql 10.0 rails 5.1.1

Hi, I recently encountered kind of a weird behavior when executing an Arel query. This is the SQL query generated through arel:

SELECT AVG("my_table"."patient_num") AS avg_patient, AVG("my_table"."stay_days") AS avg_stay_days FROM "my_table"

Here is the results in psql console:

  avg_patient_count  |  avg_stay_days   
---------------------+------------------
 57.5404913252072946 | 12.3359871661342
(1 row)

Here is what I get in Ruby

=> {"avg_patient_count"=>"57.5404913252072946", "avg_stay_days"=>12.3359871661342}

For some reasons, the first average is stringified in ruby, I am not sure why though

nekogami commented 6 years ago

Not sure if it is related but, somehow I cannot execute my query by doing

ActiveRecord::Base.connection.execute(method_generating_arel_object_request)

when in my projection I have .average.as("somename") because the following error is raised

TypeError: no implicit conversion of Arel::SelectManager into String
from /Users/{users}/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:97:in `async_exec'

so I ended up doing

ActiveRecord::Base.connection.execute(method_generating_arel_object_request.to_sql)
tenderlove commented 6 years ago

This doesn't sound a like a problem with ARel, but a problem with the database adapter or possibly your column types. The database adapter uses the column type to cast it to a Ruby object. It could be that the column type is wrong, or that the database adapter doesn't know how to handle that type. Take a look at the pg_typeof function. You can use that function to figure out what type you're selecting. From there, either fix your data so it's the right type, or file a bug on the Rails side (as it's a bug in the adapter).

Thanks!