I use the Dataset#max for a date and timestamp column (DB[:data].max(:timestamp),
but I get a String as result, not a timestamp or a date.
Example:
require 'sequel'
DB = Sequel.sqlite()
#~ DB.use_timestamp_timezones = true #no effect
DB.create_table(:data){
Fixnum :num
timestamp :timestamp
Date :date
} unless DB.table_exists?(:data)
#Insert some testdata
1.upto(10){|i|
DB[:data].insert(i, Time.now - 24*60*60*i, Date.today - i)
}
#
#my self written max function.
#
def max(ds,field)
timestamp = nil
ds.select(field).each{|ds|
timestamp = ds[field] if ! timestamp or timestamp < ds[field]
}
timestamp
end
##Ok
p max(DB[:data],:num)
p DB[:data].max(:num) #ok
p max(DB[:data],:timestamp) #timestamp -> ok
p DB[:data].max(:timestamp) #String!!
p max(DB[:data],:date) #date -> ok
p DB[:data].max(:date) #String!!
I made a crosscheck, if the data are really timestamps/dates,
this seems to be ok:
##Crosscheck:
DB[:data].each{|ds|
puts "Error" unless ds[:timestamp].is_a?(Time)
puts "Error" unless ds[:date].is_a?(Date)
puts "Error" unless ds[:num].is_a?(Fixnum)
}
I could use Time#parse to get again a timestamp:
p Time.parse(DB[:data].max(:timestamp))
But I would prefer to get the maximum in the same type.
Is there a way to get the max-result as timestamp/date?
No. SQLite doesn’t actually have date or timestamp types (http://www.sqlite.org/datatype3.html). The only reason you get ruby Date and Time/DateTime values for date and timestamp columns is Sequel can look at the named type of the column (the one used in the CREATE TABLE statement), and automatically convert the value SQLite stores as a string into a Date or Time/DateTime. SQLite expressions (e.g. max(column)) are not tied to columns, and therefore Sequel can not use that method for type conversion.
In short, if you want real date/timestamp handling, use a database that actually supports date/timestamp columns. Unfortunately, unless you are using JRuby can can use H2/HSQLDB/Derby via JDBC, I don’t believe there is another embedded database library that Sequel supports that has real date/timestamp types.