From 1ee79768f2026c2e78429f8b4349eadcc71268c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carl=20F=C3=BCrstenberg?= Date: Tue, 26 Jul 2016 13:39:52 +0200 Subject: [PATCH] Add special handling of zero date/time entries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per MySQL docs (http://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html): "MySQL permits you to store a “zero” value of '0000-00-00' as a “dummy date.” This is in some cases more convenient than using NULL values, and uses less data and index space. To disallow '0000-00-00', enable the NO_ZERO_DATE mode. “Zero” date or time values used through Connector/ODBC are converted automatically to NULL because ODBC cannot handle such values." As we are not using Connector/ODBC we need to handle this ourself. --- lib/mysql.js | 10 +++++++++- test/migration.test.js | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/mysql.js b/lib/mysql.js index 7527ff6..91f4298 100644 --- a/lib/mysql.js +++ b/lib/mysql.js @@ -405,7 +405,15 @@ MySQL.prototype.fromColumnValue = function(prop, val) { val = String(val); break; case 'Date': - val = new Date(val.toString().replace(/GMT.*$/, 'GMT')); + + // MySQL allows, unless NO_ZERO_DATE is set, dummy date/time entries + // new Date() will return Invalid Date for those, so we need to handle + // those separate. + if (val == '0000-00-00 00:00:00') { + val = null; + } else { + val = new Date(val.toString().replace(/GMT.*$/, 'GMT')); + } break; case 'Boolean': val = Boolean(val); diff --git a/test/migration.test.js b/test/migration.test.js index e8dbe14..18ab710 100644 --- a/test/migration.test.js +++ b/test/migration.test.js @@ -318,6 +318,23 @@ describe('migrations', function () { }); }); + it('should map zero dateTime into null', function (done) { + + query('INSERT INTO `DateData` ' + + '(`dateTime`, `timestamp`) ' + + 'VALUES("0000-00-00 00:00:00", "0000-00-00 00:00:00") ', + function (err, ret) { + should.not.exists(err); + DateData.findById(ret.insertId, function (err, dateData) { + should(dateData.dateTime) + .be.null(); + should(dateData.timestamp) + .be.null(); + done(); + }); + }); + }); + it('should report errors for automigrate', function() { db.automigrate('XYZ', function(err) { assert(err);