rmp135 / sql-ts

Generate TypeScript interfaces from a SQL database.
MIT License
466 stars 64 forks source link

NOT NULL constraint lost for a view #101

Closed je-l closed 2 years ago

je-l commented 2 years ago

Hi, thanks for the project!

I'm using Postgres 14 and I have SQL like this:

CREATE TABLE country (name TEXT PRIMARY KEY NOT NULL);

CREATE VIEW country_extended AS
SELECT
  country.name AS country_name
FROM country;

SELECT * FROM country_extended;

The tool generates the following Typescript:

export interface countryEntity {
  'name': string;
}
export interface country_extendedEntity {
  'country_name'?: string | null;
}

I believe more accurate type should be simply 'country_name': string. I suspect there might be complexity to this because of joins, but I'm sure this would be very useful. Would this be possible to implement?

rmp135 commented 2 years ago

I don't think it's possible to fix.

Looking in pgAdmin at the definition of that view column, it shows in the properties that it's nullable, even though the referenced column is not.

It appears postgres views simply lose their underlying attributes (the question was from 9 years ago but nothing has changed).

However, you can work around this with the columnOptionality to set the optionality, and typeOverrides to set the type and nullability. It's a lot of manual intervention but appears to be the only way. A columnNullability option might be something I look into to keep the type but force nullability.

je-l commented 2 years ago

I see, this seems to be simply how Postgres handles views. Looking at the Stackoverflow comments, also Hasura is struggling with the same issue. The current workaround is fine for me.