From 9d104016bdda3f1f1905b133293d1ca5e7307632 Mon Sep 17 00:00:00 2001 From: Wing-Kam Wong Date: Wed, 7 Dec 2022 19:56:36 +0800 Subject: [PATCH] feat(nocodb): add DATETIME_DIFF logic for mysql --- .../lib/sql/functionMappings/mysql.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/packages/nocodb/src/lib/db/sql-data-mapper/lib/sql/functionMappings/mysql.ts b/packages/nocodb/src/lib/db/sql-data-mapper/lib/sql/functionMappings/mysql.ts index ab1acb763b..2512437c17 100644 --- a/packages/nocodb/src/lib/db/sql-data-mapper/lib/sql/functionMappings/mysql.ts +++ b/packages/nocodb/src/lib/db/sql-data-mapper/lib/sql/functionMappings/mysql.ts @@ -1,6 +1,7 @@ import dayjs from 'dayjs'; import { MapFnArgs } from '../mapFunctionName'; import commonFns from './commonFns'; +import { convertUnits } from '../helpers/convertUnits'; import { getWeekdayByText } from '../helpers/formulaFnHelper'; const mysql2 = { @@ -61,6 +62,26 @@ const mysql2 = { END${colAlias}` ); }, + DATETIME_DIFF: ({ fn, knex, pt, colAlias }: MapFnArgs) => { + const datetime_expr1 = fn(pt.arguments[0]); + const datetime_expr2 = fn(pt.arguments[1]); + + const unit = convertUnits( + pt.arguments[2] ? fn(pt.arguments[2]).bindings[0] : 'seconds', + 'mysql' + ); + + if (unit === 'MICROSECOND') { + // MySQL doesn't support millisecond + // hence change from MICROSECOND to millisecond manually + return knex.raw( + `TIMESTAMPDIFF(${unit}, ${datetime_expr2}, ${datetime_expr1}) div 1000 ${colAlias}` + ); + } + return knex.raw( + `TIMESTAMPDIFF(${unit}, ${datetime_expr2}, ${datetime_expr1}) ${colAlias}` + ); + }, WEEKDAY: ({ fn, knex, pt, colAlias }: MapFnArgs) => { // WEEKDAY() returns an index from 0 to 6 for Monday to Sunday return knex.raw(