Permalink
Browse files

Handle invalid MySQL dates

Older MySQL setups have the default setting where they accept invalid
dates and datetimes and just changes it to 0000-00-00. We treat them
here as nil, since that seems the most sensible thing to do.

Fixes #37
  • Loading branch information...
1 parent 2ee41d7 commit bbcbeb56f14ff2989a843d9565194c6c681e693a @dbussink dbussink committed Aug 13, 2012
@@ -185,6 +185,10 @@ VALUE data_objects_parse_date(const char *date) {
return Qnil;
}
+ if(!year && !month && !day) {
+ return Qnil;
+ }
+
return rb_funcall(rb_cDate, ID_NEW, 3, INT2NUM(year), INT2NUM(month), INT2NUM(day));
}
@@ -237,6 +241,10 @@ VALUE data_objects_parse_date_time(const char *date) {
fmt_datetime = strchr(date, '.') ? _fmt_datetime_tz_subsec : _fmt_datetime_tz_normal;
tokens_read = sscanf(date, fmt_datetime, &year, &month, &day, &hour, &min, &sec, &hour_offset, &minute_offset);
+ if(!year && !month && !day && !hour && !min && !sec) {
+ return Qnil;
+ }
+
switch (tokens_read) {
case 8:
minute_offset *= hour_offset < 0 ? -1 : 1;
@@ -6,4 +6,30 @@
describe 'DataObjects::Mysql with Date' do
it_should_behave_like 'supporting Date'
it_should_behave_like 'supporting Date autocasting'
+
+ describe 'reading 0000-00-00' do
+
+ before do
+ @connection = DataObjects::Connection.new(CONFIG.uri)
+
+ @connection.create_command("SET SESSION sql_mode = 'ALLOW_INVALID_DATES'").execute_non_query
+ @connection.create_command("INSERT INTO widgets (release_date) VALUES ('')").execute_non_query
+
+ @command = @connection.create_command("SELECT release_date FROM widgets WHERE release_date = '0000-00-00'")
+ @reader = @command.execute_reader
+ @reader.next!
+ @values = @reader.values
+ end
+
+ after do
+ @reader.close
+ @connection.close
+ end
+
+ it 'should return the number of created rows' do
+ @values.first.should be_nil
+ end
+
+ end
+
end
@@ -6,4 +6,30 @@
describe 'DataObjects::Mysql with DateTime' do
it_should_behave_like 'supporting DateTime'
it_should_behave_like 'supporting DateTime autocasting'
+
+ describe 'reading 0000-00-00 00:00:00' do
+
+ before do
+ @connection = DataObjects::Connection.new(CONFIG.uri)
+
+ @connection.create_command("SET SESSION sql_mode = 'ALLOW_INVALID_DATES'").execute_non_query
+ @connection.create_command("INSERT INTO widgets (release_datetime) VALUES ('')").execute_non_query
+
+ @command = @connection.create_command("SELECT release_datetime FROM widgets WHERE release_datetime = '0000-00-00 00:00:00'")
+ @reader = @command.execute_reader
+ @reader.next!
+ @values = @reader.values
+ end
+
+ after do
+ @reader.close
+ @connection.close
+ end
+
+ it 'should return the number of created rows' do
+ @values.first.should be_nil
+ end
+
+ end
+
end

0 comments on commit bbcbeb5

Please sign in to comment.