Add "fields" member in JSON return. Closes #97

This commit is contained in:
Sandro Santilli 2013-06-14 18:35:04 +02:00
parent 298027aa5d
commit 88f1d33b42
3 changed files with 82 additions and 0 deletions

View File

@ -1,5 +1,6 @@
1.5.0
-----
* Add "fields" member in JSON return (#97)
* Add --skipfields switch to cdbsql
* Fix windowing with non-uppercased SELECTs

View File

@ -8,9 +8,65 @@ var p = json.prototype;
p._contentType = "application/json; charset=utf-8";
var typeNames = {
16: 'string', // bool
17: 'string', // bytea
20: 'number',
21: 'number',
23: 'number',
26: 'number',
114: 'object', // JSON
701: 'number',
1015: 'string[]', // _varchar
1042: 'string',
1043: 'string',
1005: 'number[]', // _int2
1007: 'number[]', // _int4
1014: 'string[]', // _bpchar
1016: 'number[]', // _int8
1021: 'number[]', // _float4
1022: 'number[]', // _float8
1008: 'string[]',
1009: 'string[]',
1114: 'date', // timestamp without timezone
1182: 'date', // date
1184: 'date', // timestamp
1186: 'string', // interval
1231: 'number[]', // _numeric
};
function formatResultFields(flds) {
var nfields = {};
for (var i=0; i<flds.length; ++i) {
var f = flds[i];
/*
{ name: 'the_geom',
tableID: 5528687,
columnID: 6,
dataTypeID: 77869,
dataTypeSize: -1,
dataTypeModifier: -1,
format: 'text' },
*/
var tname = typeNames[f.dataTypeID];
if ( ! tname ) {
if ( f.name.match(/^the_geom/) ) {
tname = 'geometry';
} else {
tname = f.dataTypeID; // unknown
}
}
nfields[f.name] = { type: tname };
}
return nfields;
}
p.transform = function(result, options, callback) {
var j = {
time: options.total_time,
fields: formatResultFields(result.fields),
total_rows: result.rowCount,
rows: result.rows
}

View File

@ -836,6 +836,31 @@ test('numeric arrays are rendered as such', function(done){
});
});
// See https://github.com/Vizzuality/CartoDB-SQL-API/issues/97
test('field names and types are exposed', function(done){
assert.response(app, {
url: '/api/v1/sql?' + querystring.stringify({
q: "SELECT 1::int as a, 2::float8 as b, 3::varchar as c, " +
"4::char as d, now() as e, 'POINT(0 0)'::geometry as the_geom " +
"LIMIT 0"
}),
headers: {host: 'vizzuality.cartodb.com'},
method: 'GET'
},{ }, function(res) {
assert.equal(res.statusCode, 200, res.body);
var parsedBody = JSON.parse(res.body);
assert.equal(_.keys(parsedBody.fields).length, 6);
assert.equal(parsedBody.fields.a.type, 'number');
assert.equal(parsedBody.fields.b.type, 'number');
assert.equal(parsedBody.fields.c.type, 'string');
assert.equal(parsedBody.fields.d.type, 'string');
assert.equal(parsedBody.fields.e.type, 'date');
assert.equal(parsedBody.fields.the_geom.type, 'geometry');
done();
});
});
/**
* CORS
*/