From c3a336c18dd9cebe1483d1fbe5b670a0496e26cf Mon Sep 17 00:00:00 2001 From: Joost de Bruijn Date: Wed, 3 May 2017 23:45:02 +0200 Subject: [PATCH] Adding support for fractional seconds. --- lib/migration.js | 28 +++++++++++++++++++++++++++- lib/mysql.js | 2 +- test/datetime.test.js | 19 +++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/lib/migration.js b/lib/migration.js index 50e1b6f..0407ef9 100644 --- a/lib/migration.js +++ b/lib/migration.js @@ -723,7 +723,8 @@ function mixinMigration(MySQL, mysql) { dt = numericOptionsByType(p, dt); break; case 'Date': - dt = columnType(p, 'DATETIME'); // Currently doesn't need options. + dt = columnType(p, 'DATETIME'); + dt = dateOptionsByType(p, dt); break; case 'Boolean': dt = 'TINYINT(1)'; @@ -893,6 +894,31 @@ function mixinMigration(MySQL, mysql) { return columnType; } + function dateOptionsByType(p, columnType) { + switch (columnType.toLowerCase()) { + default: + case 'date': + break; + case 'time': + case 'datetime': + case 'timestamp': + columnType = dateOptions(p, columnType); + break; + } + return columnType; + } + + function dateOptions(p, columnType) { + var precision = 0; + + if (p.precision) { + precision = Number(p.precision); + columnType += '(' + precision + ')'; + } + + return columnType; + } + function unsigned(p, columnType) { if (p.unsigned) { columnType += ' UNSIGNED'; diff --git a/lib/mysql.js b/lib/mysql.js index fd01fc1..46f8ba7 100644 --- a/lib/mysql.js +++ b/lib/mysql.js @@ -412,7 +412,7 @@ MySQL.prototype.fromColumnValue = function(prop, val) { // 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 || val == '0000-00-00 00:00:00' || val == '0000-00-00') { + if (!val || /^0{4}(-00){2}( (00:){2}0{2}(\.0{1,6}){0,1}){0,1}$/.test(val)) { val = null; } break; diff --git a/test/datetime.test.js b/test/datetime.test.js index 1924b6f..524bbba 100644 --- a/test/datetime.test.js +++ b/test/datetime.test.js @@ -17,6 +17,7 @@ describe('MySQL datetime handling', function() { married: Boolean, dob: {type: 'DateString'}, createdAt: {type: Date, default: Date}, + lastLogon: {type: Date, precision: 3, default: Date}, }; // Modifying the connection timezones mid-flight is a pain, @@ -92,4 +93,22 @@ describe('MySQL datetime handling', function() { }); } }); + + it('should allow use of fractional seconds', function(done) { + var d = new Date('1971-06-22T12:34:56.789Z'); + return Person.create({ + name: 'Mr. Pink', + gender: 'M', + lastLogon: d, + }).then(function(inst) { + return Person.findById(inst.id); + }).then(function(inst) { + inst.should.not.eql(null); + var lastLogon = new Date(inst.lastLogon); + lastLogon.toJSON().should.eql(d.toJSON()); + return done(); + }).catch(function(err) { + return done(err); + }); + }); });