knex / postgresql updating a foreign key to null

Viewed 1149

I am using knex.js with postgresql So I have a table with a nullable foreign key.

shortened version:

exports.up = function (knex, Promise) {
  return knex.schema.createTable('Note', function (table) {
    table.string('id').primary()
    table
      .string('sourceId')
      .references('id')
      .inTable('Source')
      .onDelete('SET NULL')
      .index()
  })
}

exports.down = function (knex, Promise) {
  return knex.schema.dropTable('Note')
}

I am able to create a Note with or without a sourceId. However, if I create a Note with a sourceId and then update it to set the sourceId to NULL, the update does not work. I do not get an error message, but the foreign key is not removed.

For example if I create a Note with:

{
  id: '123',
  sourceId: '456'
}

and then try to update it:

const result = await Note.query().updateAndFetchById(id, {
  id: '123',
  sourceId: null
})

The result I get is :

Note {
id: '123',
sourceId: '456'
}

I have no problem if I try to update other nullable values to null (as long as they are not foreign keys) and I can update the sourceId to a different source's id. If I try to update a not nullable foreign key to null, I get an error. But in the above case, I get no error. It just doesn't update.

Any idea what might be going on here?

0 Answers
Related