RobinBlomberg / kysely-codegen

Generate Kysely type definitions from your database.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Generated column loses Generated<T> wrapper after renaming table

austerj opened this issue · comments

After renaming a table, the primary key type no longer gets wrapped in Generated<Int8> despite the migration only modifying the table name - which is strange, since the types should be read directly from introspecting the schema as I understand it.

I'm using the Postgres dialect and tried resetting / reverting the migration and can confirm that the type is correctly generated up until changing the name of the table with no other changes being applied.

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

For now I'm using the following workaround (and importing this mutated type in place of the direct import from kysely-codegen):

import type { DB as _DB, Generated } from 'kysely-codegen'

type ForceGenerated<
    T extends Object,
    Tables extends keyof T,
    Column extends keyof T[Tables],
> = Omit<T, Tables> & {
    [TableK in Tables]: Omit<T[TableK], Column> & {
        [ColumnK in Column]: Generated<T[TableK][ColumnK]>
    }
}

export type DB = ForceGenerated<_DB, 'table', 'id'>

I got the exact same issue.

Workaround

Rename the sequence as you renamed the table/column.

Eg:

  • table: text_answer -> text_answers
  • column: id (no change)

ALTER SEQUENCE text_answer_id_seq RENAME TO text_answers_id_seq;

Tech details

I've looked into this a bit and the error seems to come from kysely core db.introspection.getTables() that returns isAutoIncrementing: false for the id column despite it's GENERATED ALWAYS AS IDENTITY

Source:

        // Detect if the column is auto incrementing by finding the sequence
        // that is created for `serial` and `bigserial` columns.
        this.#db
          .selectFrom('pg_class')
          .select(sql`true`.as('auto_incrementing'))
          // Make sure the sequence is in the same schema as the table.
          .whereRef('relnamespace', '=', 'c.relnamespace')
          .where('relkind', '=', 'S')
          .where('relname', '=', sql`c.relname || '_' || a.attname || '_seq'`)
          .as('auto_incrementing'),
      ])

https://github.com/kysely-org/kysely/blob/da1c552ac9628b1e10b23ddf769d245b044beb9b/src/dialect/postgres/postgres-introspector.ts#L61-L71