CartoDB-SQL-API/app/controllers/query_controller.js

169 lines
6.1 KiB
JavaScript
Raw Normal View History

'use strict';
var step = require('step');
var PSQL = require('cartodb-psql');
const formats = require('../models/formats');
var getContentDisposition = require('../utils/content_disposition');
const bodyParserMiddleware = require('../middlewares/body-parser');
const userMiddleware = require('../middlewares/user');
const errorMiddleware = require('../middlewares/error');
2018-02-19 22:49:17 +08:00
const authorizationMiddleware = require('../middlewares/authorization');
const connectionParamsMiddleware = require('../middlewares/connection-params');
const timeoutLimitsMiddleware = require('../middlewares/timeout-limits');
const { initializeProfilerMiddleware } = require('../middlewares/profiler');
const rateLimitsMiddleware = require('../middlewares/rate-limit');
2018-03-01 20:15:32 +08:00
const { RATE_LIMIT_ENDPOINTS_GROUPS } = rateLimitsMiddleware;
2019-07-26 23:18:18 +08:00
const parameters = require('../middlewares/parameters');
2019-02-27 16:02:31 +08:00
const logMiddleware = require('../middlewares/log');
const cancelOnClientAbort = require('../middlewares/cancel-on-client-abort');
2019-07-26 23:44:28 +08:00
const affectedTables = require('../middlewares/affected-tables');
2019-07-27 00:05:47 +08:00
const accessValidator = require('../middlewares/access-validator');
2019-07-27 00:23:14 +08:00
const queryMayWrite = require('../middlewares/query-may-write');
const cacheControl = require('../middlewares/cache-control');
const cacheChannel = require('../middlewares/cache-channel');
const surrogateKey = require('../middlewares/surrogate-key');
2019-07-24 23:44:04 +08:00
function QueryController(metadataBackend, userDatabaseService, statsd_client, userLimitsService) {
this.metadataBackend = metadataBackend;
this.statsd_client = statsd_client;
this.userDatabaseService = userDatabaseService;
2018-03-01 18:31:35 +08:00
this.userLimitsService = userLimitsService;
}
2015-12-04 01:43:13 +08:00
QueryController.prototype.route = function (app) {
const { base_url } = global.settings;
const forceToBeMaster = false;
const queryMiddlewares = () => {
return [
bodyParserMiddleware(),
initializeProfilerMiddleware('query'),
userMiddleware(this.metadataBackend),
rateLimitsMiddleware(this.userLimitsService, RATE_LIMIT_ENDPOINTS_GROUPS.QUERY),
authorizationMiddleware(this.metadataBackend, forceToBeMaster),
connectionParamsMiddleware(this.userDatabaseService),
timeoutLimitsMiddleware(this.metadataBackend),
2019-07-26 23:18:18 +08:00
parameters({ strategy: 'query' }),
2019-02-28 18:49:05 +08:00
logMiddleware(logMiddleware.TYPES.QUERY),
cancelOnClientAbort(),
2019-07-26 23:44:28 +08:00
affectedTables(),
2019-07-27 00:05:47 +08:00
accessValidator(),
2019-07-27 00:23:14 +08:00
queryMayWrite(),
cacheControl(),
cacheChannel(),
surrogateKey(),
this.handleQuery.bind(this),
errorMiddleware()
];
2018-03-01 21:47:34 +08:00
};
app.all(`${base_url}/sql`, queryMiddlewares());
app.all(`${base_url}/sql.:f`, queryMiddlewares());
};
// jshint maxcomplexity:21
QueryController.prototype.handleQuery = function (req, res, next) {
var self = this;
2019-07-26 23:44:28 +08:00
const {
user: username,
userDbParams: dbopts,
userLimits,
2019-07-27 00:23:14 +08:00
affectedTables,
mayWrite
2019-07-26 23:44:28 +08:00
} = res.locals;
const { orderBy, sortOrder, limit, offset } = res.locals.params;
2019-07-26 23:44:28 +08:00
const { sql, format, skipfields, decimalPrecision, filename, callback } = res.locals.params;
try {
let formatter;
if (req.profiler) {
req.profiler.done('init');
}
2019-07-26 23:44:28 +08:00
// 1. Setup headers
// 2. Send formatted results back
// 3. Handle error
step(
2019-07-26 23:44:28 +08:00
function setHeaders() {
var FormatClass = formats[format];
formatter = new FormatClass();
req.formatter = formatter;
// configure headers for given format
var useInline = (!req.query.format && !req.body.format && !req.query.filename && !req.body.filename);
res.header("Content-Disposition", getContentDisposition(formatter, filename, useInline));
res.header("Content-Type", formatter.getContentType());
if(!!affectedTables) {
res.header('Last-Modified',
new Date(affectedTables.getLastUpdatedAt(Number(new Date()))).toUTCString());
}
return null;
},
function generateFormat(err){
if (err) {
throw err;
}
var opts = {
username: username,
dbopts: dbopts,
sink: res,
gn: 'the_geom', // TODO: read from configuration FILE,
dp: decimalPrecision,
skipfields: skipfields,
2019-07-26 23:44:28 +08:00
sql: new PSQL.QueryWrapper(sql).orderBy(orderBy, sortOrder).window(limit, offset).query(),
filename: filename,
bufferedRows: global.settings.bufferedRows,
callback: callback,
2017-08-09 18:50:16 +08:00
timeout: userLimits.timeout
};
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
formatter.sendResponse(opts, this);
},
function errorHandle(err){
formatter = null;
if (err) {
next(err);
}
if ( req.profiler ) {
req.profiler.sendStats();
}
if (self.statsd_client) {
if ( err ) {
self.statsd_client.increment('sqlapi.query.error');
} else {
self.statsd_client.increment('sqlapi.query.success');
}
}
}
);
} catch (err) {
next(err);
if (self.statsd_client) {
self.statsd_client.increment('sqlapi.query.error');
}
}
};
module.exports = QueryController;