Search code examples
javascriptmysqlnode.jsknex.js

How to auto update record with knex.js and MySQL


This is my first post, so please correct me if I do something wrong.
I have some tables in MySQL that have the updated_at columns that I want to update it values whenever the tables are updated. It is very similar to this problem that was resolved this way:

const ON_UPDATE_TIMESTAMP_FUNCTION = `
  CREATE OR REPLACE FUNCTION on_update_timestamp()
  RETURNS trigger AS $$
  BEGIN
    NEW.updated_at = now();
    RETURN NEW;
  END;
$$ language 'plpgsql';
`

const DROP_ON_UPDATE_TIMESTAMP_FUNCTION = `DROP FUNCTION on_update_timestamp`

exports.up = knex => knex.raw(ON_UPDATE_TIMESTAMP_FUNCTION)
exports.down = knex => knex.raw(DROP_ON_UPDATE_TIMESTAMP_FUNCTION)

Otherwise, the linked problem is made with Postgres and my RDB is MySQL, so I would want to know if there is a way to do this solution with MySQL. I tried something like this but that way I can't dynamically get the table to be changed:

const CUSTOM_FUNCTIONS = `
ALTER TABLE NEW
    CHANGE updated_at
        updated_at TIMESTAMP NOT NULL
            DEFAULT CURRENT_TIMESTAMP
            ON UPDATE CURRENT_TIMESTAMP;
`

const DROP_CUSTOM_FUNCTIONS = `
DROP FUNCTION on_update_timestamp;
`

exports.up = async (knex) => knex.raw(CUSTOM_FUNCTIONS);
exports.down = async (knex) => knex.raw(DROP_CUSTOM_FUNCTIONS);

Solution

  • I tested this solution and it worked to me. It's not the best but for my projects it's enough. Basically, when I update my record, my controller automatically update the updated_at column with the current date.