2011-08-24 04:42:27 +08:00
|
|
|
// CartoDB SQL API
|
2011-06-13 11:23:02 +08:00
|
|
|
//
|
|
|
|
// all requests expect the following URL args:
|
|
|
|
// - `sql` {String} SQL to execute
|
|
|
|
//
|
|
|
|
// for private (read/write) queries:
|
2011-08-24 04:42:27 +08:00
|
|
|
// - OAuth. Must have proper OAuth 1.1 headers. For OAuth 1.1 spec see Google
|
2011-06-13 11:23:02 +08:00
|
|
|
//
|
2011-08-24 04:42:27 +08:00
|
|
|
// eg. /api/v1/?sql=SELECT 1 as one (with a load of OAuth headers or URL arguments)
|
2011-06-13 11:23:02 +08:00
|
|
|
//
|
|
|
|
// for public (read only) queries:
|
2011-08-24 04:42:27 +08:00
|
|
|
// - sql only, provided the subdomain exists in CartoDB and the table's sharing options are public
|
2011-06-13 11:23:02 +08:00
|
|
|
//
|
2011-08-24 04:42:27 +08:00
|
|
|
// eg. vizzuality.cartodb.com/api/v1/?sql=SELECT * from my_table
|
2012-04-13 22:37:09 +08:00
|
|
|
var express = require('express')
|
2011-09-21 10:15:43 +08:00
|
|
|
, app = express.createServer(
|
2011-12-14 08:50:56 +08:00
|
|
|
express.logger({
|
|
|
|
buffer: true,
|
|
|
|
format: '[:date] :req[X-Real-IP] \033[90m:method\033[0m \033[36m:req[Host]:url\033[0m \033[90m:status :response-time ms -> :res[Content-Type]\033[0m'
|
|
|
|
}))
|
2012-05-01 23:46:30 +08:00
|
|
|
, Step = require('step')
|
|
|
|
, csv = require('csv')
|
|
|
|
, crypto = require('crypto')
|
|
|
|
, Meta = require(global.settings.app_root + '/app/models/metadata')
|
|
|
|
, oAuth = require(global.settings.app_root + '/app/models/oauth')
|
|
|
|
, PSQL = require(global.settings.app_root + '/app/models/psql')
|
|
|
|
, ApiKeyAuth = require(global.settings.app_root + '/app/models/apikey_auth')
|
|
|
|
, _ = require('underscore')
|
|
|
|
, tableCache = {};
|
2011-08-24 04:42:27 +08:00
|
|
|
|
2011-09-07 19:05:10 +08:00
|
|
|
app.use(express.bodyParser());
|
2011-08-24 04:42:27 +08:00
|
|
|
app.enable('jsonp callback');
|
2011-09-07 19:05:10 +08:00
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
// basic routing
|
|
|
|
app.all('/api/v1/sql', function(req, res) { handleQuery(req, res) } );
|
2011-11-08 03:24:08 +08:00
|
|
|
app.all('/api/v1/sql.:f', function(req, res) { handleQuery(req, res) } );
|
2012-05-01 23:46:30 +08:00
|
|
|
app.get('/api/v1/cachestatus', function(req, res) { handleCacheStatus(req, res) } );
|
|
|
|
|
|
|
|
// request handlers
|
2011-09-21 09:04:26 +08:00
|
|
|
function handleQuery(req, res){
|
2011-07-04 23:28:39 +08:00
|
|
|
|
2011-08-24 19:54:26 +08:00
|
|
|
// sanitize input
|
2011-09-07 19:05:10 +08:00
|
|
|
var body = (req.body) ? req.body : {};
|
|
|
|
var sql = req.query.q || body.q; // get and post
|
2011-12-27 02:16:41 +08:00
|
|
|
var api_key = req.query.api_key || body.api_key;
|
2011-08-24 04:42:27 +08:00
|
|
|
var database = req.query.database; // deprecate this in future
|
|
|
|
var limit = parseInt(req.query.rows_per_page);
|
|
|
|
var offset = parseInt(req.query.page);
|
2011-10-28 19:11:18 +08:00
|
|
|
var format = (req.query.format) ? req.query.format : null;
|
2011-11-09 07:35:59 +08:00
|
|
|
var dp = (req.query.dp) ? req.query.dp: '15';
|
2011-10-28 19:11:18 +08:00
|
|
|
|
|
|
|
// validate input slightly
|
2012-04-21 02:34:18 +08:00
|
|
|
dp = (dp === "") ? '15' : dp;
|
2011-10-28 19:11:18 +08:00
|
|
|
format = (format === "") ? null : format;
|
|
|
|
sql = (sql === "") ? null : sql;
|
|
|
|
database = (database === "") ? null : database;
|
2011-08-24 04:42:27 +08:00
|
|
|
limit = (_.isNumber(limit)) ? limit : null;
|
2011-08-24 19:54:26 +08:00
|
|
|
offset = (_.isNumber(offset)) ? offset * limit : null
|
2011-08-24 04:42:27 +08:00
|
|
|
|
2011-08-24 19:54:26 +08:00
|
|
|
// setup step run
|
2011-08-24 04:42:27 +08:00
|
|
|
var start = new Date().getTime();
|
2012-05-01 23:46:30 +08:00
|
|
|
|
2011-08-24 04:42:27 +08:00
|
|
|
try {
|
|
|
|
if (!_.isString(sql)) throw new Error("You must indicate a sql query");
|
2012-05-08 22:28:22 +08:00
|
|
|
|
|
|
|
// initialise MD5 key of sql for cache lookups
|
|
|
|
var sql_md5 = generateMD5(sql);
|
|
|
|
|
|
|
|
// placeholder for connection
|
2012-05-08 22:25:19 +08:00
|
|
|
var pg;
|
2011-08-24 04:42:27 +08:00
|
|
|
|
|
|
|
// 1. Get database from redis via the username stored in the host header subdomain
|
|
|
|
// 2. Run the request through OAuth to get R/W user id if signed
|
2012-04-21 02:34:18 +08:00
|
|
|
// 3. Get the list of tables affected by the query
|
|
|
|
// 4. Run query with r/w or public user
|
|
|
|
// 5. package results and send back
|
2011-08-24 04:42:27 +08:00
|
|
|
Step(
|
|
|
|
function getDatabaseName(){
|
|
|
|
Meta.getDatabase(req, this);
|
|
|
|
},
|
|
|
|
function setDBGetUser(err, data) {
|
|
|
|
if (err) throw err;
|
2011-08-25 03:47:10 +08:00
|
|
|
database = (data == "" || _.isNull(data)) ? database : data;
|
2012-05-08 22:25:19 +08:00
|
|
|
|
2011-12-27 02:16:41 +08:00
|
|
|
if(api_key) {
|
|
|
|
ApiKeyAuth.verifyRequest(req, this);
|
|
|
|
} else {
|
|
|
|
oAuth.verifyRequest(req, this);
|
|
|
|
}
|
2011-08-24 04:42:27 +08:00
|
|
|
},
|
2012-04-21 02:34:18 +08:00
|
|
|
function queryExplain(err, user_id){
|
2011-08-24 04:42:27 +08:00
|
|
|
if (err) throw err;
|
2012-04-21 02:34:18 +08:00
|
|
|
// store postgres connection
|
2011-08-24 04:42:27 +08:00
|
|
|
pg = new PSQL(user_id, database, limit, offset);
|
2011-10-28 19:11:18 +08:00
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
// get all the tables from Cache or SQL
|
|
|
|
if (!_.isNull(tableCache[sql_md5]) && !_.isUndefined(tableCache[sql_md5])){
|
|
|
|
tableCache[sql_md5].hits++;
|
|
|
|
return true;
|
|
|
|
} else{
|
2012-05-02 03:55:12 +08:00
|
|
|
pg.query("SELECT CDB_QueryTables($quotesql$" + sql + "$quotesql$)", this);
|
2012-05-01 23:46:30 +08:00
|
|
|
}
|
2012-04-21 02:34:18 +08:00
|
|
|
},
|
|
|
|
function queryResult(err, result){
|
|
|
|
if (err) throw err;
|
2012-04-21 04:09:31 +08:00
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
// store explain result in local Cache
|
|
|
|
if (_.isUndefined(tableCache[sql_md5])){
|
|
|
|
tableCache[sql_md5] = result;
|
|
|
|
tableCache[sql_md5].hits = 1; //initialise hit counter
|
|
|
|
}
|
2012-04-21 02:34:18 +08:00
|
|
|
|
2011-10-28 19:11:18 +08:00
|
|
|
// TODO: refactor formats to external object
|
|
|
|
if (format === 'geojson'){
|
2011-11-09 07:35:59 +08:00
|
|
|
sql = ['SELECT *, ST_AsGeoJSON(the_geom,',dp,') as the_geom FROM (', sql, ') as foo'].join("");
|
2011-10-28 19:11:18 +08:00
|
|
|
}
|
|
|
|
|
2011-08-24 04:42:27 +08:00
|
|
|
pg.query(sql, this);
|
|
|
|
},
|
2012-04-13 22:37:09 +08:00
|
|
|
function setHeaders(err, result){
|
|
|
|
if (err) throw err;
|
|
|
|
|
|
|
|
// configure headers for geojson/CSV
|
|
|
|
res.header("Content-Disposition", getContentDisposition(format));
|
|
|
|
res.header("Content-Type", getContentType(format));
|
|
|
|
|
|
|
|
// allow cross site post
|
|
|
|
setCrossDomain(res);
|
|
|
|
|
|
|
|
// set cache headers
|
|
|
|
res.header('Last-Modified', new Date().toUTCString());
|
|
|
|
res.header('Cache-Control', 'no-cache,max-age=3600,must-revalidate, public');
|
2012-05-01 23:46:30 +08:00
|
|
|
res.header('X-Cache-Channel', generateCacheKey(database, tableCache[sql_md5]));
|
2012-04-13 22:37:09 +08:00
|
|
|
|
|
|
|
return result;
|
|
|
|
},
|
2011-08-24 04:42:27 +08:00
|
|
|
function packageResults(err, result){
|
|
|
|
if (err) throw err;
|
2011-10-28 19:11:18 +08:00
|
|
|
|
|
|
|
// TODO: refactor formats to external object
|
|
|
|
if (format === 'geojson'){
|
|
|
|
toGeoJSON(result, res, this);
|
2012-04-13 07:30:45 +08:00
|
|
|
} else if (format === 'csv'){
|
|
|
|
toCSV(result, res, this);
|
2011-10-28 19:11:18 +08:00
|
|
|
} else {
|
|
|
|
var end = new Date().getTime();
|
|
|
|
return {
|
|
|
|
'time' : ((end - start)/1000),
|
|
|
|
'total_rows': result.rows.length,
|
|
|
|
'rows' : result.rows
|
|
|
|
};
|
|
|
|
}
|
|
|
|
},
|
|
|
|
function sendResults(err, out){
|
|
|
|
if (err) throw err;
|
|
|
|
|
|
|
|
// return to browser
|
|
|
|
res.send(out);
|
2011-08-24 04:42:27 +08:00
|
|
|
},
|
|
|
|
function errorHandle(err, result){
|
|
|
|
handleException(err, res);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
} catch (err) {
|
2011-09-07 19:05:10 +08:00
|
|
|
console.log('[ERROR]\n' + err);
|
2011-08-18 01:42:19 +08:00
|
|
|
handleException(err, res);
|
2011-08-24 04:42:27 +08:00
|
|
|
}
|
2011-09-07 19:05:10 +08:00
|
|
|
}
|
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
function handleCacheStatus(req, res){
|
|
|
|
var tableCacheValues = _.values(tableCache);
|
|
|
|
var totalExplainHits = _.reduce(tableCacheValues, function(memo, res) { return memo + res.hits}, 0);
|
|
|
|
var totalExplainKeys = tableCacheValues.length;
|
|
|
|
|
|
|
|
res.send({explain: {hits: totalExplainHits, keys : totalExplainKeys }});
|
|
|
|
}
|
|
|
|
|
|
|
|
// helper functions
|
2011-10-28 19:11:18 +08:00
|
|
|
function toGeoJSON(data, res, callback){
|
|
|
|
try{
|
|
|
|
var out = {
|
|
|
|
type: "FeatureCollection",
|
|
|
|
features: []
|
|
|
|
};
|
|
|
|
|
|
|
|
_.each(data.rows, function(ele){
|
|
|
|
var geojson = {
|
|
|
|
type: "Feature",
|
|
|
|
properties: { },
|
|
|
|
geometry: { }
|
|
|
|
};
|
|
|
|
geojson.geometry = JSON.parse(ele["the_geom"]);
|
|
|
|
delete ele["the_geom"];
|
|
|
|
delete ele["the_geom_webmercator"];
|
|
|
|
geojson.properties = ele;
|
|
|
|
out.features.push(geojson);
|
|
|
|
});
|
|
|
|
|
|
|
|
// return payload
|
|
|
|
callback(null, out);
|
|
|
|
} catch (err) {
|
|
|
|
callback(err,null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-04-13 07:30:45 +08:00
|
|
|
function toCSV(data, res, callback){
|
|
|
|
try{
|
2012-04-13 22:37:09 +08:00
|
|
|
// pull out keys for column headers
|
|
|
|
var columns = _.keys(data.rows[0]);
|
|
|
|
|
|
|
|
// stream the csv out over http
|
|
|
|
csv()
|
|
|
|
.from(data.rows)
|
|
|
|
.toStream(res, {end: true, columns: columns, header: true});
|
|
|
|
return true;
|
2012-04-13 07:30:45 +08:00
|
|
|
} catch (err) {
|
|
|
|
callback(err,null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-10-28 19:11:18 +08:00
|
|
|
function getContentDisposition(format){
|
2012-04-13 07:30:45 +08:00
|
|
|
var ext = 'json';
|
|
|
|
if (format === 'geojson'){
|
|
|
|
ext = 'geojson';
|
|
|
|
}
|
|
|
|
if (format === 'csv'){
|
|
|
|
ext = 'csv';
|
|
|
|
}
|
2011-10-28 19:11:18 +08:00
|
|
|
var time = new Date().toUTCString();
|
|
|
|
return 'inline; filename=cartodb-query.' + ext + '; modification-date="' + time + '";';
|
|
|
|
}
|
2011-09-07 19:05:10 +08:00
|
|
|
|
2012-04-13 07:30:45 +08:00
|
|
|
function getContentType(format){
|
|
|
|
var type = "application/json; charset=utf-8";
|
|
|
|
if (format === 'csv'){
|
|
|
|
type = "text/csv; charset=utf-8";
|
|
|
|
}
|
|
|
|
return type;
|
|
|
|
}
|
|
|
|
|
|
|
|
function setCrossDomain(res){
|
|
|
|
res.header("Access-Control-Allow-Origin", "*");
|
|
|
|
res.header("Access-Control-Allow-Headers", "X-Requested-With");
|
|
|
|
}
|
|
|
|
|
2012-04-21 02:34:18 +08:00
|
|
|
function generateCacheKey(database,tables){
|
|
|
|
return database + ":" + tables.rows[0].cdb_querytables.split(/^\{(.*)\}$/)[1];
|
|
|
|
}
|
|
|
|
|
2012-05-01 23:46:30 +08:00
|
|
|
function generateMD5(data){
|
|
|
|
var hash = crypto.createHash('md5');
|
|
|
|
hash.update(data);
|
|
|
|
return hash.digest('hex');
|
|
|
|
}
|
|
|
|
|
2011-08-18 00:27:45 +08:00
|
|
|
function handleException(err, res){
|
2011-08-24 04:42:27 +08:00
|
|
|
var msg = (global.settings.environment == 'development') ? {error:[err.message], stack: err.stack} : {error:[err.message]}
|
2011-08-25 03:47:10 +08:00
|
|
|
if (global.settings.environment !== 'test'){
|
|
|
|
// TODO: email this Exception report
|
|
|
|
console.log("EXCEPTION REPORT")
|
|
|
|
console.log(err.message);
|
|
|
|
console.log(err.stack);
|
|
|
|
}
|
2011-10-28 19:11:18 +08:00
|
|
|
|
2012-04-13 07:30:45 +08:00
|
|
|
// allow cross site post
|
|
|
|
setCrossDomain(res);
|
|
|
|
|
2011-11-22 08:06:14 +08:00
|
|
|
// if the exception defines a http status code, use that, else a 500
|
|
|
|
if (!_.isUndefined(err.http_status)){
|
|
|
|
res.send(msg, err.http_status);
|
|
|
|
} else {
|
|
|
|
res.send(msg, 400);
|
|
|
|
}
|
2011-06-13 20:07:21 +08:00
|
|
|
}
|
|
|
|
|
2011-06-20 21:39:12 +08:00
|
|
|
module.exports = app;
|