CockroachDB inserting additional `rowid` column when using `.primary()`
See original GitHub issueEnvironment
Knex version: 2.1.0 Database + version: CockroachDB v22.1 (v21 affected as well) OS: macOS 12.3.1
Bug
Behavior
When using CockroachDB, creating a primary key of type UUID:
await database.schema.createTable("example_a", (table) => {
table.uuid("id").notNullable().primary();
});
will cause a secondary “rowid” column to be autogenerated. This is most likely due to the fact that knex
generates two SQL queries to create this table+id combo:
db.schema
.createTable("example_a", (table) => {
table.uuid("id").notNullable().primary();
})
.toSQL();
// [
// {
// sql: 'create table "example_a" ("id" uuid not null)',
// bindings: []
// },
// {
// sql: 'alter table "example_a" add constraint "example_a_pkey" primary key ("id")',
// bindings: []
// }
// ]
The first SQL query executed in Cockroach will generate the default “rowid” column, as cockroach requires a primary key to exist in the table. This means the issue (and hopefully the fix) is very similar to https://github.com/knex/knex/issues/4141 / https://github.com/knex/knex/pull/5017.
A temporary workaround is to use a specificType
, for example:
await database.schema.createTable("example_b", (table) => {
table.specificType("id", "UUID PRIMARY KEY");
});
as that generates SQL that correctly creates the primary key in the first query in CRDB:
database.schema
.createTable("example_b", (table) => {
table.specificType("id", "UUID PRIMARY KEY");
})
.toSQL();
// [
// {
// sql: 'create table "example_b" ("id" UUID PRIMARY KEY)',
// bindings: []
// }
// ]
Reproduction
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:17 (9 by maintainers)
Top GitHub Comments
I think #5212 is now ready. I didn’t add tests/support for composite keys since i think the change is already enough on it’s own and it’s somewhat offtopic wrt the itch i’m scratching anyways.
It looks like implementing a
primaryKey
option as intable.uuid('id', {primaryKey: true});
would be much easier than adding support fortable.uuid('id').primary()
.I have a basic PoC for PostgreSQL working locally, if you’re ok with adding the option to
uuid()
I’ll look into implementing it across the board. The option would work like theprimaryKey
option onincrements
andbigincrements
but it would default tofalse
and only do something on PostgreSQL style databases.Let me know if this would be something you would accept and I’ll prepare a PR.