2018-10-23 23:45:42 +08:00
|
|
|
'use strict';
|
|
|
|
|
2018-06-01 00:46:23 +08:00
|
|
|
const DATE_OIDS = Object.freeze({
|
|
|
|
1082: 'DATE',
|
|
|
|
1083: 'TIME',
|
|
|
|
1114: 'TIMESTAMP',
|
|
|
|
1184: 'TIMESTAMPTZ',
|
|
|
|
1266: 'TIMETZ'
|
|
|
|
});
|
2018-05-31 18:41:34 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Wrap a query transforming all date columns into a unix epoch
|
2018-06-05 21:39:01 +08:00
|
|
|
* @param {*} originalQuery
|
|
|
|
* @param {*} fields
|
2018-05-31 18:41:34 +08:00
|
|
|
*/
|
2019-10-22 01:07:24 +08:00
|
|
|
function wrapDates (originalQuery, fields) {
|
2018-05-31 18:41:34 +08:00
|
|
|
return `
|
2018-06-05 21:39:01 +08:00
|
|
|
SELECT
|
2019-10-22 01:07:24 +08:00
|
|
|
${fields.map(field => _isDateType(field) ? _castColumnToEpoch(field.name) : `"${field.name}"`).join(',')}
|
2018-06-05 21:39:01 +08:00
|
|
|
FROM
|
2018-05-31 18:41:34 +08:00
|
|
|
(${originalQuery}) _cdb_epoch_transformation `;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2018-06-05 21:39:01 +08:00
|
|
|
* @param {object} field
|
2018-05-31 18:41:34 +08:00
|
|
|
*/
|
2019-10-22 01:07:24 +08:00
|
|
|
function _isDateType (field) {
|
2019-10-22 05:33:27 +08:00
|
|
|
return Object.prototype.hasOwnProperty.call(DATE_OIDS, field.dataTypeID);
|
2018-05-31 18:41:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return a sql query to transform a date column into a unix epoch
|
|
|
|
* @param {string} column - The name of the date column
|
|
|
|
*/
|
2019-10-22 01:07:24 +08:00
|
|
|
function _castColumnToEpoch (columnName) {
|
2018-06-05 21:39:01 +08:00
|
|
|
return `date_part('epoch', "${columnName}") as "${columnName}"`;
|
|
|
|
}
|
|
|
|
|
2019-10-22 01:07:24 +08:00
|
|
|
function getColumnsWithWrappedDates (query) {
|
|
|
|
if (!query) {
|
2018-06-13 15:38:24 +08:00
|
|
|
return;
|
|
|
|
}
|
2018-06-13 15:42:53 +08:00
|
|
|
if (!query.match(/\b_cdb_epoch_transformation\b/)) {
|
|
|
|
return;
|
2018-06-05 21:39:01 +08:00
|
|
|
}
|
2018-06-13 15:42:53 +08:00
|
|
|
const columns = [];
|
|
|
|
const fieldMatcher = /\bdate_part\('epoch', "([^"]+)"\) as "([^"]+)"/gmi;
|
|
|
|
let match;
|
|
|
|
do {
|
|
|
|
match = fieldMatcher.exec(query);
|
|
|
|
if (match && match[1] === match[2]) {
|
|
|
|
columns.push(match[1]);
|
|
|
|
}
|
|
|
|
} while (match);
|
|
|
|
return columns;
|
2018-05-31 18:41:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2018-06-05 21:39:01 +08:00
|
|
|
wrapDates,
|
2018-06-12 18:59:10 +08:00
|
|
|
getColumnsWithWrappedDates
|
2018-06-13 15:42:53 +08:00
|
|
|
};
|