Windshaft-cartodb/lib/cartodb/utils/date-wrapper.js

57 lines
1.4 KiB
JavaScript
Raw Normal View History

const DATE_OIDS = Object.freeze({
1082: 'DATE',
1083: 'TIME',
1114: 'TIMESTAMP',
1184: 'TIMESTAMPTZ',
1266: 'TIMETZ'
});
/**
* Wrap a query transforming all date columns into a unix epoch
2018-06-05 21:39:01 +08:00
* @param {*} originalQuery
* @param {*} fields
*/
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
(${originalQuery}) _cdb_epoch_transformation `;
}
/**
2018-06-05 21:39:01 +08:00
* @param {object} field
*/
function _isDateType(field) {
return DATE_OIDS.hasOwnProperty(field.dataTypeID);
}
/**
* 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) {
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
}
}
module.exports = {
2018-06-05 21:39:01 +08:00
wrapDates,
2018-06-12 18:59:10 +08:00
getColumnsWithWrappedDates
};