Skip to content

Instantly share code, notes, and snippets.

@josepjaume
Created September 9, 2011 12:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josepjaume/1206106 to your computer and use it in GitHub Desktop.
Save josepjaume/1206106 to your computer and use it in GitHub Desktop.
Time comparison inconsistency with SQLite, PostgreSQL and MySQL with ActiveRecord
def pending_notifications
notifications = self.notifications
if last_notification_read_at
# Sqlite doesn't properly compare dates because doesn't have a dedicated
# type for it.
# TODO: Investigate further and find a better solution for this.
#
time_restriction = if connection.class.name.demodulize =~ /SQLite/
["datetime(notifications.created_at) >= ?", last_notification_read_at]
elsif connection.class.name.demodulize =~ /PostgreSQL/
["notifications.created_at >= ?", last_notification_read_at.to_time]
else
["notifications.created_at >= ?", last_notification_read_at]
end
notifications = notifications.where(time_restriction)
end
notifications
end
@josepjaume
Copy link
Author

Seriously, doesn't anyone have a good solution for this? I've been struggling with it for the last few hours.

@fesplugas
Copy link

Which version of Ruby are you using?

@fesplugas
Copy link

BTW:

time_restriction = case connection.class.name.demodulize 
                   when /SQLite/
                     ["datetime(notifications.created_at) >= ?", last_notification_read_at]
                   when /PostgreSQL/
                     ["notifications.created_at >= ?", last_notification_read_at.to_time]
                   else
                     ["notifications.created_at >= ?", last_notification_read_at]
                   end

@fesplugas
Copy link

What do you have in last_notification_read_at?

@josepjaume
Copy link
Author

Hey! Nice to see you!

last_notification_read_at is DateTime object (from an attribute)

@fesplugas
Copy link

How do you store stuff in SQLite3? Run this in the SQLite3 console.

SELECT created_at, typeof(created_at) FROM entries;

I guess you have a BLOB there when it should be text.

@josepjaume
Copy link
Author

josepjaume commented Sep 9, 2011 via email

@fesplugas
Copy link

See this commit: rails/rails@20c07170
And this rails/rails#2892

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment