Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disallow any additional properties to be passed to db.insert #170

Open
adrianmisko opened this issue Apr 13, 2024 · 2 comments
Open

Disallow any additional properties to be passed to db.insert #170

adrianmisko opened this issue Apr 13, 2024 · 2 comments

Comments

@adrianmisko
Copy link

I understand that it might be difficult because of how typescript interfaces work. Anyway:
Assume the following schema:

create table authors(name varchar(255) primary key, stage_name varchar(255));

I might have my own Author type:

interface Author {
  name: string
  stageName?: string
}

Then, I might forget about mapping my type to Insertable and try to insert my type directly. The type system will allow it:

  const authors = [{ name: 'Name', stageName: 'Stage name' }]
  db.insert('authors', authors).run(pool)

The generated query will break:

INSERT INTO "authors" ("name", "stageName") VALUES ($1, $2) RETURNING to_jsonb("authors".*) AS result // column "stageName" of relation "authors" does not exist

Related to #169 - if the nullable property had to be specified, I'd get Property 'stage_name' is missing in type 'Author' but required in type 'Insertable'.. That could prevent the error, unless I decided to add that property by using spread operator. Using an object-literal in that case would be safe.

However, it could be nice if there was a check for that - maybe even in runtime - to see if all the columns actually exist and filter out the imaginary columns. That should work because a TS interface checks in all the required fields are there, and the runtime filter removes any excess fields.

Is this doable? I don't know if the query generator has access to the schema.

@rosettaroberts-impact
Copy link

I don't know if the query generator has access to the schema.

If you look at the code for insert, it does not have access to the schema:

export const insert: InsertSignatures = function (

@rosettaroberts-impact
Copy link

rosettaroberts-impact commented Apr 15, 2024

Also, I don't think there is a way to fix this at type check time because

type A = {
  name: string;
  stageName?: string;
};

is a subtype of

type B = {
  name: string;
  stage_name?: string;
};

in typescript.

For your particular use case, I would try using the empty string instead of null :). That way, you could make stage_name always required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants