| 129 | * transaction-handle queries are exempt by construction. |
| 130 | */ |
| 131 | export function instrumentPoolClient<T extends InstrumentablePoolClient>( |
| 132 | client: T, |
| 133 | poolName: string |
| 134 | ): T { |
| 135 | // double-cast-allowed: widens the postgres client's generic method signatures to plain callables so the wrappers can forward arbitrary arguments unchanged |
| 136 | const target = client as unknown as CallableClient |
| 137 | const rawUnsafe = target.unsafe.bind(target) |
| 138 | const rawBegin = target.begin.bind(target) |
| 139 | |
| 140 | target.unsafe = (...args: unknown[]) => { |
| 141 | if (transactionContext.getStore()) { |
| 142 | report(poolName, typeof args[0] === 'string' ? args[0] : '(non-string query)') |
| 143 | } |
| 144 | return rawUnsafe(...args) |
| 145 | } |
| 146 | |
| 147 | target.begin = (...args: unknown[]) => { |
| 148 | if (transactionContext.getStore()) { |
| 149 | report(poolName, 'BEGIN (nested transaction opened on the global client)') |
| 150 | } |
| 151 | const callbackIndex = args.length - 1 |
| 152 | const callback = args[callbackIndex] |
| 153 | if (typeof callback === 'function') { |
| 154 | args[callbackIndex] = (...callbackArgs: unknown[]) => |
| 155 | transactionContext.run(true, () => |
| 156 | (callback as (...inner: unknown[]) => unknown)(...callbackArgs) |
| 157 | ) |
| 158 | } |
| 159 | // postgres-js issues its internal BEGIN/COMMIT statements through the |
| 160 | // root client's `unsafe`; running `begin` outside the ambient context |
| 161 | // keeps those from re-reporting a nested transaction the wrapper above |
| 162 | // already reported. The callback wrapper re-enters the context itself. |
| 163 | return transactionContext.exit(() => rawBegin(...args)) |
| 164 | } |
| 165 | |
| 166 | return client |
| 167 | } |