diff --git a/packages/cubejs-schema-compiler/src/adapter/MssqlQuery.ts b/packages/cubejs-schema-compiler/src/adapter/MssqlQuery.ts index 0f9503df9d391..7fdcb5b9b85db 100644 --- a/packages/cubejs-schema-compiler/src/adapter/MssqlQuery.ts +++ b/packages/cubejs-schema-compiler/src/adapter/MssqlQuery.ts @@ -384,6 +384,7 @@ export class MssqlQuery extends BaseQuery { ') AS {{ from_alias }}{% elif from_prepared %}\n' + 'FROM {{ from_prepared }}' + '{% endif %}' + + '{% for join in joins %}\n{{ join }}{% endfor %}' + '{% if filter %}\nWHERE {{ filter }}{% endif %}' + '{% if group_by %}\nGROUP BY {{ group_by }}{% endif %}' + '{% if having %}\nHAVING {{ having }}{% endif %}' + diff --git a/packages/cubejs-schema-compiler/test/unit/mssql-query.test.ts b/packages/cubejs-schema-compiler/test/unit/mssql-query.test.ts index 8dd435f19f506..8daf1dff6b88d 100644 --- a/packages/cubejs-schema-compiler/test/unit/mssql-query.test.ts +++ b/packages/cubejs-schema-compiler/test/unit/mssql-query.test.ts @@ -96,6 +96,23 @@ describe('MssqlQuery', () => { const joinedSchemaCompilers = prepareJsCompiler(createJoinedCubesSchema()); + it('renders SQL API pushdown joins after FROM and before WHERE', async () => { + await compiler.compile(); + + const query = new MssqlQuery({ joinGraph, cubeEvaluator, compiler }, { + measures: ['visitors.count'], + }); + + // The SQL API supplies already-rendered joins to statements.select. + // Omitting this loop leaves projected columns referring to absent aliases. + const { select } = query.sqlTemplates().statements; + const joins = '{% for join in joins %}\n{{ join }}{% endfor %}'; + expect(select).toContain(joins); + expect(select.indexOf(joins)).toBeGreaterThan(select.indexOf('FROM {{ from_prepared }}')); + expect(select.indexOf(joins)).toBeGreaterThan(select.indexOf(') AS {{ from_alias }}')); + expect(select.indexOf(joins)).toBeLessThan(select.indexOf('{% if filter %}')); + }); + it('should group by the created_at field on the calculated granularity for unbounded trailing windows', () => compiler.compile().then(() => { const query = new MssqlQuery(