如何为Knex迁移语句统一前置添加固定SET ROLE SQL命令?
可行实现方案
方案1:全局连接自动追加(推荐,适配所有场景)
利用Knex的afterCreate连接生命周期钩子,所有新建的数据库连接都会自动执行SET ROLE语句,不管是迁移、业务查询还是其他操作都会生效。
knexfile.js配置示例:
module.exports = { development: { client: 'postgresql', connection: { host: '127.0.0.1', user: 'your_user', password: 'your_pass', database: 'your_db' }, pool: { afterCreate: (conn, done) => { conn.query(`SET ROLE 'example_user'`, (err) => { done(err, conn); }); } } } }
该方案对业务代码无侵入,也适配迁移时直接执行、导出SQL文件等所有场景,不需要修改现有迁移脚本。
方案2:仅针对迁移流程追加
如果不需要全局生效,只希望迁移操作执行时前置该语句,可以用Knex迁移的生命周期钩子:
module.exports = { development: { // 其他基础配置同上 migrations: { directory: './migrations', beforeMigrate: async (knex) => { await knex.raw(`SET ROLE 'example_user'`); } } } }
如果是需要导出SQL文件的场景(执行knex migrate:latest --sql生成SQL文件),可以封装统一的迁移模板,所有迁移脚本复用该模板即可:
// 迁移脚本公用封装函数 const wrapMigration = (migrationFunc) => { return { up: async (knex) => { await knex.raw(`SET ROLE 'example_user'`); await migrationFunc.up(knex); }, down: async (knex) => { await knex.raw(`SET ROLE 'example_user'`); await migrationFunc.down(knex); } } } // 具体迁移脚本写法 module.exports = wrapMigration({ async up(knex) { await knex.schema.createTable('Persons', table => { table.integer('PersonID'); table.string('LastName', 255); table.string('FirstName', 255); table.string('Address', 255); table.string('City', 255); }) }, async down(knex) { await knex.schema.dropTable('Persons'); } })
内容的提问来源于stack exchange,提问作者bzupnick
相关产品推荐
相关产品推荐

