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

62 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

'use strict';
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
*/
2019-10-22 01:07:24 +08:00
function wrapDates (originalQuery, fields) {
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
(${originalQuery}) _cdb_epoch_transformation `;
}
/**
2018-06-05 21:39:01 +08:00
* @param {object} field
*/
2019-10-22 01:07:24 +08:00
function _isDateType (field) {
return Object.prototype.hasOwnProperty.call(DATE_OIDS, field.dataTypeID);
}
/**
* 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;
}
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
};