我目前正在与sequelize v5一起在一个后端项目上工作,我们正在使用PostgreSQL作为数据库。
我知道sequelize可以将钩子定义为实现触发器的一种手段,但是,我需要直接在数据库上实现(或定义)数据库触发器。
我以detailed in the docs的形式定义了钩子,但注意到它未能在数据库上正式定义触发器。
hooks: {
beforeUpdate: (instance, options) => {
sequelize.models.themodelIwantToUse.create({
actionType: 'UPDATE',
key: instance.dataValues.key,
newValue: instance.dataValues.value,
oldValue: instance._previousDataValues.value,
createdAt: instance.dataValues.createdAt,
createdBy: instance.dataValues.createdBy
})
}
}
项目经理坚持要声明触发器,所以我做了以下事情:
sequelize.query("" +
"CREATE OR REPLACE FUNCTION the_model_i_want_to_use_log_func() " +
" RETURNS TRIGGER " +
"AS $$ " +
"BEGIN " +
" IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN " +
" INSERT INTO a_schema.the_model_i_want_to_use(key, action_type, old_value, new_value, created_at, created_by) VALUES (NEW.key, TG_OP, OLD.value, NEW.value, NEW.created_at, NEW.created_by); " +
" RETURN NEW; " +
" END IF; " +
"" +
" RETURN NEW; " +
"END; " +
"$$ " +
" LANGUAGE plpgsql; " +
"DROP TRIGGER IF EXISTS general_config_log ON a_schema.the_model_i_want_to_use; " +
"CREATE TRIGGER general_config_log " +
"AFTER INSERT OR UPDATE OR DELETE ON a_schema.the_model_i_want_to_use" +
"FOR EACH ROW EXECUTE PROCEDURE the_model_i_want_to_use_log_func(); "
);
上面的代码段(您可以说)的问题是,每次实例化squelize时,它将重写触发器和函数。
我知道,如果我们将数据库更改为MySql(例如,将数据库更改为MySql),这会中断,但这不是我目前担心的问题。
是否有其他方法或正确方法来声明带有续集的触发器?
答案 0 :(得分:0)
通过处理历史记录来处理数据库更改的正确方法是使用序列迁移。
这需要在src / migrations目录(可选)中安装sequelize-cli。 请参阅文档。
https://sequelize.org/master/manual/migrations.html
示例:
在src / migration / create_table_person.js中创建迁移文件
module.exports = {
arriba: función (queryInterface, DataTypes) {
return queryInterface.createTable ('par_ec', {
id_par_ec: {
tipo: DataTypes.INTEGER,
primaryKey: verdadero,
allowNull: falso,
autoIncrement: verdadero
},
nombre: {
tipo: DataTypes.TEXT,
allowNull: falso
}
});
}
};
与src / config / data_base.json数据库的连接设置
{
"username": "postgres",
"contraseña": "admin",
"base de datos": "ppte",
"host": "localhost",
"dialecto": "postgres",
"zona horaria": "América / La_Paz",
"MigrationStorage": "secuelizar",
"MigrationStorageTableName": "sequelize_migration",
"registro": falso,
"grupo": {
"max": 15,
"min": 0,
"inactivo": 10000,
"adquirir": 10000,
"desalojar": 10000,
"handleDisconnects": verdadero,
"autoreconnect": verdadero
}
}
执行所有待处理的迁移
sequelize db: migrate --migrations-path src / migrations --config src / config / data_base.json