adelsz / pgtyped

pgTyped - Typesafe SQL in TypeScript
https://pgtyped.dev
MIT License
2.97k stars 97 forks source link

Array spread and pick infers wrong type when used as `insert into ... select from (values :rows) as t` #498

Open yaziciahmet opened 1 year ago

yaziciahmet commented 1 year ago

Describe the bug When using array spread and pick variable called rows, as follows: insert into ... select ... from (values :rows) as t (col1, col2), the types of col1 and col2 are automatically assumed to be string, even though there are number type columns in the inserted table.

Expected behavior I would expect the type of the rows would be inferred appropriately. If this is due to postgres engine, I believe there should be a way to declare the types of the array spread and pick variables.

Test case

/*
    @name CreateIssues
    @param issues -> ((issueId!, badgeId!)...)
*/
INSERT INTO issue (id, badge_id)
SELECT tmp.issue_id, tmp.badge_id
FROM (VALUES :issues) AS tmp (issue_id, badge_id);

issue table's columns: id is TEXT, and badge_id is INT.

Here is the error I get when I try to generate ts from above query:

Error in query. Details: {
  errorCode: 'transformAssignedExpr',
  hint: 'You will need to rewrite or cast the expression.',
  message: 'column "badge_id" is of type integer but expression is of type text',
  position: '94'
}

I tried explicitly type casting as

/*
    @name CreateIssues
    @param issues -> ((issueId!, badgeId!)...)
*/
INSERT INTO issue (id, badge_id)
SELECT tmp.issue_id, tmp.badge_id::int
FROM (VALUES :issues) AS tmp (issue_id, badge_id);

Even though this removes error and successfully generates the ts, the params interface has badgeId as string.

Note: I simplified my original query as above for it to be easily readable.