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
|
|
|
*/
|
|
|
|
function wrapDates(originalQuery, fields) {
|
|
|
|
return `
|
2018-06-05 21:39:01 +08:00
|
|
|
SELECT
|
|
|
|
${fields.map(field => _isDateType(field) ? _castColumnToEpoch(field.name) : `${field.name}`).join(',')}
|
|
|
|
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
|
|
|
*/
|
2018-06-01 00:46:23 +08:00
|
|
|
function _isDateType(field) {
|
|
|
|
return DATE_OIDS.hasOwnProperty(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
|
|
|
|
*/
|
|
|
|
function _castColumnToEpoch(columnName) {
|
2018-06-05 21:39:01 +08:00
|
|
|
return `date_part('epoch', "${columnName}") as "${columnName}"`;
|
|
|
|
}
|
|
|
|
|
2018-06-12 18:59:10 +08:00
|
|
|
function getColumnsWithWrappedDates(query) {
|
2018-06-12 18:05:31 +08:00
|
|
|
if (query) {
|
|
|
|
if (query.match(/\b_cdb_epoch_transformation\b/)) {
|
|
|
|
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-06-05 21:39:01 +08:00
|
|
|
}
|
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-05-31 18:41:34 +08:00
|
|
|
};
|