@contember/database 2.1.0-rc.3 → 2.2.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (392) hide show
  1. package/CLAUDE.md +22 -0
  2. package/dist/development/index.cjs +9 -0
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +10 -1
  5. package/dist/development/index.js.map +1 -1
  6. package/dist/development/src/builders/CaseStatement.cjs.map +1 -1
  7. package/dist/development/src/builders/CaseStatement.js.map +1 -1
  8. package/dist/development/src/builders/ColumnExpressionFactory.cjs.map +1 -1
  9. package/dist/development/src/builders/ColumnExpressionFactory.js.map +1 -1
  10. package/dist/development/src/builders/Compiler.cjs.map +1 -1
  11. package/dist/development/src/builders/Compiler.js.map +1 -1
  12. package/dist/development/src/builders/ConditionBuilder.cjs +6 -0
  13. package/dist/development/src/builders/ConditionBuilder.cjs.map +1 -1
  14. package/dist/development/src/builders/ConditionBuilder.js +6 -0
  15. package/dist/development/src/builders/ConditionBuilder.js.map +1 -1
  16. package/dist/development/src/builders/DeleteBuilder.cjs.map +1 -1
  17. package/dist/development/src/builders/DeleteBuilder.js.map +1 -1
  18. package/dist/development/src/builders/InsertBuilder.cjs.map +1 -1
  19. package/dist/development/src/builders/InsertBuilder.js.map +1 -1
  20. package/dist/development/src/builders/LimitByGroupWrapper.cjs +1 -1
  21. package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  22. package/dist/development/src/builders/LimitByGroupWrapper.js +1 -1
  23. package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -1
  24. package/dist/development/src/builders/SelectBuilder.cjs.map +1 -1
  25. package/dist/development/src/builders/SelectBuilder.js.map +1 -1
  26. package/dist/development/src/builders/UpdateBuilder.cjs.map +1 -1
  27. package/dist/development/src/builders/UpdateBuilder.js.map +1 -1
  28. package/dist/development/src/builders/WindowFunction.cjs +1 -1
  29. package/dist/development/src/builders/WindowFunction.cjs.map +1 -1
  30. package/dist/development/src/builders/WindowFunction.js +1 -1
  31. package/dist/development/src/builders/WindowFunction.js.map +1 -1
  32. package/dist/development/src/builders/internal/Returning.cjs.map +1 -1
  33. package/dist/development/src/builders/internal/Returning.js.map +1 -1
  34. package/dist/development/src/builders/internal/Subqueries.cjs.map +1 -1
  35. package/dist/development/src/builders/internal/Subqueries.js.map +1 -1
  36. package/dist/development/src/builders/internal/Where.cjs.map +1 -1
  37. package/dist/development/src/builders/internal/Where.js.map +1 -1
  38. package/dist/development/src/builders/internal/With.cjs.map +1 -1
  39. package/dist/development/src/builders/internal/With.js.map +1 -1
  40. package/dist/development/src/builders/utils.cjs.map +1 -1
  41. package/dist/development/src/builders/utils.js.map +1 -1
  42. package/dist/development/src/client/AcquiredConnection.cjs +105 -32
  43. package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
  44. package/dist/development/src/client/AcquiredConnection.js +107 -34
  45. package/dist/development/src/client/AcquiredConnection.js.map +1 -1
  46. package/dist/development/src/client/Client.cjs +9 -1
  47. package/dist/development/src/client/Client.cjs.map +1 -1
  48. package/dist/development/src/client/Client.js +9 -1
  49. package/dist/development/src/client/Client.js.map +1 -1
  50. package/dist/development/src/client/Connection.cjs +19 -1
  51. package/dist/development/src/client/Connection.cjs.map +1 -1
  52. package/dist/development/src/client/Connection.js +19 -1
  53. package/dist/development/src/client/Connection.js.map +1 -1
  54. package/dist/development/src/client/EventManager.cjs +6 -2
  55. package/dist/development/src/client/EventManager.cjs.map +1 -1
  56. package/dist/development/src/client/EventManager.js +6 -2
  57. package/dist/development/src/client/EventManager.js.map +1 -1
  58. package/dist/development/src/client/Pool.cjs.map +1 -1
  59. package/dist/development/src/client/Pool.js.map +1 -1
  60. package/dist/development/src/client/RequestMemoryBudget.cjs +237 -0
  61. package/dist/development/src/client/RequestMemoryBudget.cjs.map +1 -0
  62. package/dist/development/src/client/RequestMemoryBudget.js +237 -0
  63. package/dist/development/src/client/RequestMemoryBudget.js.map +1 -0
  64. package/dist/development/src/client/ScopeLimitedConnection.cjs +37 -0
  65. package/dist/development/src/client/ScopeLimitedConnection.cjs.map +1 -0
  66. package/dist/development/src/client/ScopeLimitedConnection.js +37 -0
  67. package/dist/development/src/client/ScopeLimitedConnection.js.map +1 -0
  68. package/dist/development/src/client/Transaction.cjs +20 -8
  69. package/dist/development/src/client/Transaction.cjs.map +1 -1
  70. package/dist/development/src/client/Transaction.js +21 -9
  71. package/dist/development/src/client/Transaction.js.map +1 -1
  72. package/dist/development/src/client/cancelRunningStatement.cjs +32 -0
  73. package/dist/development/src/client/cancelRunningStatement.cjs.map +1 -0
  74. package/dist/development/src/client/cancelRunningStatement.js +32 -0
  75. package/dist/development/src/client/cancelRunningStatement.js.map +1 -0
  76. package/dist/development/src/client/errors.cjs +6 -0
  77. package/dist/development/src/client/errors.cjs.map +1 -1
  78. package/dist/development/src/client/errors.js +6 -0
  79. package/dist/development/src/client/errors.js.map +1 -1
  80. package/dist/development/src/metadata/DatabaseMetadata.cjs.map +1 -1
  81. package/dist/development/src/metadata/DatabaseMetadata.js.map +1 -1
  82. package/dist/development/src/metadata/DatabaseMetadataResolver.cjs.map +1 -1
  83. package/dist/development/src/metadata/DatabaseMetadataResolver.js.map +1 -1
  84. package/dist/development/src/metadata/IndexMetadata.cjs.map +1 -1
  85. package/dist/development/src/metadata/IndexMetadata.js.map +1 -1
  86. package/dist/development/src/metadata/UniqueConstraintMetadata.cjs.map +1 -1
  87. package/dist/development/src/metadata/UniqueConstraintMetadata.js.map +1 -1
  88. package/dist/development/src/queryable/DatabaseQuery.cjs.map +1 -1
  89. package/dist/development/src/queryable/DatabaseQuery.js.map +1 -1
  90. package/dist/development/src/queryable/DatabaseQueryable.cjs.map +1 -1
  91. package/dist/development/src/queryable/DatabaseQueryable.js.map +1 -1
  92. package/dist/development/src/utils/ConstraintHelper.cjs.map +1 -1
  93. package/dist/development/src/utils/ConstraintHelper.js.map +1 -1
  94. package/dist/development/src/utils/Semaphore.cjs +43 -0
  95. package/dist/development/src/utils/Semaphore.cjs.map +1 -0
  96. package/dist/development/src/utils/Semaphore.js +43 -0
  97. package/dist/development/src/utils/Semaphore.js.map +1 -0
  98. package/dist/development/src/utils/createDatabaseIfNotExists.cjs.map +1 -1
  99. package/dist/development/src/utils/createDatabaseIfNotExists.js.map +1 -1
  100. package/dist/development/src/utils/listen.cjs.map +1 -1
  101. package/dist/development/src/utils/listen.js.map +1 -1
  102. package/dist/development/src/utils/pgClientFactory.cjs +9 -4
  103. package/dist/development/src/utils/pgClientFactory.cjs.map +1 -1
  104. package/dist/development/src/utils/pgClientFactory.js +9 -4
  105. package/dist/development/src/utils/pgClientFactory.js.map +1 -1
  106. package/dist/development/src/utils/retryTransaction.cjs.map +1 -1
  107. package/dist/development/src/utils/retryTransaction.js.map +1 -1
  108. package/dist/development/src/utils/sql.cjs.map +1 -1
  109. package/dist/development/src/utils/sql.js.map +1 -1
  110. package/dist/development/src/utils/withDatabaseAdvisoryLock.cjs.map +1 -1
  111. package/dist/development/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
  112. package/dist/production/index.cjs +9 -0
  113. package/dist/production/index.cjs.map +1 -1
  114. package/dist/production/index.js +10 -1
  115. package/dist/production/index.js.map +1 -1
  116. package/dist/production/src/builders/CaseStatement.cjs.map +1 -1
  117. package/dist/production/src/builders/CaseStatement.js.map +1 -1
  118. package/dist/production/src/builders/ColumnExpressionFactory.cjs.map +1 -1
  119. package/dist/production/src/builders/ColumnExpressionFactory.js.map +1 -1
  120. package/dist/production/src/builders/Compiler.cjs.map +1 -1
  121. package/dist/production/src/builders/Compiler.js.map +1 -1
  122. package/dist/production/src/builders/ConditionBuilder.cjs +6 -0
  123. package/dist/production/src/builders/ConditionBuilder.cjs.map +1 -1
  124. package/dist/production/src/builders/ConditionBuilder.js +6 -0
  125. package/dist/production/src/builders/ConditionBuilder.js.map +1 -1
  126. package/dist/production/src/builders/DeleteBuilder.cjs.map +1 -1
  127. package/dist/production/src/builders/DeleteBuilder.js.map +1 -1
  128. package/dist/production/src/builders/InsertBuilder.cjs.map +1 -1
  129. package/dist/production/src/builders/InsertBuilder.js.map +1 -1
  130. package/dist/production/src/builders/LimitByGroupWrapper.cjs +1 -1
  131. package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  132. package/dist/production/src/builders/LimitByGroupWrapper.js +1 -1
  133. package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -1
  134. package/dist/production/src/builders/SelectBuilder.cjs.map +1 -1
  135. package/dist/production/src/builders/SelectBuilder.js.map +1 -1
  136. package/dist/production/src/builders/UpdateBuilder.cjs.map +1 -1
  137. package/dist/production/src/builders/UpdateBuilder.js.map +1 -1
  138. package/dist/production/src/builders/WindowFunction.cjs +1 -1
  139. package/dist/production/src/builders/WindowFunction.cjs.map +1 -1
  140. package/dist/production/src/builders/WindowFunction.js +1 -1
  141. package/dist/production/src/builders/WindowFunction.js.map +1 -1
  142. package/dist/production/src/builders/internal/Returning.cjs.map +1 -1
  143. package/dist/production/src/builders/internal/Returning.js.map +1 -1
  144. package/dist/production/src/builders/internal/Subqueries.cjs.map +1 -1
  145. package/dist/production/src/builders/internal/Subqueries.js.map +1 -1
  146. package/dist/production/src/builders/internal/Where.cjs.map +1 -1
  147. package/dist/production/src/builders/internal/Where.js.map +1 -1
  148. package/dist/production/src/builders/internal/With.cjs.map +1 -1
  149. package/dist/production/src/builders/internal/With.js.map +1 -1
  150. package/dist/production/src/builders/utils.cjs.map +1 -1
  151. package/dist/production/src/builders/utils.js.map +1 -1
  152. package/dist/production/src/client/AcquiredConnection.cjs +105 -32
  153. package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
  154. package/dist/production/src/client/AcquiredConnection.js +107 -34
  155. package/dist/production/src/client/AcquiredConnection.js.map +1 -1
  156. package/dist/production/src/client/Client.cjs +9 -1
  157. package/dist/production/src/client/Client.cjs.map +1 -1
  158. package/dist/production/src/client/Client.js +9 -1
  159. package/dist/production/src/client/Client.js.map +1 -1
  160. package/dist/production/src/client/Connection.cjs +19 -1
  161. package/dist/production/src/client/Connection.cjs.map +1 -1
  162. package/dist/production/src/client/Connection.js +19 -1
  163. package/dist/production/src/client/Connection.js.map +1 -1
  164. package/dist/production/src/client/EventManager.cjs +6 -2
  165. package/dist/production/src/client/EventManager.cjs.map +1 -1
  166. package/dist/production/src/client/EventManager.js +6 -2
  167. package/dist/production/src/client/EventManager.js.map +1 -1
  168. package/dist/production/src/client/Pool.cjs.map +1 -1
  169. package/dist/production/src/client/Pool.js.map +1 -1
  170. package/dist/production/src/client/RequestMemoryBudget.cjs +237 -0
  171. package/dist/production/src/client/RequestMemoryBudget.cjs.map +1 -0
  172. package/dist/production/src/client/RequestMemoryBudget.js +237 -0
  173. package/dist/production/src/client/RequestMemoryBudget.js.map +1 -0
  174. package/dist/production/src/client/ScopeLimitedConnection.cjs +37 -0
  175. package/dist/production/src/client/ScopeLimitedConnection.cjs.map +1 -0
  176. package/dist/production/src/client/ScopeLimitedConnection.js +37 -0
  177. package/dist/production/src/client/ScopeLimitedConnection.js.map +1 -0
  178. package/dist/production/src/client/Transaction.cjs +20 -8
  179. package/dist/production/src/client/Transaction.cjs.map +1 -1
  180. package/dist/production/src/client/Transaction.js +21 -9
  181. package/dist/production/src/client/Transaction.js.map +1 -1
  182. package/dist/production/src/client/cancelRunningStatement.cjs +32 -0
  183. package/dist/production/src/client/cancelRunningStatement.cjs.map +1 -0
  184. package/dist/production/src/client/cancelRunningStatement.js +32 -0
  185. package/dist/production/src/client/cancelRunningStatement.js.map +1 -0
  186. package/dist/production/src/client/errors.cjs +6 -0
  187. package/dist/production/src/client/errors.cjs.map +1 -1
  188. package/dist/production/src/client/errors.js +6 -0
  189. package/dist/production/src/client/errors.js.map +1 -1
  190. package/dist/production/src/metadata/DatabaseMetadata.cjs.map +1 -1
  191. package/dist/production/src/metadata/DatabaseMetadata.js.map +1 -1
  192. package/dist/production/src/metadata/DatabaseMetadataResolver.cjs.map +1 -1
  193. package/dist/production/src/metadata/DatabaseMetadataResolver.js.map +1 -1
  194. package/dist/production/src/metadata/IndexMetadata.cjs.map +1 -1
  195. package/dist/production/src/metadata/IndexMetadata.js.map +1 -1
  196. package/dist/production/src/metadata/UniqueConstraintMetadata.cjs.map +1 -1
  197. package/dist/production/src/metadata/UniqueConstraintMetadata.js.map +1 -1
  198. package/dist/production/src/queryable/DatabaseQuery.cjs.map +1 -1
  199. package/dist/production/src/queryable/DatabaseQuery.js.map +1 -1
  200. package/dist/production/src/queryable/DatabaseQueryable.cjs.map +1 -1
  201. package/dist/production/src/queryable/DatabaseQueryable.js.map +1 -1
  202. package/dist/production/src/utils/ConstraintHelper.cjs.map +1 -1
  203. package/dist/production/src/utils/ConstraintHelper.js.map +1 -1
  204. package/dist/production/src/utils/Semaphore.cjs +43 -0
  205. package/dist/production/src/utils/Semaphore.cjs.map +1 -0
  206. package/dist/production/src/utils/Semaphore.js +43 -0
  207. package/dist/production/src/utils/Semaphore.js.map +1 -0
  208. package/dist/production/src/utils/createDatabaseIfNotExists.cjs.map +1 -1
  209. package/dist/production/src/utils/createDatabaseIfNotExists.js.map +1 -1
  210. package/dist/production/src/utils/listen.cjs.map +1 -1
  211. package/dist/production/src/utils/listen.js.map +1 -1
  212. package/dist/production/src/utils/pgClientFactory.cjs +9 -4
  213. package/dist/production/src/utils/pgClientFactory.cjs.map +1 -1
  214. package/dist/production/src/utils/pgClientFactory.js +9 -4
  215. package/dist/production/src/utils/pgClientFactory.js.map +1 -1
  216. package/dist/production/src/utils/retryTransaction.cjs.map +1 -1
  217. package/dist/production/src/utils/retryTransaction.js.map +1 -1
  218. package/dist/production/src/utils/sql.cjs.map +1 -1
  219. package/dist/production/src/utils/sql.js.map +1 -1
  220. package/dist/production/src/utils/withDatabaseAdvisoryLock.cjs.map +1 -1
  221. package/dist/production/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
  222. package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts +2 -0
  223. package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts.map +1 -0
  224. package/dist/tests/cases/unit/acquiredConnection.test.d.ts +2 -0
  225. package/dist/tests/cases/unit/acquiredConnection.test.d.ts.map +1 -0
  226. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +6 -3
  227. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
  228. package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts +2 -0
  229. package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts.map +1 -0
  230. package/dist/tests/cases/unit/scopeLimitedConnection.test.d.ts +2 -0
  231. package/dist/tests/cases/unit/scopeLimitedConnection.test.d.ts.map +1 -0
  232. package/dist/tests/cases/unit/semaphore.test.d.ts +2 -0
  233. package/dist/tests/cases/unit/semaphore.test.d.ts.map +1 -0
  234. package/dist/tests/src/tags.d.ts.map +1 -1
  235. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  236. package/dist/types/Literal.d.ts.map +1 -1
  237. package/dist/types/builders/CaseStatement.d.ts +2 -2
  238. package/dist/types/builders/CaseStatement.d.ts.map +1 -1
  239. package/dist/types/builders/ColumnExpressionFactory.d.ts +6 -6
  240. package/dist/types/builders/ColumnExpressionFactory.d.ts.map +1 -1
  241. package/dist/types/builders/Compiler.d.ts +5 -5
  242. package/dist/types/builders/Compiler.d.ts.map +1 -1
  243. package/dist/types/builders/ConditionBuilder.d.ts +8 -6
  244. package/dist/types/builders/ConditionBuilder.d.ts.map +1 -1
  245. package/dist/types/builders/DeleteBuilder.d.ts +8 -8
  246. package/dist/types/builders/DeleteBuilder.d.ts.map +1 -1
  247. package/dist/types/builders/InsertBuilder.d.ts +10 -10
  248. package/dist/types/builders/InsertBuilder.d.ts.map +1 -1
  249. package/dist/types/builders/LimitByGroupWrapper.d.ts +3 -3
  250. package/dist/types/builders/LimitByGroupWrapper.d.ts.map +1 -1
  251. package/dist/types/builders/QueryBuilder.d.ts +5 -5
  252. package/dist/types/builders/QueryBuilder.d.ts.map +1 -1
  253. package/dist/types/builders/SelectBuilder.d.ts +9 -9
  254. package/dist/types/builders/SelectBuilder.d.ts.map +1 -1
  255. package/dist/types/builders/UpdateBuilder.d.ts +9 -9
  256. package/dist/types/builders/UpdateBuilder.d.ts.map +1 -1
  257. package/dist/types/builders/WindowFunction.d.ts +4 -3
  258. package/dist/types/builders/WindowFunction.d.ts.map +1 -1
  259. package/dist/types/builders/index.d.ts +12 -12
  260. package/dist/types/builders/index.d.ts.map +1 -1
  261. package/dist/types/builders/internal/Returning.d.ts +3 -3
  262. package/dist/types/builders/internal/Returning.d.ts.map +1 -1
  263. package/dist/types/builders/internal/Subqueries.d.ts +4 -4
  264. package/dist/types/builders/internal/Subqueries.d.ts.map +1 -1
  265. package/dist/types/builders/internal/Where.d.ts +3 -3
  266. package/dist/types/builders/internal/Where.d.ts.map +1 -1
  267. package/dist/types/builders/internal/With.d.ts +3 -3
  268. package/dist/types/builders/internal/With.d.ts.map +1 -1
  269. package/dist/types/builders/utils.d.ts +2 -2
  270. package/dist/types/builders/utils.d.ts.map +1 -1
  271. package/dist/types/client/AcquiredConnection.d.ts +9 -4
  272. package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
  273. package/dist/types/client/Client.d.ts +12 -4
  274. package/dist/types/client/Client.d.ts.map +1 -1
  275. package/dist/types/client/Connection.d.ts +12 -4
  276. package/dist/types/client/Connection.d.ts.map +1 -1
  277. package/dist/types/client/EventManager.d.ts +6 -2
  278. package/dist/types/client/EventManager.d.ts.map +1 -1
  279. package/dist/types/client/PgClient.d.ts +12 -1
  280. package/dist/types/client/PgClient.d.ts.map +1 -1
  281. package/dist/types/client/Pool.d.ts +3 -3
  282. package/dist/types/client/Pool.d.ts.map +1 -1
  283. package/dist/types/client/RequestMemoryBudget.d.ts +41 -0
  284. package/dist/types/client/RequestMemoryBudget.d.ts.map +1 -0
  285. package/dist/types/client/ScopeLimitedConnection.d.ts +34 -0
  286. package/dist/types/client/ScopeLimitedConnection.d.ts.map +1 -0
  287. package/dist/types/client/Transaction.d.ts +5 -5
  288. package/dist/types/client/Transaction.d.ts.map +1 -1
  289. package/dist/types/client/cancelRunningStatement.d.ts +7 -0
  290. package/dist/types/client/cancelRunningStatement.d.ts.map +1 -0
  291. package/dist/types/client/errors.d.ts +3 -0
  292. package/dist/types/client/errors.d.ts.map +1 -1
  293. package/dist/types/client/index.d.ts +8 -7
  294. package/dist/types/client/index.d.ts.map +1 -1
  295. package/dist/types/index.d.ts +11 -10
  296. package/dist/types/index.d.ts.map +1 -1
  297. package/dist/types/metadata/DatabaseMetadata.d.ts +3 -3
  298. package/dist/types/metadata/DatabaseMetadata.d.ts.map +1 -1
  299. package/dist/types/metadata/DatabaseMetadataResolver.d.ts +2 -2
  300. package/dist/types/metadata/DatabaseMetadataResolver.d.ts.map +1 -1
  301. package/dist/types/metadata/ForeignKeyConstraintMetadata.d.ts.map +1 -1
  302. package/dist/types/metadata/IndexMetadata.d.ts.map +1 -1
  303. package/dist/types/metadata/UniqueConstraintMetadata.d.ts.map +1 -1
  304. package/dist/types/metadata/index.d.ts +5 -5
  305. package/dist/types/metadata/index.d.ts.map +1 -1
  306. package/dist/types/metadata/stringArrayEquals.d.ts.map +1 -1
  307. package/dist/types/queryable/DatabaseQuery.d.ts +1 -1
  308. package/dist/types/queryable/DatabaseQuery.d.ts.map +1 -1
  309. package/dist/types/queryable/DatabaseQueryable.d.ts +1 -1
  310. package/dist/types/queryable/DatabaseQueryable.d.ts.map +1 -1
  311. package/dist/types/queryable/index.d.ts +2 -2
  312. package/dist/types/queryable/index.d.ts.map +1 -1
  313. package/dist/types/tsconfig.tsbuildinfo +1 -1
  314. package/dist/types/types.d.ts +16 -0
  315. package/dist/types/types.d.ts.map +1 -1
  316. package/dist/types/utils/ConstraintHelper.d.ts +2 -2
  317. package/dist/types/utils/ConstraintHelper.d.ts.map +1 -1
  318. package/dist/types/utils/Mutex.d.ts.map +1 -1
  319. package/dist/types/utils/Semaphore.d.ts +17 -0
  320. package/dist/types/utils/Semaphore.d.ts.map +1 -0
  321. package/dist/types/utils/createDatabaseIfNotExists.d.ts +1 -1
  322. package/dist/types/utils/createDatabaseIfNotExists.d.ts.map +1 -1
  323. package/dist/types/utils/index.d.ts +11 -10
  324. package/dist/types/utils/index.d.ts.map +1 -1
  325. package/dist/types/utils/listen.d.ts +1 -1
  326. package/dist/types/utils/listen.d.ts.map +1 -1
  327. package/dist/types/utils/pgClientFactory.d.ts +3 -3
  328. package/dist/types/utils/pgClientFactory.d.ts.map +1 -1
  329. package/dist/types/utils/retryTransaction.d.ts.map +1 -1
  330. package/dist/types/utils/sql.d.ts +1 -1
  331. package/dist/types/utils/sql.d.ts.map +1 -1
  332. package/dist/types/utils/withDatabaseAdvisoryLock.d.ts +1 -1
  333. package/dist/types/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
  334. package/package.json +3 -3
  335. package/src/builders/CaseStatement.ts +3 -3
  336. package/src/builders/ColumnExpressionFactory.ts +7 -7
  337. package/src/builders/Compiler.ts +9 -9
  338. package/src/builders/ConditionBuilder.ts +13 -7
  339. package/src/builders/DeleteBuilder.ts +8 -8
  340. package/src/builders/InsertBuilder.ts +11 -11
  341. package/src/builders/LimitByGroupWrapper.ts +6 -6
  342. package/src/builders/QueryBuilder.ts +5 -5
  343. package/src/builders/SelectBuilder.ts +11 -11
  344. package/src/builders/UpdateBuilder.ts +10 -10
  345. package/src/builders/WindowFunction.ts +7 -6
  346. package/src/builders/index.ts +12 -12
  347. package/src/builders/internal/Returning.ts +4 -4
  348. package/src/builders/internal/Subqueries.ts +4 -4
  349. package/src/builders/internal/Where.ts +4 -4
  350. package/src/builders/internal/With.ts +4 -4
  351. package/src/builders/utils.ts +4 -4
  352. package/src/client/AcquiredConnection.ts +131 -39
  353. package/src/client/Client.ts +16 -6
  354. package/src/client/Connection.ts +27 -7
  355. package/src/client/EventManager.ts +12 -2
  356. package/src/client/PgClient.ts +16 -1
  357. package/src/client/Pool.ts +5 -5
  358. package/src/client/RequestMemoryBudget.ts +260 -0
  359. package/src/client/ScopeLimitedConnection.ts +65 -0
  360. package/src/client/Transaction.ts +24 -11
  361. package/src/client/cancelRunningStatement.ts +36 -0
  362. package/src/client/errors.ts +6 -0
  363. package/src/client/index.ts +8 -7
  364. package/src/index.ts +12 -10
  365. package/src/metadata/DatabaseMetadata.ts +3 -3
  366. package/src/metadata/DatabaseMetadataResolver.ts +5 -5
  367. package/src/metadata/IndexMetadata.ts +1 -1
  368. package/src/metadata/UniqueConstraintMetadata.ts +1 -1
  369. package/src/metadata/index.ts +5 -5
  370. package/src/queryable/DatabaseQuery.ts +2 -2
  371. package/src/queryable/DatabaseQueryable.ts +1 -1
  372. package/src/queryable/index.ts +2 -2
  373. package/src/types.ts +16 -0
  374. package/src/utils/ConstraintHelper.ts +3 -3
  375. package/src/utils/Semaphore.ts +49 -0
  376. package/src/utils/createDatabaseIfNotExists.ts +3 -3
  377. package/src/utils/index.ts +11 -10
  378. package/src/utils/listen.ts +2 -2
  379. package/src/utils/pgClientFactory.ts +18 -10
  380. package/src/utils/retryTransaction.ts +1 -1
  381. package/src/utils/sql.ts +1 -1
  382. package/src/utils/withDatabaseAdvisoryLock.ts +1 -1
  383. package/tests/cases/integration/requestMemoryBudget.test.ts +296 -0
  384. package/tests/cases/unit/acquiredConnection.test.ts +154 -0
  385. package/tests/cases/unit/connection.test.ts +34 -2
  386. package/tests/cases/unit/createConnectionMockAlt.ts +18 -4
  387. package/tests/cases/unit/eventManager.test.ts +2 -2
  388. package/tests/cases/unit/pool.test.ts +1 -1
  389. package/tests/cases/unit/queryBuilder.test.ts +29 -4
  390. package/tests/cases/unit/requestMemoryBudget.test.ts +287 -0
  391. package/tests/cases/unit/scopeLimitedConnection.test.ts +204 -0
  392. package/tests/cases/unit/semaphore.test.ts +53 -0
@@ -1,9 +1,10 @@
1
- import { DeleteBuilder, InsertBuilder, SelectBuilder, UpdateBuilder } from '../builders'
2
- import { DatabaseQueryable } from '../queryable'
3
- import { Connection } from './Connection'
4
- import { EventManager } from './EventManager'
1
+ import { DeleteBuilder, InsertBuilder, SelectBuilder, UpdateBuilder } from '../builders/index.js'
2
+ import { DatabaseQueryable } from '../queryable/index.js'
3
+ import { Connection } from './Connection.js'
4
+ import { EventManager } from './EventManager.js'
5
5
  import { QueryHandler } from '@contember/queryable'
6
- import { withDatabaseAdvisoryLock, wrapIdentifier } from '../utils'
6
+ import { withDatabaseAdvisoryLock, wrapIdentifier } from '../utils/index.js'
7
+ import { RequestMemoryBudget } from './RequestMemoryBudget.js'
7
8
 
8
9
  class Client<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> implements Connection.Queryable {
9
10
  constructor(
@@ -15,10 +16,18 @@ class Client<ConnectionType extends Connection.ConnectionLike = Connection.Conne
15
16
  }
16
17
 
17
18
  public forSchema(schema: string): Client<ConnectionType> {
18
- const eventManager = new EventManager(this.eventManager.parent)
19
+ const eventManager = new EventManager(this.eventManager.parent, this.eventManager.memoryBudget, this.eventManager.chargesMemoryBudget)
19
20
  return new Client<ConnectionType>(this.connection, schema, this.queryMeta, eventManager)
20
21
  }
21
22
 
23
+ /**
24
+ * Binds the request memory budget: every query of the returned client is refused once the budget is exhausted.
25
+ * With `chargeRows`, the rows the client fetches are also accounted against the budget.
26
+ */
27
+ public withMemoryBudget(memoryBudget: RequestMemoryBudget, { chargeRows = true }: { chargeRows?: boolean } = {}): Client<ConnectionType> {
28
+ return new Client(this.connection, this.schema, this.queryMeta, new EventManager(this.eventManager, memoryBudget, chargeRows))
29
+ }
30
+
22
31
  async scope<T>(callback: (wrapper: Client<ConnectionType & Connection.AcquiredConnectionLike>) => Promise<T> | T): Promise<T> {
23
32
  return await this.connection.scope(
24
33
  connection =>
@@ -74,6 +83,7 @@ class Client<ConnectionType extends Connection.ConnectionLike = Connection.Conne
74
83
  parameters: readonly any[] = [],
75
84
  meta: Record<string, any> = {},
76
85
  ): Promise<Connection.Result<Row>> {
86
+ this.eventManager.memoryBudget?.check()
77
87
  return this.connection.scope(
78
88
  connection => connection.query(sql, parameters, { ...this.queryMeta, ...meta }),
79
89
  { eventManager: this.eventManager },
@@ -1,9 +1,10 @@
1
- import { EventManager } from './EventManager'
2
- import { Client } from './Client'
3
- import { Pool, PoolConfig, PoolStatus } from './Pool'
4
- import { createPgClientFactory } from '../utils'
5
- import { DatabaseConfig } from '../types'
6
- import { AcquiredConnection } from './AcquiredConnection'
1
+ import { EventManager } from './EventManager.js'
2
+ import { Client } from './Client.js'
3
+ import { Pool, PoolConfig, PoolStatus } from './Pool.js'
4
+ import { createPgClientFactory } from '../utils/index.js'
5
+ import { DatabaseConfig } from '../types.js'
6
+ import { AcquiredConnection } from './AcquiredConnection.js'
7
+ import { ScopeLimitedConnection } from './ScopeLimitedConnection.js'
7
8
  import { Notification } from 'pg'
8
9
 
9
10
  class Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {
@@ -31,12 +32,31 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
31
32
  return new Client(this, schema, queryMeta, new EventManager(this.eventManager))
32
33
  }
33
34
 
35
+ /**
36
+ * Returns a view of this connection that limits how many pool connections may be
37
+ * acquired concurrently through it. Intended to be created per HTTP request so that
38
+ * a single request cannot starve the shared pool. The returned view shares the same
39
+ * underlying pool; only top-level scopes are counted (nested scopes reuse the already
40
+ * acquired connection), so the limit must be at least 1.
41
+ */
42
+ public withMaxConnections(maxConnections: number): Connection.ConnectionType {
43
+ return new ScopeLimitedConnection(this, maxConnections)
44
+ }
45
+
34
46
  async scope<Result>(
35
47
  callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
36
48
  options: { eventManager?: EventManager } = {},
37
49
  ): Promise<Result> {
38
- const acquired = await this.pool.acquire()
39
50
  const eventManager = new EventManager(options.eventManager ?? this.eventManager)
51
+ eventManager.memoryBudget?.check()
52
+ const acquired = await this.pool.acquire()
53
+ // A budget exhausted while waiting for the pool must not cost a healthy connection.
54
+ try {
55
+ eventManager.memoryBudget?.check()
56
+ } catch (e) {
57
+ this.pool.release(acquired)
58
+ throw e
59
+ }
40
60
  try {
41
61
  const connection = new AcquiredConnection(acquired.client, eventManager)
42
62
  const result = await callback(connection)
@@ -1,6 +1,11 @@
1
- import { Connection } from './Connection'
1
+ import { Connection } from './Connection.js'
2
+ import { RequestMemoryBudget } from './RequestMemoryBudget.js'
2
3
 
3
4
  class EventManager {
5
+ /** Every query bound to a budget is refused once it is exhausted; only queries that also charge it account their rows. */
6
+ public readonly memoryBudget: RequestMemoryBudget | undefined
7
+ public readonly chargesMemoryBudget: boolean
8
+
4
9
  private readonly listeners = {
5
10
  [EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],
6
11
  [EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],
@@ -9,7 +14,12 @@ class EventManager {
9
14
 
10
15
  constructor(
11
16
  public readonly parent: EventManager | null = null,
12
- ) {}
17
+ memoryBudget: RequestMemoryBudget | null | undefined = parent?.memoryBudget,
18
+ chargesMemoryBudget: boolean = parent?.chargesMemoryBudget ?? false,
19
+ ) {
20
+ this.memoryBudget = memoryBudget ?? undefined
21
+ this.chargesMemoryBudget = this.memoryBudget !== undefined && chargesMemoryBudget
22
+ }
13
23
 
14
24
  on<Event extends keyof EventManager.ListenerTypes>(event: Event, cb: EventManager.ListenerTypes[Event]): void {
15
25
  ;(this.listeners[event] as EventManager.ListenerTypes[Event][]).push(cb)
@@ -1,8 +1,23 @@
1
- import { Notification, QueryConfig, QueryResult, QueryResultRow } from 'pg'
1
+ import { Notification, QueryConfig, QueryResult, QueryResultRow, Submittable } from 'pg'
2
+
3
+ declare module 'pg' {
4
+ interface Client {
5
+ // Set by pg from the server's BackendKeyData message once connected; missing from @types/pg.
6
+ readonly processID: number | null
7
+ readonly secretKey: number | null
8
+ }
9
+ }
2
10
 
3
11
  export interface PgClient {
12
+ readonly host: string
13
+ readonly port: number
14
+ readonly processID: number | null
15
+ readonly secretKey: number | null
16
+
4
17
  connect(): Promise<void>
5
18
 
19
+ query<T extends Submittable>(query: T): T
20
+
6
21
  query<R extends QueryResultRow = any, I extends any[] = any[]>(
7
22
  queryTextOrConfig: string | QueryConfig<I>,
8
23
  values?: I,
@@ -1,9 +1,9 @@
1
- import { ImplementationException } from '../exceptions'
2
- import { ClientErrorCodes } from './errorCodes'
1
+ import { ImplementationException } from '../exceptions.js'
2
+ import { ClientErrorCodes } from './errorCodes.js'
3
3
  import { EventEmitter } from 'node:events'
4
- import { ClientError, DatabaseError } from './errors'
5
- import { PgClientFactory } from '../utils'
6
- import { PgClient } from './PgClient'
4
+ import { ClientError, DatabaseError } from './errors.js'
5
+ import { PgClientFactory } from '../utils/index.js'
6
+ import { PgClient } from './PgClient.js'
7
7
 
8
8
  export type PoolLogger = (message: string, status: PoolStatus) => void
9
9
 
@@ -0,0 +1,260 @@
1
+ import { Buffer } from 'node:buffer'
2
+
3
+ export interface RequestMemoryBudgetOptions {
4
+ warnBytes: number
5
+ maxBytes: number
6
+ }
7
+
8
+ const rowCompletionOverheadBytes = 256
9
+ const maximumRecursiveEstimateDepth = 64
10
+ const isBun = process.versions.bun !== undefined
11
+
12
+ export const validateRequestMemoryBudgetOptions = ({ warnBytes, maxBytes }: RequestMemoryBudgetOptions): string | undefined => {
13
+ if (!Number.isSafeInteger(warnBytes) || warnBytes <= 0) {
14
+ return 'warnBytes must be a positive safe integer'
15
+ }
16
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
17
+ return 'maxBytes must be a positive safe integer'
18
+ }
19
+ if (warnBytes > maxBytes) {
20
+ return 'warnBytes must not exceed maxBytes'
21
+ }
22
+ return undefined
23
+ }
24
+
25
+ export class RequestMemoryBudgetExceededError extends Error {
26
+ constructor() {
27
+ super('Request memory budget exceeded')
28
+ this.name = 'RequestMemoryBudgetExceededError'
29
+ }
30
+ }
31
+
32
+ export class RequestMemoryBudget {
33
+ private databaseBytes = 0
34
+ private hydrationBytes = 0
35
+ private peakBytes = 0
36
+ private databaseRows = 0
37
+ private largestDatabaseRowBytes = 0
38
+ private readonly databaseStrings = new StringMemoryEstimate()
39
+ private failure: RequestMemoryBudgetExceededError | undefined
40
+ // A plain set rather than an AbortSignal: every in-flight query of the request listens, and Node 20 warns above ten signal listeners.
41
+ private readonly exceededListeners = new Set<(failure: RequestMemoryBudgetExceededError) => void>()
42
+
43
+ constructor(private readonly options: RequestMemoryBudgetOptions) {
44
+ const optionsError = validateRequestMemoryBudgetOptions(options)
45
+ if (optionsError) {
46
+ throw new Error(`Invalid request memory budget: ${optionsError}`)
47
+ }
48
+ }
49
+
50
+ get exceeded(): boolean {
51
+ return this.failure !== undefined
52
+ }
53
+
54
+ check(): void {
55
+ if (this.failure) {
56
+ throw this.failure
57
+ }
58
+ }
59
+
60
+ /** Calls the listener once the budget is exceeded, immediately when it already is. Returns the unsubscribe. */
61
+ onExceeded(listener: (failure: RequestMemoryBudgetExceededError) => void): () => void {
62
+ if (this.failure) {
63
+ listener(this.failure)
64
+ return () => {}
65
+ }
66
+ this.exceededListeners.add(listener)
67
+ return () => this.exceededListeners.delete(listener)
68
+ }
69
+
70
+ addDatabaseRow(row: Record<string, unknown>): void {
71
+ this.check()
72
+ this.databaseRows++
73
+ let rowBytes = 40
74
+ for (const key in row) {
75
+ if (Object.prototype.hasOwnProperty.call(row, key)) {
76
+ rowBytes += 16 + estimateValueBytes(row[key], this.databaseStrings)
77
+ }
78
+ }
79
+ this.databaseBytes += rowBytes
80
+ this.largestDatabaseRowBytes = Math.max(this.largestDatabaseRowBytes, rowBytes)
81
+ this.update()
82
+ }
83
+
84
+ addHydrationBytes(bytes: number): void {
85
+ this.check()
86
+ this.hydrationBytes += bytes
87
+ this.update()
88
+ }
89
+
90
+ snapshot() {
91
+ return {
92
+ estimatedRetainedBytes: this.databaseBytes + this.hydrationBytes,
93
+ reservedCompletionBytes: this.getCompletionBytes(),
94
+ estimatedPeakBytes: this.peakBytes,
95
+ databaseRows: this.databaseRows,
96
+ databaseBytes: this.databaseBytes,
97
+ hydrationBytes: this.hydrationBytes,
98
+ warnBytes: this.options.warnBytes,
99
+ maxBytes: this.options.maxBytes,
100
+ warningThresholdExceeded: this.peakBytes > this.options.warnBytes,
101
+ maxBytesExceeded: this.peakBytes > this.options.maxBytes,
102
+ }
103
+ }
104
+
105
+ private getCompletionBytes(): number {
106
+ // GraphQL shares scalar strings with DB results; completion allocates structures and serialized text.
107
+ const projectedCompletionBytes = (this.databaseBytes - this.databaseStrings.retainedBytes) * 2
108
+ + this.databaseStrings.serializedBytes + this.hydrationBytes
109
+ // Decoding a row and serializing the response happen in different phases.
110
+ // JSC includes pg's growing buffers in its heap account; V8 reports them as external memory.
111
+ const decodingBytes = this.largestDatabaseRowBytes * (isBun ? 3 : 1)
112
+ return Math.max(projectedCompletionBytes, decodingBytes)
113
+ + this.databaseRows * rowCompletionOverheadBytes
114
+ }
115
+
116
+ private update(): void {
117
+ const estimatedBytes = this.databaseBytes + this.hydrationBytes + this.getCompletionBytes()
118
+ this.peakBytes = Math.max(this.peakBytes, estimatedBytes)
119
+ if (estimatedBytes > this.options.maxBytes) {
120
+ const failure = new RequestMemoryBudgetExceededError()
121
+ this.failure = failure
122
+ const listeners = [...this.exceededListeners]
123
+ this.exceededListeners.clear()
124
+ listeners.forEach(listener => listener(failure))
125
+ throw failure
126
+ }
127
+ }
128
+ }
129
+
130
+ function estimateValueBytes(value: unknown, strings: StringMemoryEstimate): number {
131
+ return estimateScalarBytes(value, strings) ?? estimateStructuredValueBytes(value, strings, 0)
132
+ }
133
+
134
+ function estimateStructuredValueBytes(value: unknown, strings: StringMemoryEstimate, depth: number): number {
135
+ if (depth >= maximumRecursiveEstimateDepth) {
136
+ return estimateDeepValueBytes(value, strings)
137
+ }
138
+ if (Array.isArray(value)) {
139
+ let bytes = 32 + value.length * 8
140
+ for (let i = 0; i < value.length; i++) {
141
+ const item: unknown = value[i]
142
+ const scalarBytes = estimateScalarBytes(item, strings)
143
+ bytes += scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1)
144
+ }
145
+ return bytes
146
+ }
147
+ let bytes = 32
148
+ if (value !== null && typeof value === 'object') {
149
+ for (const key in value) {
150
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
151
+ const item: unknown = Reflect.get(value, key)
152
+ const scalarBytes = estimateScalarBytes(item, strings)
153
+ strings.addPropertyName(key)
154
+ bytes += 16 + (scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1))
155
+ }
156
+ }
157
+ }
158
+ return bytes
159
+ }
160
+
161
+ function estimateDeepValueBytes(value: unknown, strings: StringMemoryEstimate): number {
162
+ const scalarBytes = estimateScalarBytes(value, strings)
163
+ if (scalarBytes !== undefined) {
164
+ return scalarBytes
165
+ }
166
+ let bytes = 0
167
+ const pending: Iterator<unknown>[] = [[value].values()]
168
+ while (pending.length > 0) {
169
+ const next = pending[pending.length - 1].next()
170
+ if (next.done) {
171
+ pending.pop()
172
+ continue
173
+ }
174
+ const current: unknown = next.value
175
+ const scalarBytes = estimateScalarBytes(current, strings)
176
+ if (scalarBytes !== undefined) {
177
+ bytes += scalarBytes
178
+ } else if (Array.isArray(current)) {
179
+ bytes += 32 + current.length * 8
180
+ pending.push(current.values())
181
+ } else if (current !== null && typeof current === 'object') {
182
+ bytes += 32
183
+ let hasNestedValues = false
184
+ for (const key in current) {
185
+ if (!Object.prototype.hasOwnProperty.call(current, key)) {
186
+ continue
187
+ }
188
+ strings.addPropertyName(key)
189
+ bytes += 16
190
+ const scalarBytes = estimateScalarBytes(Reflect.get(current, key), strings)
191
+ if (scalarBytes === undefined) {
192
+ hasNestedValues = true
193
+ } else {
194
+ bytes += scalarBytes
195
+ }
196
+ }
197
+ if (hasNestedValues) {
198
+ pending.push(nestedValues(current))
199
+ }
200
+ }
201
+ }
202
+ return bytes
203
+
204
+ function* nestedValues(object: object): Generator<unknown> {
205
+ for (const key in object) {
206
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
207
+ const value: unknown = Reflect.get(object, key)
208
+ if (value !== null && typeof value === 'object' && !(value instanceof Date) && !ArrayBuffer.isView(value)) {
209
+ yield value
210
+ }
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ function estimateScalarBytes(value: unknown, strings: StringMemoryEstimate): number | undefined {
217
+ if (typeof value === 'string') {
218
+ return 24 + strings.add(value)
219
+ }
220
+ if (value === null || typeof value !== 'object') {
221
+ return 8
222
+ }
223
+ if (value instanceof Date) {
224
+ return 40
225
+ }
226
+ if (ArrayBuffer.isView(value)) {
227
+ return 64 + value.byteLength
228
+ }
229
+ return undefined
230
+ }
231
+
232
+ class StringMemoryEstimate {
233
+ private codeUnits = 0
234
+ private storageBytes = 0
235
+ private nonAscii = false
236
+
237
+ get retainedBytes(): number {
238
+ return this.storageBytes
239
+ }
240
+
241
+ get serializedBytes(): number {
242
+ // One non-ASCII string can promote the entire serialized JSON string to two-byte storage.
243
+ return this.codeUnits * (this.nonAscii ? 2 : 1)
244
+ }
245
+
246
+ add(value: string): number {
247
+ // A native length comparison avoids a JavaScript character loop and RegExp.input, which can retain a request string.
248
+ const ascii = Buffer.byteLength(value) === value.length
249
+ this.nonAscii ||= !ascii
250
+ this.codeUnits += value.length
251
+ const bytes = ascii ? value.length : value.length * 2
252
+ this.storageBytes += bytes
253
+ return bytes
254
+ }
255
+
256
+ // Runtimes share property names between objects of one shape; only their serialized copies are new.
257
+ addPropertyName(key: string): void {
258
+ this.codeUnits += key.length
259
+ }
260
+ }
@@ -0,0 +1,65 @@
1
+ import { Connection } from './Connection.js'
2
+ import { EventManager } from './EventManager.js'
3
+ import { Client } from './Client.js'
4
+ import { PoolStatus } from './Pool.js'
5
+ import { Semaphore } from '../utils/Semaphore.js'
6
+
7
+ /**
8
+ * Wraps a {@link Connection} and limits the number of pool connections that may be
9
+ * acquired concurrently through it.
10
+ *
11
+ * Every top-level {@link Connection.scope} call (and therefore every {@link query} and
12
+ * {@link transaction}) acquires exactly one pool connection. By routing those calls
13
+ * through a {@link Semaphore} we cap how many connections a single owner of this
14
+ * instance (typically a single HTTP request) can hold at once, preventing one request
15
+ * from starving the shared pool under high concurrency.
16
+ *
17
+ * Nested scopes/transactions reuse the already-acquired connection (they go through
18
+ * `AcquiredConnection`, not back to the underlying `Connection`), so they are not
19
+ * counted again and cannot deadlock against the limit.
20
+ */
21
+ export class ScopeLimitedConnection implements Connection.ConnectionType {
22
+ private readonly semaphore: Semaphore
23
+
24
+ constructor(
25
+ private readonly inner: Connection.ConnectionType,
26
+ maxConnections: number,
27
+ public readonly eventManager: EventManager = inner.eventManager,
28
+ ) {
29
+ this.semaphore = new Semaphore(maxConnections)
30
+ }
31
+
32
+ createClient(schema: string, queryMeta: Record<string, any>): Client {
33
+ return new Client(this, schema, queryMeta, new EventManager(this.eventManager))
34
+ }
35
+
36
+ async scope<Result>(
37
+ callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
38
+ options: { eventManager?: EventManager } = {},
39
+ ): Promise<Result> {
40
+ return await this.semaphore.execute(() => this.inner.scope(callback, options))
41
+ }
42
+
43
+ async transaction<Result>(
44
+ callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
45
+ options: { eventManager?: EventManager } = {},
46
+ ): Promise<Result> {
47
+ return await this.scope(async connection => {
48
+ return await connection.transaction(callback)
49
+ }, options)
50
+ }
51
+
52
+ async query<Row extends Record<string, any>>(
53
+ sql: string,
54
+ parameters: any[] = [],
55
+ meta: Record<string, any> = {},
56
+ ): Promise<Connection.Result<Row>> {
57
+ return await this.scope(async connection => {
58
+ return await connection.query(sql, parameters, meta)
59
+ })
60
+ }
61
+
62
+ getPoolStatus(): PoolStatus | undefined {
63
+ return this.inner.getPoolStatus()
64
+ }
65
+ }
@@ -1,8 +1,8 @@
1
- import { Connection } from './Connection'
2
- import { EventManager } from './EventManager'
3
- import { wrapIdentifier } from '../utils'
1
+ import { Connection } from './Connection.js'
2
+ import { EventManager } from './EventManager.js'
3
+ import { wrapIdentifier } from '../utils/index.js'
4
4
  import { Notification } from 'pg'
5
- import { CannotCommitError, DatabaseError } from './errors'
5
+ import { CannotCommitError, DatabaseError, TerminatedConnectionError } from './errors.js'
6
6
 
7
7
  export class Transaction implements Connection.TransactionLike {
8
8
  public get isClosed(): boolean {
@@ -55,7 +55,7 @@ export class Transaction implements Connection.TransactionLike {
55
55
  }
56
56
 
57
57
  async rollback(): Promise<void> {
58
- await this.close('ROLLBACK')
58
+ await this.close('ROLLBACK', new EventManager(this.eventManager, null))
59
59
  }
60
60
 
61
61
  async commit(): Promise<void> {
@@ -65,8 +65,11 @@ export class Transaction implements Connection.TransactionLike {
65
65
  }
66
66
  }
67
67
 
68
- private async close(command: string) {
69
- const result = await this.query(command)
68
+ private async close(command: string, eventManager = this.eventManager) {
69
+ if (this.isClosed) {
70
+ throw new Error('Transaction is already closed')
71
+ }
72
+ const result = await this.scope(connection => connection.query(command), { eventManager })
70
73
  this.state.close()
71
74
  return result
72
75
  }
@@ -124,15 +127,18 @@ class SavePoint implements Connection.TransactionLike {
124
127
  }
125
128
 
126
129
  async rollback(): Promise<void> {
127
- await this.close(`ROLLBACK TO SAVEPOINT ${wrapIdentifier(this.savepointName)}`)
130
+ await this.close(`ROLLBACK TO SAVEPOINT ${wrapIdentifier(this.savepointName)}`, new EventManager(this.eventManager, null))
128
131
  }
129
132
 
130
133
  async commit(): Promise<void> {
131
134
  await this.close(`RELEASE SAVEPOINT ${wrapIdentifier(this.savepointName)}`)
132
135
  }
133
136
 
134
- private async close(sql: string) {
135
- await this.query(sql)
137
+ private async close(sql: string, eventManager = this.eventManager) {
138
+ if (this.isClosed) {
139
+ throw new Error(`Savepoint ${this.savepointName} is already closed.`)
140
+ }
141
+ await this.scope(connection => connection.query(sql), { eventManager })
136
142
  this.state.close()
137
143
  }
138
144
  }
@@ -176,7 +182,14 @@ export const executeTransaction = async <Result>(
176
182
  return result
177
183
  } catch (e) {
178
184
  if (!transaction.isClosed) {
179
- await transaction.rollback()
185
+ try {
186
+ await transaction.rollback()
187
+ } catch (rollbackError) {
188
+ // PostgreSQL already rolled back the transaction of a terminated connection, whatever terminated it.
189
+ if (!(rollbackError instanceof TerminatedConnectionError)) {
190
+ throw rollbackError
191
+ }
192
+ }
180
193
  }
181
194
  throw e
182
195
  }
@@ -0,0 +1,36 @@
1
+ import { connect } from 'node:net'
2
+ import { PgClient } from './PgClient.js'
3
+
4
+ const CANCEL_REQUEST_CODE = 80877102
5
+ const CANCEL_REQUEST_TIMEOUT_MS = 5000
6
+
7
+ /**
8
+ * Asks the server to cancel the statement the client is running, with a protocol CancelRequest on a separate socket.
9
+ * Closing the client's own socket does not stop a statement that has not sent a row yet.
10
+ */
11
+ export const cancelRunningStatement = async ({ host, port, processID, secretKey }: PgClient): Promise<void> => {
12
+ if (processID === null || secretKey === null) {
13
+ return
14
+ }
15
+ const message = Buffer.alloc(16)
16
+ message.writeInt32BE(16, 0)
17
+ message.writeInt32BE(CANCEL_REQUEST_CODE, 4)
18
+ message.writeInt32BE(processID, 8)
19
+ message.writeInt32BE(secretKey, 12)
20
+
21
+ const socket = host.startsWith('/') ? connect(`${host}/.s.PGSQL.${port}`) : connect(port, host)
22
+ await new Promise<void>((resolve, reject) => {
23
+ socket.setTimeout(CANCEL_REQUEST_TIMEOUT_MS, () => {
24
+ socket.destroy(new Error(`PostgreSQL cancel request timed out after ${CANCEL_REQUEST_TIMEOUT_MS} ms`))
25
+ })
26
+ socket.once('error', reject)
27
+ socket.once('close', hadError => {
28
+ if (!hadError) {
29
+ resolve()
30
+ }
31
+ })
32
+ socket.once('connect', () => {
33
+ socket.end(message)
34
+ })
35
+ })
36
+ }
@@ -56,3 +56,9 @@ export class InvalidDataError extends QueryError {}
56
56
  export class TransactionAbortedError extends QueryError {}
57
57
 
58
58
  export class CannotCommitError extends DatabaseError {}
59
+
60
+ export class TerminatedConnectionError extends DatabaseError {
61
+ constructor() {
62
+ super('Database connection was terminated')
63
+ }
64
+ }
@@ -1,7 +1,8 @@
1
- export * from './Client'
2
- export * from './errorCodes'
3
- export * from './errors'
4
- export * from './Connection'
5
- export * from './EventManager'
6
- export * from './Pool'
7
- export * from './Transaction'
1
+ export * from './Client.js'
2
+ export * from './errorCodes.js'
3
+ export * from './errors.js'
4
+ export * from './Connection.js'
5
+ export * from './ScopeLimitedConnection.js'
6
+ export * from './EventManager.js'
7
+ export * from './Pool.js'
8
+ export * from './Transaction.js'
package/src/index.ts CHANGED
@@ -1,17 +1,17 @@
1
- import { With } from './builders/internal/With'
2
- import { Where } from './builders/internal/Where'
3
- import { Returning } from './builders/internal/Returning'
1
+ import { With } from './builders/internal/With.js'
2
+ import { Where } from './builders/internal/Where.js'
3
+ import { Returning } from './builders/internal/Returning.js'
4
4
 
5
5
  export type WithAware = With.Aware
6
6
  export type WhereAware = Where.Aware
7
7
  export type ReturningAware = Returning.Aware
8
8
 
9
- export * from './client'
10
- export * from './builders'
11
- export * from './metadata'
12
- export * from './queryable'
13
- export * from './Literal'
14
- export * from './types'
9
+ export * from './client/index.js'
10
+ export * from './builders/index.js'
11
+ export * from './metadata/index.js'
12
+ export * from './queryable/index.js'
13
+ export * from './Literal.js'
14
+ export * from './types.js'
15
15
  export {
16
16
  AcquiringListener,
17
17
  asyncIterableTransaction,
@@ -21,6 +21,8 @@ export {
21
21
  formatColumnIdentifier,
22
22
  Listener,
23
23
  retryTransaction,
24
+ Semaphore,
24
25
  withDatabaseAdvisoryLock,
25
26
  wrapIdentifier,
26
- } from './utils'
27
+ } from './utils/index.js'
28
+ export * from './client/RequestMemoryBudget.js'
@@ -1,6 +1,6 @@
1
- import { UniqueConstraintMetadata, UniqueConstraintMetadataSet } from './UniqueConstraintMetadata'
2
- import { ForeignKeyConstraintMetadata, ForeignKeyConstraintMetadataSet } from './ForeignKeyConstraintMetadata'
3
- import { IndexMetadata, IndexMetadataSet } from './IndexMetadata'
1
+ import { UniqueConstraintMetadata, UniqueConstraintMetadataSet } from './UniqueConstraintMetadata.js'
2
+ import { ForeignKeyConstraintMetadata, ForeignKeyConstraintMetadataSet } from './ForeignKeyConstraintMetadata.js'
3
+ import { IndexMetadata, IndexMetadataSet } from './IndexMetadata.js'
4
4
 
5
5
  export interface DatabaseMetadata {
6
6
  uniqueConstraints: UniqueConstraintMetadataSet