@@ -15,7 +15,18 @@ import type { Operator, PostgresClient } from "./client.ts"
1515 * The inner effect runs in the parent fiber (via `Effect.exit`) so all
1616 * provided services (repositories, etc.) remain available inside the
1717 * transaction scope.
18+ *
19+ * **Concurrent transactions**: do NOT run two `transaction()` calls
20+ * concurrently on the same SqlClient instance (e.g. via `Effect.all` with
21+ * concurrency > 1). `activeTx` has no fiber identity, so concurrent
22+ * transactions will overwrite each other's operator and corrupt both
23+ * connections. Use separate `SqlClientLive` layer instances instead.
1824 */
25+ const setRlsContext = ( tx : Operator , organizationId : OrganizationId ) => {
26+ if ( organizationId === "system" ) return Promise . resolve ( )
27+ return tx . execute ( sql `select set_config('app.current_organization_id', ${ organizationId } , true)` )
28+ }
29+
1930export const SqlClientLive = ( client : PostgresClient , organizationId : OrganizationId = OrganizationId ( "system" ) ) =>
2031 Layer . effect (
2132 SqlClient ,
@@ -42,7 +53,7 @@ export const SqlClientLive = (client: PostgresClient, organizationId: Organizati
4253 } )
4354
4455 const txPromise = client . transaction ( async ( tx ) => {
45- await tx . execute ( sql `select set_config('app.current_organization_id', ${ organizationId } , true)` )
56+ await setRlsContext ( tx as Operator , organizationId )
4657 resolveTxReady ( tx as Operator )
4758 const result = await effectDone
4859 if ( ! result . ok ) throw result . error
@@ -89,7 +100,7 @@ export const SqlClientLive = (client: PostgresClient, organizationId: Organizati
89100 return yield * Effect . tryPromise ( {
90101 try : ( ) =>
91102 client . transaction ( async ( tx ) => {
92- await tx . execute ( sql `select set_config('app.current_organization_id', ${ organizationId } , true)` )
103+ await setRlsContext ( tx as Operator , organizationId )
93104 return fn ( tx as Operator , organizationId )
94105 } ) ,
95106 catch : ( error ) => toRepositoryError ( error , "query" ) ,
0 commit comments