@@ -8,8 +8,7 @@ import { isProdEnv } from '../helpers/values';
8
8
*/
9
9
export const sqlTransactionContext = new AsyncLocalStorage < SqlTransactionContext > ( ) ;
10
10
type SqlTransactionContext = {
11
- usageName : string ;
12
- sql : PgSqlClient ;
11
+ [ dbName : string ] : PgSqlClient ;
13
12
} ;
14
13
type UnwrapPromiseArray < T > = T extends any [ ]
15
14
? {
@@ -26,8 +25,9 @@ export abstract class BasePgStore {
26
25
* async context will be returned to guarantee transaction consistency.
27
26
*/
28
27
get sql ( ) : PgSqlClient {
28
+ const dbName = this . _sql . options . database ?. toString ( ) ?? 'default' ;
29
29
const sqlContext = sqlTransactionContext . getStore ( ) ;
30
- return sqlContext ? sqlContext . sql : this . _sql ;
30
+ return sqlContext ? sqlContext [ dbName ] : this . _sql ;
31
31
}
32
32
private readonly _sql : PgSqlClient ;
33
33
@@ -52,15 +52,16 @@ export abstract class BasePgStore {
52
52
callback : ( sql : PgSqlClient ) => T | Promise < T > ,
53
53
readOnly = true
54
54
) : 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 > ;
59
60
}
60
61
// Otherwise, start a transaction and store the scoped connection in the current async context.
61
- const usageName = this . _sql . options . connection . application_name ?? '' ;
62
62
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 ) ) ;
64
65
} ) ;
65
66
}
66
67
0 commit comments