Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default value in Knex migration?

Tags:

knex.js

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?

like image 300
serverpunk Avatar asked Feb 13 '19 07:02

serverpunk


1 Answers

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.

like image 98
Nedko Dimitrov Avatar answered Oct 19 '22 15:10

Nedko Dimitrov