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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions packages/core/postgrest-js/src/select-query-parser/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,11 @@ type ProcessFieldNode<
Relationships extends GenericRelationship[],
Field extends Ast.FieldNode,
> = Field['children'] extends []
? {}
? // Empty `()` — could be a scalar computed column (e.g. `user_count()`).
// Route through ProcessEmbeddedResource so the scalar path returns the correct
// primitive type. For non-scalar embedded resources with empty selection,
// ProcessEmbeddedResource returns {} (no contribution to result type).
ProcessEmbeddedResource<ClientOptions, Schema, Relationships, Field, RelationName>
: IsNonEmptyArray<Field['children']> extends true // Has embedded resource?
? ProcessEmbeddedResource<ClientOptions, Schema, Relationships, Field, RelationName>
: ProcessSimpleField<Row, RelationName, Field>
Expand Down Expand Up @@ -366,13 +370,35 @@ export type ProcessEmbeddedResource<
> =
ResolveRelationship<Schema, Relationships, Field, CurrentTableOrView> extends infer Resolved
? Resolved extends {
referencedTable: Pick<GenericTable, 'Row' | 'Relationships'>
relation: GenericRelationship & { match: 'refrel' | 'col' | 'fkname' | 'func' }
direction: string
scalarType: infer ScalarType
relation: { isSetofReturn?: boolean; isNotNullable?: boolean }
}
? ProcessEmbeddedResourceResult<ClientOptions, Schema, Resolved, Field, CurrentTableOrView>
: // Otherwise the Resolved is a SelectQueryError return it
{ [K in GetFieldNodeResultName<Field>]: Resolved }
? // Scalar computed column: bypass ProcessNodes and return the primitive type directly.
{
[K in GetFieldNodeResultName<Field>]: Resolved['relation']['isSetofReturn'] extends true
? ScalarType
: Resolved['relation']['isNotNullable'] extends true
? ScalarType
: ScalarType | null
}
: Resolved extends {
referencedTable: Pick<GenericTable, 'Row' | 'Relationships'>
relation: GenericRelationship & { match: 'refrel' | 'col' | 'fkname' | 'func' }
direction: string
}
? Field['children'] extends []
? // Empty `()` on a regular table embed — no fields selected, contribute nothing.
// This preserves the prior behavior: `users()` does not add a `users` key to the result.
{}
: ProcessEmbeddedResourceResult<
ClientOptions,
Schema,
Resolved,
Field,
CurrentTableOrView
>
: // Otherwise the Resolved is a SelectQueryError return it
{ [K in GetFieldNodeResultName<Field>]: Resolved }
: {
[K in GetFieldNodeResultName<Field>]: SelectQueryError<'Failed to resolve relationship.'> &
string
Expand Down
78 changes: 53 additions & 25 deletions packages/core/postgrest-js/src/select-query-parser/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,30 +464,58 @@ export type ResolveForwardRelationship<
CurrentTableOrView,
Field['name']
> extends infer FoundEmbededFunctionJoinTableRelation
? FoundEmbededFunctionJoinTableRelation extends GenericSetofOption
? {
referencedTable: TablesAndViews<Schema>[FoundEmbededFunctionJoinTableRelation['to']]
relation: {
foreignKeyName: `${Field['name']}_${CurrentTableOrView}_${FoundEmbededFunctionJoinTableRelation['to']}_forward`
columns: []
isOneToOne: FoundEmbededFunctionJoinTableRelation['isOneToOne'] extends true
? true
: false
referencedColumns: []
referencedRelation: FoundEmbededFunctionJoinTableRelation['to']
} & {
match: 'func'
isNotNullable: FoundEmbededFunctionJoinTableRelation['isNotNullable'] extends true
? true
: FoundEmbededFunctionJoinTableRelation['isSetofReturn'] extends true
? false
: true
isSetofReturn: FoundEmbededFunctionJoinTableRelation['isSetofReturn']
}
direction: 'forward'
from: CurrentTableOrView
type: 'found-by-embeded-function'
}
? FoundEmbededFunctionJoinTableRelation extends GenericFunction
? FoundEmbededFunctionJoinTableRelation['SetofOptions'] extends GenericSetofOption
? FoundEmbededFunctionJoinTableRelation['SetofOptions']['to'] extends ''
? // Scalar computed column: function returns a primitive (not a table row).
// `to` is '' because there is no target table — the value is returned directly.
{
referencedTable: { Row: Record<string, never>; Relationships: [] }
relation: {
foreignKeyName: `${Field['name']}_${CurrentTableOrView}_scalar_forward`
columns: []
isOneToOne: false
referencedColumns: []
referencedRelation: ''
} & {
match: 'func'
isNotNullable: FoundEmbededFunctionJoinTableRelation['SetofOptions']['isNotNullable'] extends true
? true
: FoundEmbededFunctionJoinTableRelation['SetofOptions']['isSetofReturn'] extends true
? false
: true
isSetofReturn: FoundEmbededFunctionJoinTableRelation['SetofOptions']['isSetofReturn']
}
scalarType: FoundEmbededFunctionJoinTableRelation['Returns']
direction: 'forward'
from: CurrentTableOrView
type: 'found-by-embeded-scalar-function'
}
: // Table-valued function: `to` names the target table/view.
{
referencedTable: TablesAndViews<Schema>[FoundEmbededFunctionJoinTableRelation['SetofOptions']['to']]
relation: {
foreignKeyName: `${Field['name']}_${CurrentTableOrView}_${FoundEmbededFunctionJoinTableRelation['SetofOptions']['to']}_forward`
columns: []
isOneToOne: FoundEmbededFunctionJoinTableRelation['SetofOptions']['isOneToOne'] extends true
? true
: false
referencedColumns: []
referencedRelation: FoundEmbededFunctionJoinTableRelation['SetofOptions']['to']
} & {
match: 'func'
isNotNullable: FoundEmbededFunctionJoinTableRelation['SetofOptions']['isNotNullable'] extends true
? true
: FoundEmbededFunctionJoinTableRelation['SetofOptions']['isSetofReturn'] extends true
? false
: true
isSetofReturn: FoundEmbededFunctionJoinTableRelation['SetofOptions']['isSetofReturn']
}
direction: 'forward'
from: CurrentTableOrView
type: 'found-by-embeded-function'
}
: SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`>
: SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`>
: SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`>
: SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field['name']}`>
Expand Down Expand Up @@ -542,7 +570,7 @@ type ResolveEmbededFunctionJoinTableRelationship<
CurrentTableOrView
> extends infer Fn
? Fn extends GenericFunction
? Fn['SetofOptions']
? Fn
: false
: false

Expand Down
26 changes: 26 additions & 0 deletions packages/core/postgrest-js/test/embeded_functions_join.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1433,4 +1433,30 @@ describe('embeded functions select', () => {
>
>(true)
})

test('scalar_computed_count - non-SETOF non-nullable scalar returns number (not null)', async () => {
const res = await postgrest.from('users').select('username, scalar_computed_count()')
let result: Exclude<typeof res.data, null>
const ExpectedSchema = z.array(
z.object({
username: z.string(),
scalar_computed_count: z.number(),
})
)
let expected: z.infer<typeof ExpectedSchema>
expectType<TypeEqual<typeof result, typeof expected>>(true)
})

test('scalar_computed_ids - SETOF scalar returns string[] (not null)', async () => {
const res = await postgrest.from('users').select('username, scalar_computed_ids()')
let result: Exclude<typeof res.data, null>
const ExpectedSchema = z.array(
z.object({
username: z.string(),
scalar_computed_ids: z.array(z.string()),
})
)
let expected: z.infer<typeof ExpectedSchema>
expectType<TypeEqual<typeof result, typeof expected>>(true)
})
})
19 changes: 19 additions & 0 deletions packages/core/postgrest-js/test/types.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,25 @@ export type Database = {
isSetofReturn: true
}
}
scalar_computed_count: {
Args: { '': Database['public']['Tables']['users']['Row'] }
Returns: number
SetofOptions: {
from: 'users'
to: ''
isSetofReturn: false
isNotNullable: true
}
}
scalar_computed_ids: {
Args: { '': Database['public']['Tables']['users']['Row'] }
Returns: string[]
SetofOptions: {
from: 'users'
to: ''
isSetofReturn: true
}
}
function_returning_single_row: {
Args: { messages: Database['public']['Tables']['messages']['Row'] }
Returns: {
Expand Down
Loading