diff --git a/lib/cartodb/utils/overviews_query_rewriter.js b/lib/cartodb/utils/overviews_query_rewriter.js index 622c2018..2b253908 100644 --- a/lib/cartodb/utils/overviews_query_rewriter.js +++ b/lib/cartodb/utils/overviews_query_rewriter.js @@ -168,9 +168,16 @@ OverviewsQueryRewriter.prototype.query = function(query, data) { }; OverviewsQueryRewriter.prototype.is_supported_query = function(sql) { - return !!sql.match( - /^\s*SELECT\s+[\*a-z0-9_,\s]+?\s+FROM\s+((\"[^"]+\"|[a-z0-9_]+)\.)?(\"[^"]+\"|[a-z0-9_]+)\s*;?\s*$/i + var basic_query = /\s*SELECT\s+[\*a-z0-9_,\s]+?\s+FROM\s+((\"[^"]+\"|[a-z0-9_]+)\.)?(\"[^"]+\"|[a-z0-9_]+)\s*;?\s*/i; + var unwrapped_query = new RegExp("^"+basic_query.source+"$", 'i'); + // queries for named maps are wrapped like this: + var wrapped_query = new RegExp( + "^\\s*SELECT\\s+\\*\\s+FROM\\s+\\(" + + basic_query.source + + "\\)\\s+AS\\s+wrapped_query\\s+WHERE\\s+\\d+=1\\s*$", + 'i' ); + return !!(sql.match(unwrapped_query) || sql.match(wrapped_query)); }; OverviewsQueryRewriter.prototype.overviews_metadata = function(data) { diff --git a/test/unit/cartodb/overviews_query_rewriter.js b/test/unit/cartodb/overviews_query_rewriter.js index b58b55b0..f79e82c7 100644 --- a/test/unit/cartodb/overviews_query_rewriter.js +++ b/test/unit/cartodb/overviews_query_rewriter.js @@ -395,5 +395,32 @@ describe('Overviews query rewriter', function() { done(); }); - + it('generates overviews for wrapped query', function(done){ + var sql = "SELECT * FROM (SELECT * FROM table1) AS wrapped_query WHERE 1=1"; + var data = { + overviews: { + table1: { + 0: { table: 'table1_ov0' }, + 1: { table: 'table1_ov1' }, + 2: { table: 'table1_ov2' } + } + } + }; + var overviews_sql = overviewsQueryRewriter.query(sql, data); + var expected_sql = "\ + WITH\ + _vovw_scale AS ( SELECT ZoomLevel() AS _vovw_z )\ + SELECT * FROM (SELECT * FROM (\ + SELECT * FROM table1_ov0, _vovw_scale WHERE _vovw_z = 0\ + UNION ALL\ + SELECT * FROM table1_ov1, _vovw_scale WHERE _vovw_z = 1\ + UNION ALL\ + SELECT * FROM table1_ov2, _vovw_scale WHERE _vovw_z = 2\ + UNION ALL\ + SELECT * FROM table1, _vovw_scale WHERE _vovw_z > 2\ + ) AS _vovw_table1) AS wrapped_query WHERE 1=1\ + "; + assertSameSql(overviews_sql, expected_sql); + done(); + }); });