I would like to set a default value for a primary key in a Knex migration, but I'm running into issues. This is my initial migration:
exports.up = (knex, Promise) => {
return knex.schema.createTable(
'users',
(table) => {
table.uuid('id').primary();
table.string('email');
}
);
};
I would like to default the id
field to a random UUID. So this is my next migration:
exports.up = (knex, Promise) => {
return Promise.all([
knex.raw('create extension if not exists "uuid-ossp"'),
knex.schema.alterTable('users', (table) => {
table.uuid('id')
.defaultTo(knex.raw('uuid_generate_v4()'))
.alter();
}),
]);
};
When I run that I get the following error:
migration failed with error: alter table "users" alter column "id" drop not null - column "id" is in a primary key
Based on that it looks like Knex is trying to drop the NOT NULL
constraint. I tried chaining a .notNullable()
before the .defaultTo()
and it still gives the same error. Is there something I'm doing wrong?
Here is a quick copy/paste answer for those who came here searching "How to set a default value in Knex migration"
table.string('state').notNullable().defaultTo('pending')
Note: notNullable()
is not required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With