kysely
kysely copied to clipboard
Adds `onReserveConnection` to Postgres and MySQL dialect configs
- Adds the
onReserveConnectioncallback to the Postgres and MySql dialect drivers - This method is called for every connection checkout, regardless if the connection has been seen before or not.
- Companion to
onCreateConnection
Problem
My projects use row-level security in Postgres to ensure multi-tenancy. As a result I have a need to ensure Postgres session variables are set on a given connection to ensure context is carried through. The pre-existing onCreateConnection callback for the Postgres dialect only executes on new connections, meaning if a connection doesn't expire and is re-used by the pool the callback will not fire and context setting will not happen.
For example, assume we run SET app.org_id = ${org_id} for every connection:
- Pool is empty (no connections)
- Request handler asks for a connection for OrgA.
- A new connection, Con1, is created and returned
- Kysely executes
onCreateConnectionwhich runsSET app.org_id = OrgAon Con1 - Request handler completes, Con1 is returned to the Pool
- Request handler asks for connection for OrgB
- Con1 is reused and returned by the Pool (as it has not expired and closed)
- Kysely does NOT execute
onCreateConnection - Request handler fails to complete as sql queries are blocked by RLS policies (context is set to OrgA, but app attempts to make OrgB queries)
Adding an additional callback that runs every time a connection is pulled from Kysely mitigates the issue by ensuring the session variables can be set every time at the expense of possibly running it more often than is required.