Skip to content

Commit

Permalink
improvement: Support MariaDB's CURRENT_TIMESTAMP format
Browse files Browse the repository at this point in the history
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
  • Loading branch information
nwoltman committed Jun 28, 2020
1 parent ed932c9 commit 5c6d3c7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/sqlToSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -120,7 +122,7 @@ function generateColumnsSchema(createDefinitions) {

if (
(type === 'datetime' || type === 'timestamp') &&
definitionSQL.indexOf(' ON UPDATE CURRENT_TIMESTAMP') >= 0
rgxOnUpdateCurTimestamp.test(definitionSQL)
) {
columnDefintion.onUpdateCurrentTimestamp();
}
Expand All @@ -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]);
}
Expand Down
16 changes: 16 additions & 0 deletions test/unit/sqlToSchema.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const ColumnDefinitions = require('../../lib/ColumnDefinitions');

const sqlToSchema = require('../../lib/sqlToSchema');

describe('sqlToSchema', () => {
Expand All @@ -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();
});

});

0 comments on commit 5c6d3c7

Please sign in to comment.