在 knexjs 中使用 current_timestamp() 触发更新 mysql

Trigger to update mysql with current_timestamp() in knexjs

我正在使用 MySQL 并希望在更改记录时执行触发器并更新数据库中的 updated_at 列。

这是我的迁移文件:

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

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)

这是我的 knexfile.js

onUpdateTrigger: (table) => `
    CREATE TRIGGER ${table}_updated_at
    BEFORE UPDATE ON ${table}
    FOR EACH ROW
    EXECUTE PROCEDURE on_update_timestamp();
  `

这是我给用户的文件链接:

exports.up = async (knex) => {
  await knex.schema.createTable('users', (table) => {
    table.increments('id')
    table.string('email').notNullable()
    table.string('password').notNullable()
    table.string('reset_token')
    table.timestamp('reset_expires')
    table.timestamp('created_at').defaultTo(knex.fn.now())
    table.timestamp('updated_at').defaultTo(knex.fn.now())
  }).then(() => knex.raw(onUpdateTrigger('users')))
}

当我 运行 npx knex migrate:latest 我得到一个错误:

migration file "20210918131335_add_custom_functions.js" failed
migration failed with error:
  CREATE OR REPLACE FUNCTION on_update_timestamp()
  RETURNS trigger AS $$
  BEGIN
      NEW.updated_at = now();
      RETURN NEW;
  END;
 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FUNCTION on_update_timestamp()
  RETURNS trigger AS $$
  BEGIN
      NEW.updated' at line 1

我解决了这个问题:

table.timestamp('updated_at').defaultTo(
  knex.raw('NULL ON UPDATE CURRENT_TIMESTAMP')
)