RobinBlomberg / kysely-codegen

Generate Kysely type definitions from your database.
MIT License
770 stars 69 forks source link

Generated column loses Generated<T> wrapper after renaming table #119

Open austerj opened 10 months ago

austerj commented 10 months ago

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

Fund with Polar

austerj commented 10 months ago

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'>
lukas-slezevicius commented 9 months ago

I got the exact same issue.

cassus commented 8 months ago

Workaround

Rename the sequence as you renamed the table/column.

Eg:

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