Skip to content

Commit 5c6d3c7

Browse files
committed
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
1 parent ed932c9 commit 5c6d3c7

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

lib/sqlToSchema.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ function generateColumnsSchema(createDefinitions) {
7878
const rgxDefault = / DEFAULT (?:'((?:''|[^'])*?)'(?!')|(\S+))/;
7979
const rgxCharset = / CHARACTER SET (\w+)/;
8080
const rgxCollate = / COLLATE (\w+)/;
81+
// Support MariaDB. See: https://github.com/nwoltman/node-mysql-plus/issues/4
82+
const rgxOnUpdateCurTimestamp = / ON UPDATE (?:CURRENT_TIMESTAMP\b|current_timestamp\(\))/;
8183

8284
for (var i = 0; i < createDefinitions.length; i++) {
8385
const definitionSQL = createDefinitions[i].trim();
@@ -120,7 +122,7 @@ function generateColumnsSchema(createDefinitions) {
120122

121123
if (
122124
(type === 'datetime' || type === 'timestamp') &&
123-
definitionSQL.indexOf(' ON UPDATE CURRENT_TIMESTAMP') >= 0
125+
rgxOnUpdateCurTimestamp.test(definitionSQL)
124126
) {
125127
columnDefintion.onUpdateCurrentTimestamp();
126128
}
@@ -129,7 +131,12 @@ function generateColumnsSchema(createDefinitions) {
129131

130132
if (match = rgxDefault.exec(definitionSQL)) {
131133
if (match[2]) {
132-
columnDefintion.$defaultRaw(match[2]);
134+
let rawDefault = match[2];
135+
if (rawDefault === 'current_timestamp()') {
136+
// Support MariaDB. See: https://github.com/nwoltman/node-mysql-plus/issues/4
137+
rawDefault = 'CURRENT_TIMESTAMP';
138+
}
139+
columnDefintion.$defaultRaw(rawDefault);
133140
} else {
134141
columnDefintion.default(match[1]);
135142
}

test/unit/sqlToSchema.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
'use strict';
22

3+
const ColumnDefinitions = require('../../lib/ColumnDefinitions');
4+
35
const sqlToSchema = require('../../lib/sqlToSchema');
46

57
describe('sqlToSchema', () => {
@@ -19,4 +21,18 @@ describe('sqlToSchema', () => {
1921
});
2022
});
2123

24+
it('should translate MariaDB DEFAULT and ON UPDATE current_timestamp() to be compatible with CURRENT_TIMESTAMP', () => {
25+
const schema = sqlToSchema(`
26+
CREATE TABLE \`test\` (
27+
\`dt\` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
28+
)
29+
`);
30+
31+
ColumnDefinitions.datetime()
32+
.defaultCurrentTimestamp()
33+
.onUpdateCurrentTimestamp()
34+
.$equals(schema.columns.dt)
35+
.should.be.true();
36+
});
37+
2238
});

0 commit comments

Comments
 (0)