From 5c6d3c711f304ee97d3a2c790dab353594936ce9 Mon Sep 17 00:00:00 2001 From: Nathan Woltman Date: Sun, 28 Jun 2020 18:25:43 -0400 Subject: [PATCH] improvement: Support MariaDB's CURRENT_TIMESTAMP format Handle MariaDB using a different format for `DEFAULT CURRENT_TIMESTAMP` and `ON UPDATE CURRENT_TIMESTAMP` (MariaDB uses `current_timestamp()`) by translating `current_timestamp()` to `CURRENT_TIMESTAMP` when parsing the SQL into a schema object. Fixes #4 --- lib/sqlToSchema.js | 11 +++++++++-- test/unit/sqlToSchema.test.js | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/lib/sqlToSchema.js b/lib/sqlToSchema.js index 4be5c29..3d62c87 100644 --- a/lib/sqlToSchema.js +++ b/lib/sqlToSchema.js @@ -78,6 +78,8 @@ function generateColumnsSchema(createDefinitions) { const rgxDefault = / DEFAULT (?:'((?:''|[^'])*?)'(?!')|(\S+))/; const rgxCharset = / CHARACTER SET (\w+)/; const rgxCollate = / COLLATE (\w+)/; + // Support MariaDB. See: https://github.com/nwoltman/node-mysql-plus/issues/4 + const rgxOnUpdateCurTimestamp = / ON UPDATE (?:CURRENT_TIMESTAMP\b|current_timestamp\(\))/; for (var i = 0; i < createDefinitions.length; i++) { const definitionSQL = createDefinitions[i].trim(); @@ -120,7 +122,7 @@ function generateColumnsSchema(createDefinitions) { if ( (type === 'datetime' || type === 'timestamp') && - definitionSQL.indexOf(' ON UPDATE CURRENT_TIMESTAMP') >= 0 + rgxOnUpdateCurTimestamp.test(definitionSQL) ) { columnDefintion.onUpdateCurrentTimestamp(); } @@ -129,7 +131,12 @@ function generateColumnsSchema(createDefinitions) { if (match = rgxDefault.exec(definitionSQL)) { if (match[2]) { - columnDefintion.$defaultRaw(match[2]); + let rawDefault = match[2]; + if (rawDefault === 'current_timestamp()') { + // Support MariaDB. See: https://github.com/nwoltman/node-mysql-plus/issues/4 + rawDefault = 'CURRENT_TIMESTAMP'; + } + columnDefintion.$defaultRaw(rawDefault); } else { columnDefintion.default(match[1]); } diff --git a/test/unit/sqlToSchema.test.js b/test/unit/sqlToSchema.test.js index fff1e2a..f27e686 100644 --- a/test/unit/sqlToSchema.test.js +++ b/test/unit/sqlToSchema.test.js @@ -1,5 +1,7 @@ 'use strict'; +const ColumnDefinitions = require('../../lib/ColumnDefinitions'); + const sqlToSchema = require('../../lib/sqlToSchema'); describe('sqlToSchema', () => { @@ -19,4 +21,18 @@ describe('sqlToSchema', () => { }); }); + it('should translate MariaDB DEFAULT and ON UPDATE current_timestamp() to be compatible with CURRENT_TIMESTAMP', () => { + const schema = sqlToSchema(` + CREATE TABLE \`test\` ( + \`dt\` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp() + ) + `); + + ColumnDefinitions.datetime() + .defaultCurrentTimestamp() + .onUpdateCurrentTimestamp() + .$equals(schema.columns.dt) + .should.be.true(); + }); + });