auto_cast_date_and_time.rb

lib/sequel/extensions/auto_cast_date_and_time.rb
Last Update: 2023-12-29 12:15:30 -0800

The auto_cast_date_and_time extension uses SQL standard type casting when literalizing date, time, and timestamp values:

DB.literal(Time.now)
# => "TIMESTAMP '...'"

DB.literal(Date.today)
# => "DATE '...'"

DB.literal(Sequel::SQLTime.create(10, 20, 30))
# => "TIME '10:20:30.000000'"

The default behavior of Sequel on adapters that do not require the SQL standard behavior is to format the date or time value without: casting

DB.literal(Sequel::SQLTime.create(10, 20, 30))
# => "'10:20:30.000000'"

However, then the database cannot determine the type of the string, and must perform some implicit casting. If implicit casting cannot be used, it will probably treat the value as a string:

DB.get(Time.now).class
# Without auto_cast_date_and_time: String
#    With auto_cast_date_and_time: Time

Note that not all databases support this extension. PostgreSQL and MySQL support it, but SQLite and Microsoft SQL Server do not.

You can load this extension into specific datasets:

ds = DB[:table]
ds = ds.extension(:auto_cast_date_and_time)

Or you can load it into all of a database’s datasets, which is probably the desired behavior if you are using this extension:

DB.extension(:auto_cast_date_and_time)

Related module: Sequel::AutoCastDateAndTime