supabase-js icon indicating copy to clipboard operation
supabase-js copied to clipboard

Supabase improperly types postgrest computed relationships

Open gwax opened this issue 10 months ago • 1 comments

Bug report

  • [x] I confirm this is a bug with Supabase, not with my own application.
  • [x] I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

Supabase supports making calls using postgrest computed relationships: https://postgrest.org/en/v12/references/api/resource_embedding.html#computed-relationships

However, these show up as typescript errors of the form SelectQueryError<"could not find the relation between ...">

The types for computed relationships (mostly) worked in 2.47.7 but broke starting in 2.47.8

To Reproduce

Minimal reproduction is available in the gwax/computed-relationships branch here: https://github.com/manapoolinc/supabase-playground/tree/gwax/computed-relationships

  1. Create a computed relationship: https://github.com/manapoolinc/supabase-playground/blob/gwax/computed-relationships/supabase/migrations/20250127194033_create_country_fns.sql#L1
  2. Use the computed relationship in a query: https://github.com/manapoolinc/supabase-playground/blob/gwax/computed-relationships/src/lib/db/countries.ts#L47
  3. See type error in IDE / typescript compiler: https://github.com/manapoolinc/supabase-playground/blob/gwax/computed-relationships/src/lib/db/countries.ts#L101

Expected behavior

No Type Errors in reproduction code

System information

  • Version of supabase: 2.6.8
  • Version of supabase-js: 2.48.1

gwax avatar Jan 28 '25 00:01 gwax

Thanks for documenting this issue! I've been using a custom utility type to manually override the faulty type, but it has become a burden for deeply embedded resources - see the code below.

I am exploring how to improve the utility, but I hope a native solution is possible.

Show code applying custom utility type
type RawCustomerContractLineItem = NonNullable<
  typeof rawData
>['customer_contract_line_items'][number]
type RawLineItemToPurchaseAssignment =
  RawCustomerContractLineItem['customer_contract_line_items__token_purchases'][number]
type RawTokenPurchase = RawLineItemToPurchaseAssignment['token_purchases']
type RawBatch = RawTokenPurchase['batches_flat']
type RawOutputFraction = RawBatch['output_fractions'][number]

type Result = FixSupabaseQueryDataSingle<
  typeof rawData,
  'customer_contract_line_items',
  {
    customer_contract_line_items: FixSupabaseQueryDataSingle<
      RawCustomerContractLineItem,
      'customer_contract_line_items__token_purchases',
      {
        customer_contract_line_items__token_purchases: FixSupabaseQueryDataSingle<
          RawLineItemToPurchaseAssignment,
          'token_purchases',
          FixSupabaseQueryDataSingle<
            RawTokenPurchase,
            'batches_flat',
            {
              batches_flat: FixSupabaseQueryDataSingle<
                RawBatch,
                'output_fractions',
                FixSupabaseQueryDataSingle<
                  RawOutputFraction,
                  'output_materials',
                  {
                    output_materials: {
                      id: string
                      name: string
                    }
                  }
                >
              >
            }
          >
        >[]
      }
    >[]
  }
>

stefan-girlich avatar Feb 06 '25 10:02 stefan-girlich

Same issue. The returned data/filtering/... are OK except the TypeScript type of computed relationship. I use both computed field and computed relationship in my project. TypeScript type issue only happens for computed relationship.

dule-kitemetric avatar Apr 24 '25 04:04 dule-kitemetric

We are also affected by this issue for the last 6 months. We rely on computed relationships heavily. Are there any plans to fix the type generation? We currently need to manually typecast query results since every query using computed relationships is causing the SelectQueryError<"could not find the relation between ... type. Which in essence then drops all typesafety from the query.

jens-f avatar Jul 15 '25 01:07 jens-f

We are also affected by this issue for the last 6 months. We rely on computed relationships heavily. Are there any plans to fix the type generation? We currently need to manually typecast query results since every query using computed relationships is causing the SelectQueryError<"could not find the relation between ... type. Which in essence then drops all typesafety from the query.

+1

redegade avatar Jul 15 '25 14:07 redegade

Hello there!

We’re working on a fix for this bug and have published a canary release for early testing. If you’re affected, please try it out and let us know if it resolves your issue (or causes any regressions):

# Pin postgres-meta (SETOF introspection)
echo "supabase/postgres-meta:canary-pr-971-40c06b8e011f91c1ae4d2f3d65f2a7c07ad78af8" > supabase/.temp/pgmeta-version

# Install supabase-js canary with updated postgrest-js inference
npm i https://pkg.pr.new/@supabase/supabase-js@749e4d1

# Regenerate types with latest CLI
npx supabase@latest gen types --local --lang=typescript > database.types.ts

Feedback on whether this fixes things (or breaks anything else) would be super valuable!

avallete avatar Sep 24 '25 10:09 avallete

I tried running the canary release following the directions you listed (using equivalent pnpm commands) and encountered the following error when trying to generate types:

$ pnpm supabase gen types --local --lang=typescript
Connecting to db 5432
file:///usr/src/app/dist/server/templates/typescript.js:105
          from: ${JSON.stringify(typesById[fn.args[0].type_id].format)}
                                                               ^

TypeError: Cannot read properties of undefined (reading 'format')
    at getFunctionTsReturnType (file:///usr/src/app/dist/server/templates/typescript.js:105:64)
    at file:///usr/src/app/dist/server/templates/typescript.js:301:53
    at Array.map (<anonymous>)
    at getFunctionSignatures (file:///usr/src/app/dist/server/templates/typescript.js:241:20)
    at file:///usr/src/app/dist/server/templates/typescript.js:481:44
    at Array.map (<anonymous>)
    at file:///usr/src/app/dist/server/templates/typescript.js:480:65
    at file:///usr/src/app/dist/server/templates/typescript.js:484:11
    at Array.map (<anonymous>)
    at apply (file:///usr/src/app/dist/server/templates/typescript.js:316:13)

Node.js v20.19.5
error running container: exit 1
Try rerunning the command with --debug to troubleshoot the error.

gwax avatar Sep 27 '25 07:09 gwax

I tried running the canary release following the directions you listed (using equivalent pnpm commands) and encountered the following error when trying to generate types:

$ pnpm supabase gen types --local --lang=typescript
Connecting to db 5432
file:///usr/src/app/dist/server/templates/typescript.js:105
          from: ${JSON.stringify(typesById[fn.args[0].type_id].format)}
                                                               ^

TypeError: Cannot read properties of undefined (reading 'format')
    at getFunctionTsReturnType (file:///usr/src/app/dist/server/templates/typescript.js:105:64)
    at file:///usr/src/app/dist/server/templates/typescript.js:301:53
    at Array.map (<anonymous>)
    at getFunctionSignatures (file:///usr/src/app/dist/server/templates/typescript.js:241:20)
    at file:///usr/src/app/dist/server/templates/typescript.js:481:44
    at Array.map (<anonymous>)
    at file:///usr/src/app/dist/server/templates/typescript.js:480:65
    at file:///usr/src/app/dist/server/templates/typescript.js:484:11
    at Array.map (<anonymous>)
    at apply (file:///usr/src/app/dist/server/templates/typescript.js:316:13)

Node.js v20.19.5
error running container: exit 1
Try rerunning the command with --debug to troubleshoot the error.

Hey there!

Thanks for giving the canary a try 🙏

Just to clarify is this error happening on the MRE example you mentioned earlier, or on a different project? To help us reproduce, it would be super useful to have the same database schema definition.

Meanwhile I'll update the code around this exception so we can get some more useful debugging information when such type error occurs.

Edit: Just released a new version that should fix the bug if you want to give it a try with:

echo "supabase/postgres-meta:canary-pr-971-cfb405f4b881a1c5a0915a77c4c633e5162d30dd" > supabase/.temp/pgmeta-version

avallete avatar Sep 27 '25 07:09 avallete

The error wasn't in my MRE example from before but in our main codebase, but going back and booting up the MRE again revealed that the problem wasn't your changes but that all the rest of my supabase libraries were on very old versions (because of this bug).

Going back to my MRE and:

pnpm add -D supabase@latest
echo "supabase/postgres-meta:canary-pr-971-cfb405f4b881a1c5a0915a77c4c633e5162d30dd" > supabase/.temp/pgmeta-version
pnpm add https://pkg.pr.new/@supabase/supabase-js@749e4d1
pnpm supabase gen types --local --lang=typescript > src/lib/db/schema.ts

seems to work and gives correct results

doing this also seems to generate output without crashing for our main codebase but doesn't seem to solve the original problem

I have extended the minimum reproduction to include a case that is closer to the failing cases we still see:

  • https://github.com/manapoolinc/supabase-playground/blob/gwax/computed-relationships/src/lib/db/countries.ts#L141
  • https://github.com/manapoolinc/supabase-playground/blob/gwax/computed-relationships/supabase/migrations/20250928073130_create_country_view.sql

Here, what we see is that a materialized view that DOES NOT use the primary key of a table but is joined to that table through a join function is unable to join to that table in supabase.

As before, this works just fine in current supabase and types correctly with @supabase/[email protected] and [email protected]

gwax avatar Sep 28 '25 08:09 gwax

The error wasn't in my MRE example from before but in our main codebase, but going back and booting up the MRE again revealed that the problem wasn't your changes but that all the rest of my supabase libraries were on very old versions (because of this bug).

Going back to my MRE and:

pnpm add -D supabase@latest echo "supabase/postgres-meta:canary-pr-971-cfb405f4b881a1c5a0915a77c4c633e5162d30dd" > supabase/.temp/pgmeta-version pnpm add https://pkg.pr.new/@supabase/supabase-js@749e4d1 pnpm supabase gen types --local --lang=typescript > src/lib/db/schema.ts seems to work and gives correct results

doing this also seems to generate output without crashing for our main codebase but doesn't seem to solve the original problem

I have extended the minimum reproduction to include a case that is closer to the failing cases we still see:

  • https://github.com/manapoolinc/supabase-playground/blob/gwax/computed-relationships/src/lib/db/countries.ts#L141
  • https://github.com/manapoolinc/supabase-playground/blob/gwax/computed-relationships/supabase/migrations/20250928073130_create_country_view.sql

Here, what we see is that a materialized view that DOES NOT use the primary key of a table but is joined to that table through a join function is unable to join to that table in supabase.

As before, this works just fine in current supabase and types correctly with @supabase/[email protected] and [email protected]

Thanks a lot for extending the reproduction and testing the canary 🙏

I’ve just pushed a fix for the materialized view issue you spotted. Could you try again with the updated pg-meta build?

echo "supabase/postgres-meta:canary-pr-971-0262ebc9fd3914f7fdc2627f0b7c6e37e14f5e8e" > supabase/.temp/pgmeta-version

Let us know if this resolves the problem on your side, or if you hit anything else.

For context: the earlier behavior around function handling was a bit too loose it only matched on the function name and didn’t always verify that the function was callable from where it was used. On top of that, some types were inferred incorrectly (arrays vs objects, etc.), which could lead to runtime issues. Since those areas weren’t well covered by tests, it meant regressions like the ones you’ve seen could sneak through.

We’re tightening this up now: improving correctness of the generated types and adding test coverage so these cases are properly caught in the future. Really appreciate you helping surface these edge cases it makes the whole system stronger

avallete avatar Sep 29 '25 10:09 avallete

The most recent updates seems to have fixed a lot of the errors for this issue but I'm still seeing type errors related to #1366 so it's hard to know if this one is resolved yet. I'll take another look later and try to comment on that issue with more details.

gwax avatar Sep 29 '25 16:09 gwax

I have one edge case related to this that doesn't seem to be working correctly. I'm going to see if this is on our end or if it's something that I can reproduce.

gwax avatar Sep 30 '25 16:09 gwax

This appears fixed as of @avallete changes getting deployed.

gwax avatar Nov 01 '25 19:11 gwax