js强制对以下4个查询进行会话重用

js强制对以下4个查询进行会话重用

本文介绍了Knex.js强制对以下4个查询进行会话重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个子查询,该子查询正在四个不同的查询中使用,所有这些查询都执行以呈现一些类似于仪表板的功能。
所有查询的共同点是该子查询,我想将其提取到临时表中。
这是成功的,但是使用Knex.js(太神奇了),连接被池化了,这意味着所有查询都使用不同的连接,这又导致临时表被丢弃。

I have a sub-query that is being used in four different queries that all execute to present some dashboard like functionality.The common ground for all queries is this sub-query which I want to extract in a temporary table.This has been a success, but using Knex.js (which is amazing) the connections are pooled, which means that all the queries use different connections which again lead to the temporary table being dropped in between.

有没有办法强制使用一个连接,而在Knex中使用这种方式进行一次会话?还是我需要寻找其他解决方法,例如将其全部包装在事务中?

Is there any way to force using one connection, and one session in Knex this way? Or would I need to look for other workarounds, such as wrapping it all in a transaction?

推荐答案

基本上,您只能这样做通过在同一事务中运行这些查询。这迫使knex对所有查询使用相同的连接。

Basically you can do that only by running those queries in the same transaction. That forces knex to use the same connection for all of the queries.

另一种方法是使用 knex从池中手动获取连接。 client.aqcuireConnection()并使用 knex.connection(connection)在单个连接中运行查询。最后,您需要将连接释放回池中,以免使用 knex.client.releaseConnection(connection)泄漏连接。

Another way to do it is to acquire connection from pool manually with knex.client.aqcuireConnection() and use knex.connection(connection) to run queries in that single connection. Finally you need to release the connection back to the pool to not leak connections with knex.client.releaseConnection(connection).

类似的东西:

let connection = await knex.client.acquireConnection();
try {
    const res = await knex('table').connection(connection).where('id',1);
    const res2 = await knex('table2').connection(connection).where('id',1);
} finally {
    knex.client.releaseConnection(connection);
}

这篇关于Knex.js强制对以下4个查询进行会话重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 01:16