postgres-meta icon indicating copy to clipboard operation
postgres-meta copied to clipboard

Typegen is not respecting unique table constraint

Open kristofferso opened this issue 2 years ago • 3 comments

Describe the bug I have three tables. One main table customers and two linked tables addresses and orders. They both are linked to the customers table's id column, but the addresses table has a unique constraint on customer_id relation column. The problem is that the generated types assumes that both table relations are one to many.

To Reproduce Steps to reproduce the behavior:

  1. Start a new project and create three tables. Reference one main table from the two others, one with a unique constraint and one without.
  2. Generate types using npx supabase gen types typescript --local > types/supabase.ts
  3. Use const supabase = createClient<Database>() and query const { data } = supabase .from("customers") .select("*, orders (id), addresses (id)").single()
  4. see that the type of data.orders and data.addresses are both an array of objects.

Expected behavior The types to respect the unique constraint and be an object and not an array of objects.

Desktop

  • OS: Mac OS 13.4.1
  • Version of CLI: v1.93.0
  • Version of supabase-js: v2.33.2
  • Version of Node.js: v16.14.2

kristofferso avatar Sep 13 '23 12:09 kristofferso

I agree this is a non-intuitive query pattern of PostgREST. As a workaround, you can specify the foreign key to get back a single entity. For eg.

const { data } = supabase.
    from("customers").
    select("*, orders!orders_customer_id_fkey (id), addresses!addresses_customer_id_fkey (id)").
    single()

Hope it helps.

sweatybridge avatar Sep 13 '23 13:09 sweatybridge

Thank you for the quick reply @sweatybridge 🙏 . So that didn't work for me unfortunately. Maybe I should clarify – the actual data returned from the query has the correct structure (not an array), only the types are wrongly inferred as an array of objects.

Maybe you understood that already, but regardless specifying the foreign key doesn't get me the right type structure unfortunately :(

kristofferso avatar Sep 13 '23 20:09 kristofferso

Thank you for clarifying. I'm transferring this issue to postgres-meta repo which the cli uses for typegen. @soedirgo might have a better idea of what fixes are needed here.

sweatybridge avatar Sep 15 '23 03:09 sweatybridge