pg-mem icon indicating copy to clipboard operation
pg-mem copied to clipboard

Aggregation error when `COUNT(DISTINCT xx)` on SELECT query (caused by `DISTINCT`)

Open ilianAZZ opened this issue 3 months ago • 0 comments

Describe the bug

Adding a "distinct" in a function aggregate arises an issue

Minimal SQL queries to reproduce above

This seems to be the same error as here But error has changed (and I provided a minimal SQL example)

Error executing SQL: select a.id, count(distinct b.id) as b_count from a left join b on b.a_id = a.id group by a.id; 
TypeError: Cannot read properties of undefined (reading '0')

💥 This is a nasty error, which was unexpected by pg-mem. Also known "a bug" 😁 Please file an issue !

*️⃣ Failed SQL statement: select a.id, count(distinct b.id) as b_count from a left join b on b.a_id = a.id group by a.id; ;

👉 You can file an issue at https://github.com/oguimbal/pg-mem along with a way to reproduce this error (if you can), and  the stacktrace:


    at Evaluator.val (/project/node_modules/.pnpm/[email protected][email protected]/node_modules/pg-mem/src/transforms/aggregation.ts:114:38)
    at Evaluator.get (/project/node_modules/.pnpm/[email protected][email protected]/node_modules/pg-mem/src/evaluator.ts:220:21)
    at <anonymous> (/project/node_modules/.pnpm/[email protected][email protected]/node_modules/pg-mem/src/transforms/aggregation.ts:241:75)
    at Array.map (<anonymous>)
    at Aggregation.seqScan (/project/node_modules/.pnpm/[email protected][email protected]/node_modules/pg-mem/src/transforms/aggregation.ts:241:64)
    at seqScan.next (<anonymous>)
    at Aggregation.enumerate (/project/node_modules/.pnpm/[email protected][email protected]/node_modules/pg-mem/src/transforms/aggregation.ts:144:20)
    at enumerate.next (<anonymous>)
    at Selection.enumerate (/project/node_modules/.pnpm/[email protected][email protected]/node_modules/pg-mem/src/transforms/selection.ts:200:20)
    at enumerate.next (<anonymous>) {
  location: { start: 0, end: 0 },
  [Symbol(errorDetailsIncluded)]: true
}

To Reproduce

create table "a" (
  id serial primary key,
  name text not null
);

create table "b" (
  id serial primary key,
  a_id integer references a(id),
  description text
);

insert into a (name) values ('First A'), ('Second A');
insert into b (a_id, description) values (1, 'First B for A1'), (1, 'Second B for A1'), (2, 'First B for A2');

-- this quey works well
select
  a.id,
  count(b.id) as b_count
from a
left join b on b.a_id = a.id
group by a.id;

-- This query does not works
select
  a.id,
  count(distinct b.id) as b_count -- <--- Adding DISCTINCT here
from a
left join b on b.a_id = a.id
group by a.id;

pg-mem version

3.0.5

(nb: the version in your package.json version is often not precise enough... please run "cat ./node_modules/pg-mem/package.json | grep version" to tell which minor version is actually installed)

ilianAZZ avatar Aug 29 '25 20:08 ilianAZZ