supabase / cli

Supabase CLI. Manage postgres migrations, run Supabase locally, deploy edge functions. Postgres backups. Generating types from your database schema.
https://supabase.com/docs/reference/cli/about
MIT License
994 stars 193 forks source link

[Bug?] Views with non-nullable properties are nullable in generated types #577

Open xxRockOnxx opened 1 year ago

xxRockOnxx commented 1 year ago

Bug report

So as mentioned in the title: Views with non-nullable properties are nullable in generated types.

Describe the bug

Related StackOverflow question: https://stackoverflow.com/questions/17301323/why-are-my-views-columns-nullable

It seems like according to one of the answers:

The nullability tracking in PostgreSQL is not developed very much at all. In most places, it will default to claiming everything is potentially nullable, which is in many cases allowed by the relevant standards. This is the case here as well: Nullability is not tracked through views. I wouldn't rely on it for an application.

According to another one of the answers, you can also set the nullability manually.

The CLI seems to solely use Postgres as the source of truth.

That said, I'm not sure however if letting CLI check the base table would be an option.

It seems like either that or setting the attribute manually are the only options.

To Reproduce

Expected behavior

Generated view properties are the same as the base table

System information

soedirgo commented 1 year ago

Yeah, I think this is a limitation on the Postgres side as per the SO link. See also: https://github.com/supabase/cli/issues/385#issuecomment-1253370577

So the only option is probably setting the nullability manually. The typegen currently ignores that though - I'll keep this issue open until we fix that.

enyo commented 1 year ago

This might help you @xxRockOnxx I wrote this helper utility type in typescript:

type NonNullableRow<Row, NullableKeys = never> = {
  [key in keyof Row]: key extends NullableKeys
    ? Row[key]
    : NonNullable<Row[key]>
}

It can be used like this:

type ProfileWithStats = NonNullableRow<
  Database['public']['Views']['profiles_with_stats']['Row'],
  'email_hash' | 'middle_name'
>

The second generic argument is optional, if you don't provide it, then all fields will be non nullable. But if some fields actually are nullable, then you can provide the list too.

enyo commented 1 year ago

@soedirgo any info on when this might get added to the cli (it seems to be fixed already in postgres-meta?)

binury commented 6 months ago

This is still causing any and all view typings generated to be unusable