@@ -8,8 +8,7 @@ import { isProdEnv } from '../helpers/values';
88 */
99export const sqlTransactionContext = new AsyncLocalStorage < SqlTransactionContext > ( ) ;
1010type SqlTransactionContext = {
11- usageName : string ;
12- sql : PgSqlClient ;
11+ [ dbName : string ] : PgSqlClient ;
1312} ;
1413type UnwrapPromiseArray < T > = T extends any [ ]
1514 ? {
@@ -26,8 +25,9 @@ export abstract class BasePgStore {
2625 * async context will be returned to guarantee transaction consistency.
2726 */
2827 get sql ( ) : PgSqlClient {
28+ const dbName = this . _sql . options . database ?. toString ( ) ?? 'default' ;
2929 const sqlContext = sqlTransactionContext . getStore ( ) ;
30- return sqlContext ? sqlContext . sql : this . _sql ;
30+ return sqlContext ? sqlContext [ dbName ] : this . _sql ;
3131 }
3232 private readonly _sql : PgSqlClient ;
3333
@@ -52,15 +52,16 @@ export abstract class BasePgStore {
5252 callback : ( sql : PgSqlClient ) => T | Promise < T > ,
5353 readOnly = true
5454 ) : Promise < UnwrapPromiseArray < T > > {
55- // Do we have a scoped client already? Use it directly.
56- const sqlContext = sqlTransactionContext . getStore ( ) ;
57- if ( sqlContext ) {
58- return callback ( sqlContext . sql ) as UnwrapPromiseArray < T > ;
55+ // Do we have a scoped client already? Use it directly. Key is the database name.
56+ const dbName = this . _sql . options . database ?. toString ( ) ?? 'default' ;
57+ const sql = sqlTransactionContext . getStore ( ) ?. [ dbName ] ;
58+ if ( sql ) {
59+ return callback ( sql ) as UnwrapPromiseArray < T > ;
5960 }
6061 // Otherwise, start a transaction and store the scoped connection in the current async context.
61- const usageName = this . _sql . options . connection . application_name ?? '' ;
6262 return this . _sql . begin ( readOnly ? 'read only' : 'read write' , sql => {
63- return sqlTransactionContext . run ( { usageName, sql } , ( ) => callback ( sql ) ) ;
63+ const currentStore = sqlTransactionContext . getStore ( ) ?? { } ;
64+ return sqlTransactionContext . run ( { ...currentStore , [ dbName ] : sql } , ( ) => callback ( sql ) ) ;
6465 } ) ;
6566 }
6667
0 commit comments