Ff00ff/mammoth

Generated SQL for WHERE clause doesn't match AST nesting

Opened this issue · 1 comments

Two expressions with slightly different nesting.

await db
  .select(db.test.a)
  .from(db.test)
  .where(db.test.a.and(db.test.b).eq(true));
await db
  .select(db.test.a)
  .from(db.test)
  .where(db.test.a.and(db.test.b.eq(true)));

But Mammoth produces the same SQL for both:

SELECT test.a FROM test WHERE test.a AND test.b = $1

I'd expect the first one to yield:

SELECT test.a FROM test WHERE (test.a AND test.b) = $1

Code Sandbox: link

More serious variant of the issue:

  const subExpr = () => {
    return db.test.a.or(db.test.b);
  }
  await db
    .select(db.test.a)
    .from(db.test)
    .where(db.test.xyz.and(subExpr());
  await db
    .select(db.test.a)
    .from(db.test)
    .where(subExpr().and(db.test.xyz)));
SELECT test.a FROM test WHERE test.xyz AND test.a OR test.b 
SELECT test.a FROM test WHERE test.a OR test.b AND test.xyz 

I would expect the OR to be parenthesized because it is deeper in the function call tree:

SELECT test.a FROM test WHERE test.xyz AND (test.a OR test.b)
SELECT test.a FROM test WHERE (test.a OR test.b) AND test.xyz 

Without that, it makes it hard to reliably write functions that return subexpressions.

Code Sandbox: link