Skip to content

Commit 2fcab08

Browse files
committed
fix: pre-aggregate primary_keys
Can't aggregate over 2 source tables in the same query, otherwise it'll produce incorrect results: https://stackoverflow.com/a/27626358/12396224
1 parent 2f8a204 commit 2fcab08

File tree

2 files changed

+28
-24
lines changed

2 files changed

+28
-24
lines changed

src/lib/sql/tables.sql

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,7 @@ SELECT
1717
pg_stat_get_live_tuples(c.oid) AS live_rows_estimate,
1818
pg_stat_get_dead_tuples(c.oid) AS dead_rows_estimate,
1919
obj_description(c.oid) AS comment,
20-
coalesce(
21-
jsonb_agg(primary_keys) filter (where primary_keys is not null),
22-
'[]'
23-
) as primary_keys,
20+
coalesce(pk.primary_keys, '[]') as primary_keys,
2421
coalesce(
2522
jsonb_agg(relationships) filter (where relationships is not null),
2623
'[]'
@@ -30,23 +27,29 @@ FROM
3027
JOIN pg_class c ON nc.oid = c.relnamespace
3128
left join (
3229
select
33-
n.nspname as schema,
34-
c.relname as table_name,
35-
a.attname as name,
36-
c.oid :: int8 as table_id
37-
from
38-
pg_index i,
39-
pg_class c,
40-
pg_attribute a,
41-
pg_namespace n
42-
where
43-
i.indrelid = c.oid
44-
and c.relnamespace = n.oid
45-
and a.attrelid = c.oid
46-
and a.attnum = any (i.indkey)
47-
and i.indisprimary
48-
) as primary_keys
49-
on primary_keys.table_id = c.oid
30+
table_id,
31+
jsonb_agg(_pk.*) as primary_keys
32+
from (
33+
select
34+
n.nspname as schema,
35+
c.relname as table_name,
36+
a.attname as name,
37+
c.oid :: int8 as table_id
38+
from
39+
pg_index i,
40+
pg_class c,
41+
pg_attribute a,
42+
pg_namespace n
43+
where
44+
i.indrelid = c.oid
45+
and c.relnamespace = n.oid
46+
and a.attrelid = c.oid
47+
and a.attnum = any (i.indkey)
48+
and i.indisprimary
49+
) as _pk
50+
group by table_id
51+
) as pk
52+
on pk.table_id = c.oid
5053
left join (
5154
select
5255
c.oid :: int8 as id,
@@ -91,4 +94,5 @@ group by
9194
c.relrowsecurity,
9295
c.relforcerowsecurity,
9396
c.relreplident,
94-
nc.nspname
97+
nc.nspname,
98+
pk.primary_keys

test/lib/tables.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -465,12 +465,12 @@ test('primary keys', async () => {
465465
"name": "t",
466466
"primary_keys": [
467467
{
468-
"name": "cc",
468+
"name": "c",
469469
"schema": "public",
470470
"table_name": "t",
471471
},
472472
{
473-
"name": "c",
473+
"name": "cc",
474474
"schema": "public",
475475
"table_name": "t",
476476
},

0 commit comments

Comments
 (0)