Search code examples
knex.js

I want to know how to add & drop default () to colmun later


I am using knex.js. I want to know how to add & drop default () to colmun later.

The column has already been created.

knex.schema.alterTable('users', function(t) {
    t.string('email', 30).notNullable()
})

The add & drop of unique found. https://knexjs.org/#Schema-unique https://knexjs.org/#Schema-dropUnique

ADD:

   knex.schema.alterTable('users', function(t) {
      t.unique('email') 
   })

DROP:

   knex.schema.alterTable('users', function(t) {
      t.dropUnique('email') 
   })

but, the default add & drop method is not found

I tried this.

knex.schema.alterTable('users', function(t) {
 t.dropUnique('email').defaultTo('[email protected]')
})

I got this error message.

ER_DUP_FIELDNAME: Duplicate column name 'email'

Is there anyone who knows how?


Solution

  • This should do it:

    knex.schema.alterTable('users', function(t) {
      t.string('email', 30).notNullable().defaultTo('[email protected]').alter();
    });
    

    .alter() in the end of query builder tells knex to create alter table declaration for the column instead of normal column add (in many databases altering like that is not trivial at all, but this works for basic cases and changing type / default and not nullable at least).