2015-12-04 00:28:18 +08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var _ = require('underscore');
|
|
|
|
var step = require('step');
|
|
|
|
var PSQL = require('cartodb-psql');
|
2016-03-08 21:48:56 +08:00
|
|
|
var CachedQueryTables = require('../services/cached-query-tables');
|
2018-04-24 00:17:44 +08:00
|
|
|
const pgEntitiesAccessValidator = require('../services/pg-entities-access-validator');
|
2016-02-22 19:21:44 +08:00
|
|
|
var queryMayWrite = require('../utils/query_may_write');
|
2015-12-04 00:28:18 +08:00
|
|
|
|
|
|
|
var formats = require('../models/formats');
|
|
|
|
|
|
|
|
var sanitize_filename = require('../utils/filename_sanitizer');
|
|
|
|
var getContentDisposition = require('../utils/content_disposition');
|
2018-05-04 21:15:37 +08:00
|
|
|
const bodyParserMiddleware = require('../middlewares/body-parser');
|
2018-02-17 01:21:06 +08:00
|
|
|
const userMiddleware = require('../middlewares/user');
|
|
|
|
const errorMiddleware = require('../middlewares/error');
|
2018-02-19 22:49:17 +08:00
|
|
|
const authorizationMiddleware = require('../middlewares/authorization');
|
2018-02-22 19:22:39 +08:00
|
|
|
const connectionParamsMiddleware = require('../middlewares/connection-params');
|
2018-02-22 19:45:55 +08:00
|
|
|
const timeoutLimitsMiddleware = require('../middlewares/timeout-limits');
|
2018-02-19 22:13:36 +08:00
|
|
|
const { initializeProfilerMiddleware } = require('../middlewares/profiler');
|
2018-03-01 19:19:57 +08:00
|
|
|
const rateLimitsMiddleware = require('../middlewares/rate-limit');
|
2018-03-01 20:15:32 +08:00
|
|
|
const { RATE_LIMIT_ENDPOINTS_GROUPS } = rateLimitsMiddleware;
|
2019-02-26 21:47:23 +08:00
|
|
|
const handleQueryMiddleware = require('../middlewares/handle-query');
|
2019-02-27 16:02:31 +08:00
|
|
|
const logMiddleware = require('../middlewares/log');
|
2015-12-04 00:28:18 +08:00
|
|
|
|
2019-07-04 16:45:35 +08:00
|
|
|
const ONE_YEAR_IN_SECONDS = 31536000; // ttl in cache provider
|
|
|
|
const FIVE_MINUTES_IN_SECONDS = 60 * 5; // ttl in cache provider
|
2016-01-28 21:08:18 +08:00
|
|
|
|
2018-03-01 18:31:35 +08:00
|
|
|
function QueryController(metadataBackend, userDatabaseService, tableCache, statsd_client, userLimitsService) {
|
2018-02-22 18:46:34 +08:00
|
|
|
this.metadataBackend = metadataBackend;
|
2015-12-04 00:28:18 +08:00
|
|
|
this.statsd_client = statsd_client;
|
2016-01-22 00:24:48 +08:00
|
|
|
this.userDatabaseService = userDatabaseService;
|
2016-03-08 21:48:56 +08:00
|
|
|
this.queryTables = new CachedQueryTables(tableCache);
|
2018-03-01 18:31:35 +08:00
|
|
|
this.userLimitsService = userLimitsService;
|
2015-12-04 00:28:18 +08:00
|
|
|
}
|
|
|
|
|
2015-12-04 01:43:13 +08:00
|
|
|
QueryController.prototype.route = function (app) {
|
2018-02-19 20:24:44 +08:00
|
|
|
const { base_url } = global.settings;
|
2018-06-05 19:14:50 +08:00
|
|
|
const forceToBeMaster = false;
|
|
|
|
|
2018-12-11 01:19:56 +08:00
|
|
|
const queryMiddlewares = () => {
|
2018-03-01 19:19:57 +08:00
|
|
|
return [
|
2018-05-04 21:15:37 +08:00
|
|
|
bodyParserMiddleware(),
|
2018-03-01 19:19:57 +08:00
|
|
|
initializeProfilerMiddleware('query'),
|
2018-05-29 19:23:50 +08:00
|
|
|
userMiddleware(this.metadataBackend),
|
2018-12-11 01:19:56 +08:00
|
|
|
rateLimitsMiddleware(this.userLimitsService, RATE_LIMIT_ENDPOINTS_GROUPS.QUERY),
|
2018-06-05 19:14:50 +08:00
|
|
|
authorizationMiddleware(this.metadataBackend, forceToBeMaster),
|
2018-03-01 19:19:57 +08:00
|
|
|
connectionParamsMiddleware(this.userDatabaseService),
|
|
|
|
timeoutLimitsMiddleware(this.metadataBackend),
|
2019-02-26 21:47:23 +08:00
|
|
|
handleQueryMiddleware(),
|
2019-02-28 18:49:05 +08:00
|
|
|
logMiddleware(logMiddleware.TYPES.QUERY),
|
2018-03-01 19:19:57 +08:00
|
|
|
this.handleQuery.bind(this),
|
|
|
|
errorMiddleware()
|
|
|
|
];
|
2018-03-01 21:47:34 +08:00
|
|
|
};
|
2018-03-01 19:19:57 +08:00
|
|
|
|
2018-12-11 01:19:56 +08:00
|
|
|
app.all(`${base_url}/sql`, queryMiddlewares());
|
|
|
|
app.all(`${base_url}/sql.:f`, queryMiddlewares());
|
2015-12-04 00:28:18 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// jshint maxcomplexity:21
|
2018-02-17 01:21:06 +08:00
|
|
|
QueryController.prototype.handleQuery = function (req, res, next) {
|
2015-12-07 16:40:51 +08:00
|
|
|
var self = this;
|
2018-02-16 17:46:58 +08:00
|
|
|
// clone so don't modify req.params or req.body so oauth is not broken
|
2019-02-26 21:47:23 +08:00
|
|
|
var params = _.extend({}, req.query, req.body || {});
|
2015-12-04 00:28:18 +08:00
|
|
|
var limit = parseInt(params.rows_per_page);
|
|
|
|
var offset = parseInt(params.page);
|
|
|
|
var orderBy = params.order_by;
|
|
|
|
var sortOrder = params.sort_order;
|
|
|
|
var requestedFormat = params.format;
|
|
|
|
var format = _.isArray(requestedFormat) ? _.last(requestedFormat) : requestedFormat;
|
|
|
|
var requestedFilename = params.filename;
|
|
|
|
var filename = requestedFilename;
|
|
|
|
var requestedSkipfields = params.skipfields;
|
2018-02-19 20:24:44 +08:00
|
|
|
|
2019-02-26 23:34:26 +08:00
|
|
|
let { sql } = res.locals;
|
2018-06-05 19:21:56 +08:00
|
|
|
const { user: username, userDbParams: dbopts, authDbParams, userLimits, authorizationLevel } = res.locals;
|
2018-02-19 20:24:44 +08:00
|
|
|
|
2015-12-04 00:28:18 +08:00
|
|
|
var skipfields;
|
|
|
|
var dp = params.dp; // decimal point digits (defaults to 6)
|
2018-02-19 19:37:19 +08:00
|
|
|
var gn = "the_geom"; // TODO: read from configuration FILE
|
2015-12-04 00:28:18 +08:00
|
|
|
|
|
|
|
req.aborted = false;
|
|
|
|
req.on("close", function() {
|
|
|
|
if (req.formatter && _.isFunction(req.formatter.cancel)) {
|
|
|
|
req.formatter.cancel();
|
|
|
|
}
|
|
|
|
req.aborted = true; // TODO: there must be a builtin way to check this
|
|
|
|
});
|
|
|
|
|
|
|
|
function checkAborted(step) {
|
|
|
|
if ( req.aborted ) {
|
|
|
|
var err = new Error("Request aborted during " + step);
|
|
|
|
// We'll use status 499, same as ngnix in these cases
|
|
|
|
// see http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error
|
|
|
|
err.http_status = 499;
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
|
|
// sanitize and apply defaults to input
|
|
|
|
dp = (dp === "" || _.isUndefined(dp)) ? '6' : dp;
|
|
|
|
format = (format === "" || _.isUndefined(format)) ? 'json' : format.toLowerCase();
|
|
|
|
filename = (filename === "" || _.isUndefined(filename)) ? 'cartodb-query' : sanitize_filename(filename);
|
|
|
|
sql = (sql === "" || _.isUndefined(sql)) ? null : sql;
|
|
|
|
limit = (!_.isNaN(limit)) ? limit : null;
|
|
|
|
offset = (!_.isNaN(offset)) ? offset * limit : null;
|
|
|
|
|
|
|
|
// Accept both comma-separated string or array of comma-separated strings
|
|
|
|
if ( requestedSkipfields ) {
|
|
|
|
if ( _.isString(requestedSkipfields) ) {
|
|
|
|
skipfields = requestedSkipfields.split(',');
|
|
|
|
} else if ( _.isArray(requestedSkipfields) ) {
|
|
|
|
skipfields = [];
|
|
|
|
_.each(requestedSkipfields, function(ele) {
|
|
|
|
skipfields = skipfields.concat(ele.split(','));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
skipfields = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
//if ( -1 === supportedFormats.indexOf(format) )
|
|
|
|
if ( ! formats.hasOwnProperty(format) ) {
|
|
|
|
throw new Error("Invalid format: " + format);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!_.isString(sql)) {
|
|
|
|
throw new Error("You must indicate a sql query");
|
|
|
|
}
|
|
|
|
|
|
|
|
var formatter;
|
|
|
|
|
|
|
|
if ( req.profiler ) {
|
|
|
|
req.profiler.done('init');
|
|
|
|
}
|
|
|
|
|
2018-02-19 20:24:44 +08:00
|
|
|
// 1. Get the list of tables affected by the query
|
|
|
|
// 2. Setup headers
|
|
|
|
// 3. Send formatted results back
|
|
|
|
// 4. Handle error
|
2015-12-04 00:28:18 +08:00
|
|
|
step(
|
2018-02-19 20:24:44 +08:00
|
|
|
function queryExplain() {
|
2016-03-08 21:00:31 +08:00
|
|
|
var next = this;
|
|
|
|
|
2015-12-04 00:28:18 +08:00
|
|
|
checkAborted('queryExplain');
|
|
|
|
|
2017-08-09 00:21:10 +08:00
|
|
|
var pg = new PSQL(authDbParams);
|
2018-02-19 20:24:44 +08:00
|
|
|
|
2018-06-05 19:21:56 +08:00
|
|
|
var skipCache = authorizationLevel === 'master';
|
2016-03-08 21:00:31 +08:00
|
|
|
|
2016-03-11 02:20:56 +08:00
|
|
|
self.queryTables.getAffectedTablesFromQuery(pg, sql, skipCache, function(err, result) {
|
2016-03-08 21:00:31 +08:00
|
|
|
if (err) {
|
|
|
|
var errorMessage = (err && err.message) || 'unknown error';
|
|
|
|
console.error("Error on query explain '%s': %s", sql, errorMessage);
|
|
|
|
}
|
|
|
|
return next(null, result);
|
|
|
|
});
|
2015-12-04 00:28:18 +08:00
|
|
|
},
|
2016-02-22 19:21:44 +08:00
|
|
|
function setHeaders(err, affectedTables) {
|
2018-11-08 01:05:39 +08:00
|
|
|
if (err) {
|
|
|
|
throw err;
|
|
|
|
}
|
2015-12-04 00:28:18 +08:00
|
|
|
|
2016-02-22 19:21:44 +08:00
|
|
|
var mayWrite = queryMayWrite(sql);
|
2015-12-04 00:28:18 +08:00
|
|
|
if ( req.profiler ) {
|
|
|
|
req.profiler.done('queryExplain');
|
|
|
|
}
|
|
|
|
|
|
|
|
checkAborted('setHeaders');
|
2018-06-05 19:21:56 +08:00
|
|
|
if(!pgEntitiesAccessValidator.validate(affectedTables, authorizationLevel)) {
|
2018-04-24 00:17:44 +08:00
|
|
|
const syntaxError = new SyntaxError("system tables are forbidden");
|
|
|
|
syntaxError.http_status = 403;
|
|
|
|
throw(syntaxError);
|
2015-12-04 00:28:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
var FormatClass = formats[format];
|
|
|
|
formatter = new FormatClass();
|
|
|
|
req.formatter = formatter;
|
|
|
|
|
|
|
|
|
|
|
|
// configure headers for given format
|
|
|
|
var use_inline = !requestedFormat && !requestedFilename;
|
|
|
|
res.header("Content-Disposition", getContentDisposition(formatter, filename, use_inline));
|
|
|
|
res.header("Content-Type", formatter.getContentType());
|
|
|
|
|
|
|
|
// set cache headers
|
2016-01-28 21:08:18 +08:00
|
|
|
var cachePolicy = req.query.cache_policy;
|
|
|
|
if (cachePolicy === 'persist') {
|
|
|
|
res.header('Cache-Control', 'public,max-age=' + ONE_YEAR_IN_SECONDS);
|
2015-12-04 00:28:18 +08:00
|
|
|
} else {
|
2019-07-04 22:52:18 +08:00
|
|
|
if (affectedTables && affectedTables.getTables().every(table => table.updated_at !== null)) {
|
|
|
|
const maxAge = mayWrite ? 0 : (global.settings.cache.ttl || ONE_YEAR_IN_SECONDS);
|
2019-07-04 16:45:35 +08:00
|
|
|
res.header('Cache-Control', `no-cache,max-age=${maxAge},must-revalidate,public`);
|
|
|
|
} else {
|
2019-07-04 22:52:18 +08:00
|
|
|
const maxAge = global.settings.cache.fallbackTtl || FIVE_MINUTES_IN_SECONDS;
|
2019-07-04 16:45:35 +08:00
|
|
|
res.header('Cache-Control', `no-cache,max-age=${maxAge},must-revalidate,public`);
|
|
|
|
}
|
2015-12-04 00:28:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Only set an X-Cache-Channel for responses we want Varnish to cache.
|
2016-07-11 22:39:12 +08:00
|
|
|
var skipNotUpdatedAtTables = true;
|
|
|
|
if (!!affectedTables && affectedTables.getTables(skipNotUpdatedAtTables).length > 0 && !mayWrite) {
|
|
|
|
res.header('X-Cache-Channel', affectedTables.getCacheChannel(skipNotUpdatedAtTables));
|
|
|
|
res.header('Surrogate-Key', affectedTables.key(skipNotUpdatedAtTables).join(' '));
|
2015-12-04 00:28:18 +08:00
|
|
|
}
|
|
|
|
|
2016-02-23 02:08:04 +08:00
|
|
|
if(!!affectedTables) {
|
|
|
|
res.header('Last-Modified',
|
|
|
|
new Date(affectedTables.getLastUpdatedAt(Number(new Date()))).toUTCString());
|
|
|
|
}
|
2015-12-04 00:28:18 +08:00
|
|
|
|
|
|
|
return null;
|
|
|
|
},
|
|
|
|
function generateFormat(err){
|
2018-11-08 01:05:39 +08:00
|
|
|
if (err) {
|
|
|
|
throw err;
|
|
|
|
}
|
2015-12-04 00:28:18 +08:00
|
|
|
checkAborted('generateFormat');
|
|
|
|
|
|
|
|
// TODO: drop this, fix UI!
|
|
|
|
sql = new PSQL.QueryWrapper(sql).orderBy(orderBy, sortOrder).window(limit, offset).query();
|
|
|
|
|
|
|
|
var opts = {
|
2018-02-19 20:24:44 +08:00
|
|
|
username: username,
|
2015-12-04 00:28:18 +08:00
|
|
|
dbopts: dbopts,
|
|
|
|
sink: res,
|
|
|
|
gn: gn,
|
|
|
|
dp: dp,
|
|
|
|
skipfields: skipfields,
|
|
|
|
sql: sql,
|
|
|
|
filename: filename,
|
|
|
|
bufferedRows: global.settings.bufferedRows,
|
|
|
|
callback: params.callback,
|
2017-08-09 18:50:16 +08:00
|
|
|
abortChecker: checkAborted,
|
|
|
|
timeout: userLimits.timeout
|
2015-12-04 00:28:18 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
if ( req.profiler ) {
|
|
|
|
opts.profiler = req.profiler;
|
|
|
|
opts.beforeSink = function() {
|
|
|
|
req.profiler.done('beforeSink');
|
|
|
|
res.header('X-SQLAPI-Profiler', req.profiler.toJSONString());
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
if (dbopts.host) {
|
|
|
|
res.header('X-Served-By-DB-Host', dbopts.host);
|
|
|
|
}
|
2019-02-27 16:02:31 +08:00
|
|
|
|
2015-12-04 00:28:18 +08:00
|
|
|
formatter.sendResponse(opts, this);
|
|
|
|
},
|
|
|
|
function errorHandle(err){
|
|
|
|
formatter = null;
|
|
|
|
|
2018-02-17 01:21:06 +08:00
|
|
|
if (err) {
|
|
|
|
next(err);
|
2015-12-04 00:28:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if ( req.profiler ) {
|
2018-02-19 22:13:36 +08:00
|
|
|
req.profiler.sendStats();
|
2015-12-04 00:28:18 +08:00
|
|
|
}
|
2015-12-07 16:40:51 +08:00
|
|
|
if (self.statsd_client) {
|
2015-12-04 00:28:18 +08:00
|
|
|
if ( err ) {
|
2015-12-07 16:40:51 +08:00
|
|
|
self.statsd_client.increment('sqlapi.query.error');
|
2015-12-04 00:28:18 +08:00
|
|
|
} else {
|
2015-12-07 16:40:51 +08:00
|
|
|
self.statsd_client.increment('sqlapi.query.success');
|
2015-12-04 00:28:18 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
} catch (err) {
|
2018-02-17 01:21:06 +08:00
|
|
|
next(err);
|
2015-12-04 00:28:18 +08:00
|
|
|
|
2015-12-07 16:40:51 +08:00
|
|
|
if (self.statsd_client) {
|
|
|
|
self.statsd_client.increment('sqlapi.query.error');
|
2015-12-04 00:28:18 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = QueryController;
|