FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

fix(postgrest): type hinted self-referencing embeds as arrays by mandarini · Pull Request #2520 · supabase/supabase-js · GitHub

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .ts  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -459,20 +459,26 @@ type ProcessEmbeddedResourceResult<
: ProcessedChildren | null
: ProcessedChildren | null
: ProcessedChildren[]
: // If the relation is a self-reference it'll always be considered as reverse relationship
: // If the relation is a self-reference it'll always be considered as a reverse relationship.
// PostgREST returns arrays for a self-reference when using the table name
// (collections(*)) or any hint (collections!parent_id(*)), and a single object
// only when using the column name directly (parent_id(*)).
// See https://github.com/PostgREST/postgrest/blob/8776ece7d5fd612fad44151f9be4dffd855b28f0/src/PostgREST/Plan.hs#L633-L644
Resolved['relation']['referencedRelation'] extends CurrentTableOrView
? // It can either be a reverse reference via a column inclusion (eg: parent_id(*))
// in such case the result will be a single object
Resolved['relation']['match'] extends 'col'
? IsRelationNullable<
TablesAndViews<Schema>[CurrentTableOrView],
Resolved['relation']
> extends true
? ProcessedChildren | null
: ProcessedChildren
: // Or it can be a reference via the reference relation (eg: collections(*))
// in such case, the result will be an array of all the values (all collection with parent_id being the current id)
ProcessedChildren[]
? // An explicit hint must be checked before `match: 'col'`, since a hinted
// self-reference is always an array (eg: collections!parent_id(*)).
Resolved['relation'] extends { hint: string }
? ProcessedChildren[]
: // Without a hint, a column inclusion (eg: parent_id(*)) is a single object.
Resolved['relation']['match'] extends 'col'
? IsRelationNullable<
TablesAndViews<Schema>[CurrentTableOrView],
Resolved['relation']
> extends true
? ProcessedChildren | null
: ProcessedChildren
: // The table name (eg: collections(*)) is an array of children.
ProcessedChildren[]
: // Otherwise if it's a non self-reference reverse relationship it's a single object
IsRelationNullable<
TablesAndViews<Schema>[CurrentTableOrView],
Expand Down
95 changes: 95 additions & 0 deletions packages/core/postgrest-js/test/relationships.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,101 @@ test('self reference relation via column', async () => {
ExpectedSchema.parse(res.data)
})

test('self reference relation via hint matching column name', async () => {
const res = await postgrest
.from('collections')
.select('*, collections!parent_id(*)')
.eq('id', 1)
.limit(1)
.single()
expect(res).toMatchInlineSnapshot(`
{
"count": null,
"data": {
"collections": [
{
"description": "Child of Root",
"id": 2,
"parent_id": 1,
},
{
"description": "Another Child of Root",
"id": 3,
"parent_id": 1,
},
],
"description": "Root Collection",
"id": 1,
"parent_id": null,
},
"error": null,
"status": 200,
"statusText": "OK",
"success": true,
}
`)
let result: Exclude<typeof res.data, null>
const ExpectedSchema = z.object({
id: z.number(),
description: z.string().nullable(),
parent_id: z.number().nullable(),
collections: z.array(
z.object({
description: z.string().nullable(),
id: z.number(),
parent_id: z.number().nullable(),
})
),
})
let expected: z.infer<typeof ExpectedSchema>
expectType<TypeEqual<typeof result, typeof expected>>(true)
ExpectedSchema.parse(res.data)
})

// Documents a known PostgREST limitation: a self-referencing embed cannot be
// disambiguated by its foreign key constraint name, so this
// query fails at runtime with PGRST200. Use the column name hint instead (see the
// test above). The inferred type is still (correctly) an array. See
// https://github.com/supabase/supabase-js/issues/2517
Comment thread
mandarini marked this conversation as resolved.
test('self reference relation via hint matching fk constraint name fails at runtime', async () => {
const res = await postgrest
.from('collections')
.select('*, collections!collections_parent_id_fkey(*)')
.eq('id', 1)
.limit(1)
.single()
expect(res).toMatchInlineSnapshot(`
{
"count": null,
"data": null,
"error": {
"code": "PGRST200",
"details": "Searched for a foreign key relationship between 'collections' and 'collections' using the hint 'collections_parent_id_fkey' in the schema 'public', but no matches were found.",
"hint": null,
"message": "Could not find a relationship between 'collections' and 'collections' in the schema cache",
},
"status": 400,
"statusText": "Bad Request",
"success": false,
}
`)
let result: Exclude<typeof res.data, null>
const ExpectedSchema = z.object({
id: z.number(),
description: z.string().nullable(),
parent_id: z.number().nullable(),
collections: z.array(
z.object({
description: z.string().nullable(),
id: z.number(),
parent_id: z.number().nullable(),
})
),
})
let expected: z.infer<typeof ExpectedSchema>
expectType<TypeEqual<typeof result, typeof expected>>(true)
})

test('many-to-many with join table', async () => {
const res = await postgrest.from('products').select('*, categories(*)').eq('id', 1).single()
expect(res).toMatchInlineSnapshot(`
Expand Down
Loading

Back | FazBrowse Home | New Git URL