supabase / postgrest-js

Isomorphic JavaScript client for PostgREST.
https://supabase.com
MIT License
965 stars 129 forks source link

Exclude generated columns from the insert type #400

Open yannxaver opened 1 year ago

yannxaver commented 1 year ago

Bug report

Describe the bug

Postgres allows the creation of generated columns: https://www.postgresql.org/docs/current/ddl-generated-columns.html. Inserting a value into such a column throws an error: https://www.tutorialsteacher.com/postgresql/generated-always. Supabase includes these columns in its table['Insert'] type which goes against the functionality of postgres.

To Reproduce

Expected behavior

Exclude generated columns.

juanvilladev commented 1 year ago

Yeah, this would be amazing. I don't see any use case for having the generated columns there. They shouldn't even be queryable by the Supabase Client IMO.

soedirgo commented 1 year ago

Hmm, I thought we already do exclude it: https://github.com/supabase/postgres-meta/blob/df5df091c2b33eaea2e747bdb5bce3d18f74dad6/src/server/templates/typescript.ts#L103

Do you have an example schema I could reproduce this with?

soedirgo commented 1 year ago

Tried reproducing this - here's what I got:

create table t (id int8 generated always as identity);
export type Json =
  | string
  | number
  | boolean
  | null
  | { [key: string]: Json }
  | Json[]

export interface Database {
  public: {
    Tables: {
      t: {
        Row: {
          id: number
        }
        Insert: {
          id?: never
        }
        Update: {
          id?: never
        }
      }
    }
    Views: {
      [_ in never]: never
    }
    Functions: {
      [_ in never]: never
    }
    Enums: {
      [_ in never]: never
    }
    CompositeTypes: {
      [_ in never]: never
    }
  }
}

The type is replaced with undefined, which is acceptable because undefined values are stripped out on JSON.stringify(). But you'll see an error if you supply a number there.

yannxaver commented 1 year ago

If I run

alter table foo
add column bar numeric GENERATED ALWAYS AS (col_a + col_b) STORED

the generated type becomes

Insert: {
  bar?: number | null
}

// same for update
soedirgo commented 1 year ago

Ah, thanks - I was able to reproduce this.