jawj / zapatos

Zero-abstraction Postgres for TypeScript: a non-ORM database library
https://jawj.github.io/zapatos/
Other
1.3k stars 46 forks source link

Reusing subqueries inside of laterals with the shortcut functions results in incorrect parent tables #167

Open rosettaroberts-impact opened 7 months ago

rosettaroberts-impact commented 7 months ago

Let me know if you want me to make a minimal reproduce-able example!

Here is an example of a query with the problem:

const foo = db.selectOne('foo', { id: parent('foo_id') });

const result = await db.select('bar', db.all, {
  lateral: {
    foo,
    baz: db.selectOne('baz', { id: parent('baz_id') }, {
      lateral: { foo }
    })
  }
);

In this example, you will get a database error somewhat like the following:

      "type": "DatabaseError",
      "message": "missing FROM-clause entry for table \"baz\"",

This is because foo's parent table is set first to bar, but then overridden with baz.

A solution to this is to make the parentTable property on SQLExpression readonly, and to require making a copy of the SQLExpression to set the parentTable.

rosettaroberts-impact commented 7 months ago

I'll be able to make a PR to fix this probably next week if someone else doesn't get to it by then!