1

I'm looking for an explanation of the result of the following query with Active Record:

date_range = (Date.today - 7)..(Time.now.to_datetime)
r = Report.find(:all, :conditions => {:created_at => date_range},
                      :group => 'date(created_at)',
                      :select => 'date(created_at) as day, count(id) as counter') 

Basically I'm just counting the results in a table "reports," but I got different types of values for the named field "counter", array of double quote strings vs array of only numbers.

MySQL

If using MySQL,

r.map(&:counter)

returns:
=> ["3", "3", "5", "4", "4"]

SQLite

If using SQLite,

r.map(&:counter)

returns:
=> [3, 3, 5, 4, 4]

Is it correct that MySQL returns the numbers with quotes (Strings) and SQLite numbers? I expected that both return just integers. Or am I missing some configuration with on MySQL side?

Edit:
Just in case, both DBs where created using normal migrations, so all fields are equivalent types.

2
  • I'm presuming that in the MySQL database it's stored as an integer rather than string? Commented Mar 1, 2011 at 4:54
  • Just in case I checked again, "id" is as usual integer in both cases. And count(id) isn't supposed to give you just a number...? Commented Mar 1, 2011 at 5:02

2 Answers 2

1

This is a bug in the SQLite ActiveRecord adapter.

When you are synthesizing new column values using "SELECT expr AS col_name" col_name is cast to a String instead of the proper data type (int in this case).

See related Rails bug ticket: https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/4544-rails3-activerecord-sqlite3-lost-column-type-when-using-views#ticket-4544-2

Apparently SQLite can't return proper column type values for views, which is the mechanism used when you're synthesizing attributes like this.

Sign up to request clarification or add additional context in comments.

Comments

0

I've been having the same issue using the underlying connection to execute my SQL statements.

I have noticed, however, that if you are using binds in exec_sql statement, the data types come back as expected.

E.g.

ActiveRecord::Base.connection.exec_sql("select * from users where id = 35") 

results in

ActiveRecord::Result:0x7fa2c6ede200 @columns=["id", "name"], @hash_rows=nil, @rows=[["35", "FOO"]]

However,

ActiveRecord::Base.connection.exec_sql("select * from users where id = ?", nil, [[nil,35]]) 

results in

ActiveRecord::Result:0x7fa2c6ede200 @columns=["id", "name"], @hash_rows=nil, @rows=[[35, "FOO"]]

Note that datatype of 35 is integer! Hope that helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.