Skip to content

fix(drizzle): coalesce jsonb_agg/json_group_array to empty array for hasMany select join-where#16759

Open
GeorgS wants to merge 1 commit into
payloadcms:mainfrom
GeorgS:fix/drizzle-hasmany-select-join-where-null-coalesce
Open

fix(drizzle): coalesce jsonb_agg/json_group_array to empty array for hasMany select join-where#16759
GeorgS wants to merge 1 commit into
payloadcms:mainfrom
GeorgS:fix/drizzle-hasmany-select-join-where-null-coalesce

Conversation

@GeorgS
Copy link
Copy Markdown
Contributor

@GeorgS GeorgS commented May 27, 2026

What?

Fix sub-folders not showing up in the folder browser (e.g. "Browse by folder" drawer) when those folders have no folderType set (universal folders).

Why?

Universal folders have zero rows in the payload_folders_folder_type join table. In drizzle/find/traverseFields.ts, the subquery that aggregates hasMany select field values uses jsonb_agg() (PostgreSQL) / json_group_array() (SQLite). When there are zero rows, these aggregates return NULL — not an empty array. The subsequent JSON path check NOT jsonb_path_exists(NULL, '$[*]') evaluates to NULL in SQL (not TRUE), so the WHERE clause silently excludes universal folders from the results.

SELECT NOT jsonb_path_exists(NULL, '$[*]');
-- Returns: NULL  -> row excluded from WHERE clause

SELECT NOT jsonb_path_exists(COALESCE(NULL, '[]'::jsonb), '$[*]');
-- Returns: true  -> row correctly included

This affects any query using exists: false (or any other operator) on a hasMany select field used inside a polymorphic join where clause.

How?

Wrap both aggregate subqueries in COALESCE so they always return an empty array instead of NULL when no rows exist:

- sql`(select jsonb_agg(t.value) from t where t.parent_id = parent.id)`
+ sql`coalesce((select jsonb_agg(t.value) from t where t.parent_id = parent.id), '[]'::jsonb)`
- sql`(select json_group_array(t.value) from t where t.parent_id = parent.id)`
+ sql`coalesce((select json_group_array(t.value) from t where t.parent_id = parent.id), '[]')`

This should also be backported to v3

Fixes #14821

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant