Skip to content

Commit

Permalink
fix: prepend aliases to refs within function args in on conditions (#795
Browse files Browse the repository at this point in the history
)

we need to drill recursively into the function arguments found in
on-conditions and prepend aliases of the outer query in case of scoped
queries / expands

fixes #779

Co-authored-by: Johannes Vogel <31311694+johannes-vogel@users.noreply.github.com>
  • Loading branch information
patricebender and johannes-vogel authored Sep 2, 2024
1 parent abac818 commit 9b34314
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
5 changes: 5 additions & 0 deletions db-service/lib/cqn4sql.js
Original file line number Diff line number Diff line change
Expand Up @@ -1853,6 +1853,11 @@ function cqn4sql(originalQuery, model) {
result[i] = asXpr(xpr)
continue
}
if(lhs.args) {
const args = calculateOnCondition(lhs.args)
result[i] = { ...lhs, args }
continue
}
const rhs = result[i + 2]
if (rhs?.ref || lhs.ref) {
// if we have refs on each side of the comparison, we might need to perform tuple expansion
Expand Down
7 changes: 7 additions & 0 deletions db-service/test/bookshop/db/schema.cds
Original file line number Diff line number Diff line change
Expand Up @@ -422,3 +422,10 @@ entity Item {
key ID: Integer;
item: Association to Item;
}

entity Posts {
key ID: Integer;
name: String;
iSimilar: Association to many Posts on UPPER(name) = UPPER(iSimilar.name);
iSimilarNested: Association to many Posts on UPPER(iSimilarNested.name) = UPPER(LOWER(UPPER(name)), name);
}
43 changes: 43 additions & 0 deletions db-service/test/cqn4sql/table-alias.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,49 @@ describe('table alias access', () => {
let result = cqn4sql(query, model)
expect(result).to.deep.equal(expected)
})

it('refs in function args in on condition are aliased', () => {
let query = CQL`
SELECT
ID,
iSimilar { name }
from bookshop.Posts`

const expected = CQL`
SELECT
Posts.ID,
(
SELECT from bookshop.Posts as iSimilar {
iSimilar.name
}
where UPPER(Posts.name) = UPPER(iSimilar.name)
) as iSimilar
from bookshop.Posts as Posts`

let result = cqn4sql(query, model)
expect(JSON.parse(JSON.stringify(result))).to.deep.equal(expected)
})
it('refs in nested function args in on condition are aliased', () => {
let query = CQL`
SELECT
ID,
iSimilarNested { name }
from bookshop.Posts`

const expected = CQL`
SELECT
Posts.ID,
(
SELECT from bookshop.Posts as iSimilarNested {
iSimilarNested.name
}
where UPPER(iSimilarNested.name) = UPPER(LOWER(UPPER(Posts.name)), Posts.name)
) as iSimilarNested
from bookshop.Posts as Posts`

let result = cqn4sql(query, model)
expect(JSON.parse(JSON.stringify(result))).to.deep.equal(expected)
})
})

describe('replace $self references', () => {
Expand Down

0 comments on commit 9b34314

Please sign in to comment.