diff --git a/db-service/lib/cqn4sql.js b/db-service/lib/cqn4sql.js index d42a9222f..ec9d307a3 100644 --- a/db-service/lib/cqn4sql.js +++ b/db-service/lib/cqn4sql.js @@ -787,7 +787,7 @@ function cqn4sql(originalQuery, model) { } else { outerAlias = transformedQuery.SELECT.from.as subqueryFromRef = [ - ...transformedQuery.SELECT.from.ref, + ...(transformedQuery.SELECT.from.ref || /* subq in from */ [transformedQuery.SELECT.from.target.name]), ...(column.$refLinks[0].definition.kind === 'entity' ? column.ref.slice(1) : column.ref), ] } @@ -1911,8 +1911,7 @@ function cqn4sql(originalQuery, model) { result[i].ref = [targetSideRefLink.alias, lhs.ref.join('_')] } } - } else if (lhs.ref.length === 1) - result[i].ref.unshift(targetSideRefLink.alias) + } else if (lhs.ref.length === 1) result[i].ref.unshift(targetSideRefLink.alias) } } return result diff --git a/db-service/test/cqn4sql/expand.test.js b/db-service/test/cqn4sql/expand.test.js index 9fc4bd3ac..1f98d0e18 100644 --- a/db-service/test/cqn4sql/expand.test.js +++ b/db-service/test/cqn4sql/expand.test.js @@ -416,6 +416,20 @@ describe('Unfold expands on associations to special subselects', () => { expect(JSON.parse(JSON.stringify(res))).to.deep.eql(qx) }) + it('correctly builds correlated subquery if selecting from subquery', () => { + const q = CQL`SELECT from (select author from bookshop.Books) as book { + author { name } + }` + const qx = CQL`SELECT from (select Books.author_ID from bookshop.Books as Books) as book { + (SELECT + author.name + from bookshop.Authors as author + where book.author_ID = author.ID) as author + }` + const res = cqn4sql(q) + expect(JSON.parse(JSON.stringify(res))).to.deep.eql(qx) + }) + it('unfold expand, several fields with alias', () => { const q = CQL`SELECT from bookshop.Books { author { name, dateOfBirth as dob, placeOfBirth as pob}