From ebb7210736c30aa9a7b845c060996a05559d2563 Mon Sep 17 00:00:00 2001 From: Wing-Kam Wong Date: Sat, 29 Apr 2023 17:05:40 +0800 Subject: [PATCH] feat(nocodb): add type cast for mysql --- .../nocodb-nest/src/utils/NcConfigFactory.ts | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/packages/nocodb-nest/src/utils/NcConfigFactory.ts b/packages/nocodb-nest/src/utils/NcConfigFactory.ts index 5fd54e6676..3914c185c3 100644 --- a/packages/nocodb-nest/src/utils/NcConfigFactory.ts +++ b/packages/nocodb-nest/src/utils/NcConfigFactory.ts @@ -4,6 +4,8 @@ import { promisify } from 'util'; import * as path from 'path'; import parseDbUrl from 'parse-database-url'; import { SqlClientFactory } from '../db/sql-client/lib/SqlClientFactory'; +import dayjs from 'dayjs'; +import utc from 'dayjs/plugin/utc'; // import SqlClientFactory from '../db/sql-client/lib/SqlClientFactory'; // import type { // AuthConfig, @@ -19,6 +21,8 @@ import { SqlClientFactory } from '../db/sql-client/lib/SqlClientFactory'; // animals, // } = require('unique-names-generator'); +dayjs.extend(utc); + type NcConfig = any; type DbConfig = any; @@ -236,6 +240,11 @@ export default class NcConfigFactory { acquireConnectionTimeout: 600000, } as any; + dbConfig.connection = this.addTypeCastConfig( + url.protocol, + dbConfig.connection, + ); + if (process.env.NODE_TLS_REJECT_UNAUTHORIZED) { dbConfig.connection.ssl = true; } @@ -297,6 +306,16 @@ export default class NcConfigFactory { .replace(/[ -]/g, '_');*/ } + private static addTypeCastConfig(clientType: string, connection) { + if (clientType.startsWith('mysql')) { + connection = { + ...connection, + ...this.mysqlConnectionTypeCastConfig, + }; + } + return connection; + } + static async metaUrlToDbConfig(urlString) { const url = new URL(urlString); @@ -348,6 +367,12 @@ export default class NcConfigFactory { } : {}), }; + + dbConfig.connection = this.addTypeCastConfig( + url.protocol, + dbConfig.connection, + ); + if (process.env.NODE_TLS_REJECT_UNAUTHORIZED) { dbConfig.connection.ssl = true; } @@ -511,6 +536,11 @@ export default class NcConfigFactory { }; } + dbConfig.connection = this.addTypeCastConfig( + dbConfig.client, + dbConfig.connection, + ); + // todo: const key = ''; Object.assign(dbConfig, { @@ -744,6 +774,22 @@ export default class NcConfigFactory { return res; } + // mysql driver will cast mysql types into native JavaScript types by default + // hence we use typeCast to convert to the expected value (UTC) for date time fields + private static mysqlConnectionTypeCastConfig = { + typeCast: function (field, next) { + if (field.type === 'DATETIME' || field.type === 'TIMESTAMP') { + const d = dayjs(field.string()); + if (!d.isValid()) { + return null; + } + return d.utc().format('YYYY-MM-DD HH:mm:ss'); + } + return next(); + }, + timezone: '+00:00', + }; + // public static initOneClickDeployment() { // if (process.env.NC_ONE_CLICK) { // const url = NcConfigFactory.extractXcUrlFromJdbc(process.env.DATABASE_URL);