如何使用 Knex.js 为连接池中的每个连接定义默认设置



我需要为连接池中的每个连接设置默认会话配置,例如 Oracle 数据库的TIME_ZONE、LNS_DATE_LANGUAGE等。Knex.js文档提供了一个演示如下的代码片段,但适用于PostgreSQL:

var knex = require('knex')({
client: 'pg',
connection: {hos: ''},
pool: {
afterCreate: function (conn, done) {
// in this example we use pg driver's connection API
conn.query('SET timezone="UTC";', function (err) {
if (err) {
// first query failed, return error and don't try to make next query
done(err, conn);
} else {
// do the second query...
conn.query('SELECT set_limit(0.01);', function (err) {
// if err is not falsy, connection is discarded from pool
// if connection aquire was triggered by a query the error is passed to query promise
done(err, conn);
});
}
});
}
}
});

oracledb 的方法是为sessionCallback属性定义回调:

async function init() {
try {
await oracledb.createPool({
user: 'USER',
password: 'PWD',
connectString: 'HOST:1521/SERVICE',
sessionCallback: initSession //HERE MY DEFAULT SETTINGS
});
} catch (e) {
console.error(e);
}
}
async function initSession(connection, requestedTag, cb) {
try {
await connection.execute(`
ALTER SESSION SET 
TIME_ZONE='UTC'
NLS_LANGUAGE = 'BRAZILIAN PORTUGUESE'
NLS_TERRITORY = 'BRAZIL'
NLS_CURRENCY = 'R$'
NLS_ISO_CURRENCY = 'BRAZIL'
NLS_NUMERIC_CHARACTERS = ',.'
NLS_CALENDAR = 'GREGORIAN'
NLS_DATE_FORMAT = 'DD/MM/YYYY'
NLS_DATE_LANGUAGE = 'BRAZILIAN PORTUGUESE'
NLS_SORT = 'WEST_EUROPEAN'
NLS_TIMESTAMP_FORMAT = 'DD/MM/YYYY HH24:MI:SS'
NLS_DUAL_CURRENCY = 'R$'
`);
} catch (e) {
console.error(e);
cb(e);
} finally {
if (connection) {
await connection.close();
}
}
}

我希望能够将上面的这个片段翻译为 Knex.js 实现。怎么做?

您的 KNEX 是否使用 Oracle DB 的连接池? https://github.com/tgriesser/knex/issues/2665 将其显示为未来的项目。

尝试您发布的 pg 代码段,使用其他示例中的 ALTER 会话购买。

最新更新