@contember/database 2.1.0-alpha.37 → 2.1.0-alpha.39

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 (491) hide show
  1. package/dist/development/index.cjs +104 -0
  2. package/dist/development/index.cjs.map +1 -0
  3. package/dist/development/index.js +92 -0
  4. package/dist/development/index.js.map +1 -0
  5. package/dist/development/src/Literal.cjs +37 -0
  6. package/dist/development/src/Literal.cjs.map +1 -0
  7. package/dist/development/src/Literal.js +37 -0
  8. package/dist/development/src/Literal.js.map +1 -0
  9. package/dist/development/src/builders/CaseStatement.cjs +47 -0
  10. package/dist/development/src/builders/CaseStatement.cjs.map +1 -0
  11. package/dist/development/src/builders/CaseStatement.js +47 -0
  12. package/dist/development/src/builders/CaseStatement.js.map +1 -0
  13. package/dist/development/src/builders/ColumnExpressionFactory.cjs +41 -0
  14. package/dist/development/src/builders/ColumnExpressionFactory.cjs.map +1 -0
  15. package/dist/development/src/builders/ColumnExpressionFactory.js +41 -0
  16. package/dist/development/src/builders/ColumnExpressionFactory.js.map +1 -0
  17. package/dist/development/src/builders/Compiler.cjs +219 -0
  18. package/dist/development/src/builders/Compiler.cjs.map +1 -0
  19. package/dist/development/src/builders/Compiler.js +219 -0
  20. package/dist/development/src/builders/Compiler.js.map +1 -0
  21. package/dist/development/src/builders/ConditionBuilder.cjs +167 -0
  22. package/dist/development/src/builders/ConditionBuilder.cjs.map +1 -0
  23. package/dist/development/src/builders/ConditionBuilder.js +167 -0
  24. package/dist/development/src/builders/ConditionBuilder.js.map +1 -0
  25. package/dist/development/src/builders/ConflictActionType.cjs +9 -0
  26. package/dist/development/src/builders/ConflictActionType.cjs.map +1 -0
  27. package/dist/development/src/builders/ConflictActionType.js +9 -0
  28. package/dist/development/src/builders/ConflictActionType.js.map +1 -0
  29. package/dist/development/src/builders/DeleteBuilder.cjs +54 -0
  30. package/dist/development/src/builders/DeleteBuilder.cjs.map +1 -0
  31. package/dist/development/src/builders/DeleteBuilder.js +54 -0
  32. package/dist/development/src/builders/DeleteBuilder.js.map +1 -0
  33. package/dist/development/src/builders/InsertBuilder.cjs +106 -0
  34. package/dist/development/src/builders/InsertBuilder.cjs.map +1 -0
  35. package/dist/development/src/builders/InsertBuilder.js +106 -0
  36. package/dist/development/src/builders/InsertBuilder.js.map +1 -0
  37. package/dist/development/src/builders/LimitByGroupWrapper.cjs +37 -0
  38. package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -0
  39. package/dist/development/src/builders/LimitByGroupWrapper.js +37 -0
  40. package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -0
  41. package/dist/development/src/builders/LockType.cjs +17 -0
  42. package/dist/development/src/builders/LockType.cjs.map +1 -0
  43. package/dist/development/src/builders/LockType.js +17 -0
  44. package/dist/development/src/builders/LockType.js.map +1 -0
  45. package/dist/development/src/builders/SelectBuilder.cjs +149 -0
  46. package/dist/development/src/builders/SelectBuilder.cjs.map +1 -0
  47. package/dist/development/src/builders/SelectBuilder.js +149 -0
  48. package/dist/development/src/builders/SelectBuilder.js.map +1 -0
  49. package/dist/development/src/builders/UpdateBuilder.cjs +82 -0
  50. package/dist/development/src/builders/UpdateBuilder.cjs.map +1 -0
  51. package/dist/development/src/builders/UpdateBuilder.js +82 -0
  52. package/dist/development/src/builders/UpdateBuilder.js.map +1 -0
  53. package/dist/development/src/builders/WindowFunction.cjs +60 -0
  54. package/dist/development/src/builders/WindowFunction.cjs.map +1 -0
  55. package/dist/development/src/builders/WindowFunction.js +60 -0
  56. package/dist/development/src/builders/WindowFunction.js.map +1 -0
  57. package/dist/development/src/builders/internal/Returning.cjs +34 -0
  58. package/dist/development/src/builders/internal/Returning.cjs.map +1 -0
  59. package/dist/development/src/builders/internal/Returning.js +34 -0
  60. package/dist/development/src/builders/internal/Returning.js.map +1 -0
  61. package/dist/development/src/builders/internal/Subqueries.cjs +15 -0
  62. package/dist/development/src/builders/internal/Subqueries.cjs.map +1 -0
  63. package/dist/development/src/builders/internal/Subqueries.js +15 -0
  64. package/dist/development/src/builders/internal/Subqueries.js.map +1 -0
  65. package/dist/development/src/builders/internal/Where.cjs +53 -0
  66. package/dist/development/src/builders/internal/Where.cjs.map +1 -0
  67. package/dist/development/src/builders/internal/Where.js +54 -0
  68. package/dist/development/src/builders/internal/Where.js.map +1 -0
  69. package/dist/development/src/builders/internal/With.cjs +52 -0
  70. package/dist/development/src/builders/internal/With.cjs.map +1 -0
  71. package/dist/development/src/builders/internal/With.js +53 -0
  72. package/dist/development/src/builders/internal/With.js.map +1 -0
  73. package/dist/development/src/builders/utils.cjs +35 -0
  74. package/dist/development/src/builders/utils.cjs.map +1 -0
  75. package/dist/development/src/builders/utils.js +35 -0
  76. package/dist/development/src/builders/utils.js.map +1 -0
  77. package/dist/development/src/client/AcquiredConnection.cjs +91 -0
  78. package/dist/development/src/client/AcquiredConnection.cjs.map +1 -0
  79. package/dist/development/src/client/AcquiredConnection.js +91 -0
  80. package/dist/development/src/client/AcquiredConnection.js.map +1 -0
  81. package/dist/development/src/client/Client.cjs +87 -0
  82. package/dist/development/src/client/Client.cjs.map +1 -0
  83. package/dist/development/src/client/Client.js +87 -0
  84. package/dist/development/src/client/Client.js.map +1 -0
  85. package/dist/development/src/client/Connection.cjs +62 -0
  86. package/dist/development/src/client/Connection.cjs.map +1 -0
  87. package/dist/development/src/client/Connection.js +62 -0
  88. package/dist/development/src/client/Connection.js.map +1 -0
  89. package/dist/development/src/client/EventManager.cjs +36 -0
  90. package/dist/development/src/client/EventManager.cjs.map +1 -0
  91. package/dist/development/src/client/EventManager.js +36 -0
  92. package/dist/development/src/client/EventManager.js.map +1 -0
  93. package/dist/development/src/client/Pool.cjs +380 -0
  94. package/dist/development/src/client/Pool.cjs.map +1 -0
  95. package/dist/development/src/client/Pool.js +380 -0
  96. package/dist/development/src/client/Pool.js.map +1 -0
  97. package/dist/development/src/client/Transaction.cjs +148 -0
  98. package/dist/development/src/client/Transaction.cjs.map +1 -0
  99. package/dist/development/src/client/Transaction.js +148 -0
  100. package/dist/development/src/client/Transaction.js.map +1 -0
  101. package/dist/development/src/client/errorCodes.cjs +266 -0
  102. package/dist/development/src/client/errorCodes.cjs.map +1 -0
  103. package/dist/development/src/client/errorCodes.js +266 -0
  104. package/dist/development/src/client/errorCodes.js.map +1 -0
  105. package/dist/development/src/client/errors.cjs +68 -0
  106. package/dist/development/src/client/errors.cjs.map +1 -0
  107. package/dist/development/src/client/errors.js +68 -0
  108. package/dist/development/src/client/errors.js.map +1 -0
  109. package/dist/development/src/exceptions.cjs +6 -0
  110. package/dist/development/src/exceptions.cjs.map +1 -0
  111. package/dist/development/src/exceptions.js +6 -0
  112. package/dist/development/src/exceptions.js.map +1 -0
  113. package/dist/development/src/metadata/DatabaseMetadata.cjs +18 -0
  114. package/dist/development/src/metadata/DatabaseMetadata.cjs.map +1 -0
  115. package/dist/development/src/metadata/DatabaseMetadata.js +18 -0
  116. package/dist/development/src/metadata/DatabaseMetadata.js.map +1 -0
  117. package/dist/development/src/metadata/DatabaseMetadataResolver.cjs +103 -0
  118. package/dist/development/src/metadata/DatabaseMetadataResolver.cjs.map +1 -0
  119. package/dist/development/src/metadata/DatabaseMetadataResolver.js +103 -0
  120. package/dist/development/src/metadata/DatabaseMetadataResolver.js.map +1 -0
  121. package/dist/development/src/metadata/ForeignKeyConstraintMetadata.cjs +56 -0
  122. package/dist/development/src/metadata/ForeignKeyConstraintMetadata.cjs.map +1 -0
  123. package/dist/development/src/metadata/ForeignKeyConstraintMetadata.js +56 -0
  124. package/dist/development/src/metadata/ForeignKeyConstraintMetadata.js.map +1 -0
  125. package/dist/development/src/metadata/IndexMetadata.cjs +33 -0
  126. package/dist/development/src/metadata/IndexMetadata.cjs.map +1 -0
  127. package/dist/development/src/metadata/IndexMetadata.js +33 -0
  128. package/dist/development/src/metadata/IndexMetadata.js.map +1 -0
  129. package/dist/development/src/metadata/UniqueConstraintMetadata.cjs +39 -0
  130. package/dist/development/src/metadata/UniqueConstraintMetadata.cjs.map +1 -0
  131. package/dist/development/src/metadata/UniqueConstraintMetadata.js +39 -0
  132. package/dist/development/src/metadata/UniqueConstraintMetadata.js.map +1 -0
  133. package/dist/development/src/metadata/stringArrayEquals.cjs +12 -0
  134. package/dist/development/src/metadata/stringArrayEquals.cjs.map +1 -0
  135. package/dist/development/src/metadata/stringArrayEquals.js +12 -0
  136. package/dist/development/src/metadata/stringArrayEquals.js.map +1 -0
  137. package/dist/development/src/queryable/DatabaseQuery.cjs +16 -0
  138. package/dist/development/src/queryable/DatabaseQuery.cjs.map +1 -0
  139. package/dist/development/src/queryable/DatabaseQuery.js +16 -0
  140. package/dist/development/src/queryable/DatabaseQuery.js.map +1 -0
  141. package/dist/development/src/queryable/DatabaseQueryable.cjs +13 -0
  142. package/dist/development/src/queryable/DatabaseQueryable.cjs.map +1 -0
  143. package/dist/development/src/queryable/DatabaseQueryable.js +13 -0
  144. package/dist/development/src/queryable/DatabaseQueryable.js.map +1 -0
  145. package/dist/development/src/utils/ConstraintHelper.cjs +44 -0
  146. package/dist/development/src/utils/ConstraintHelper.cjs.map +1 -0
  147. package/dist/development/src/utils/ConstraintHelper.js +44 -0
  148. package/dist/development/src/utils/ConstraintHelper.js.map +1 -0
  149. package/dist/development/src/utils/Mutex.cjs +49 -0
  150. package/dist/development/src/utils/Mutex.cjs.map +1 -0
  151. package/dist/development/src/utils/Mutex.js +49 -0
  152. package/dist/development/src/utils/Mutex.js.map +1 -0
  153. package/dist/development/src/utils/assertNever.cjs +7 -0
  154. package/dist/development/src/utils/assertNever.cjs.map +1 -0
  155. package/dist/development/src/utils/assertNever.js +7 -0
  156. package/dist/development/src/utils/assertNever.js.map +1 -0
  157. package/dist/development/src/utils/asyncIterableTransaction.cjs +26 -0
  158. package/dist/development/src/utils/asyncIterableTransaction.cjs.map +1 -0
  159. package/dist/development/src/utils/asyncIterableTransaction.js +26 -0
  160. package/dist/development/src/utils/asyncIterableTransaction.js.map +1 -0
  161. package/dist/development/src/utils/createDatabaseIfNotExists.cjs +34 -0
  162. package/dist/development/src/utils/createDatabaseIfNotExists.cjs.map +1 -0
  163. package/dist/development/src/utils/createDatabaseIfNotExists.js +34 -0
  164. package/dist/development/src/utils/createDatabaseIfNotExists.js.map +1 -0
  165. package/dist/development/src/utils/listen.cjs +118 -0
  166. package/dist/development/src/utils/listen.cjs.map +1 -0
  167. package/dist/development/src/utils/listen.js +118 -0
  168. package/dist/development/src/utils/listen.js.map +1 -0
  169. package/dist/development/src/utils/pgClientFactory.cjs +13 -0
  170. package/dist/development/src/utils/pgClientFactory.cjs.map +1 -0
  171. package/dist/development/src/utils/pgClientFactory.js +13 -0
  172. package/dist/development/src/utils/pgClientFactory.js.map +1 -0
  173. package/dist/development/src/utils/retryTransaction.cjs +49 -0
  174. package/dist/development/src/utils/retryTransaction.cjs.map +1 -0
  175. package/dist/development/src/utils/retryTransaction.js +49 -0
  176. package/dist/development/src/utils/retryTransaction.js.map +1 -0
  177. package/dist/development/src/utils/sql.cjs +30 -0
  178. package/dist/development/src/utils/sql.cjs.map +1 -0
  179. package/dist/development/src/utils/sql.js +30 -0
  180. package/dist/development/src/utils/sql.js.map +1 -0
  181. package/dist/development/src/utils/withDatabaseAdvisoryLock.cjs +15 -0
  182. package/dist/development/src/utils/withDatabaseAdvisoryLock.cjs.map +1 -0
  183. package/dist/development/src/utils/withDatabaseAdvisoryLock.js +15 -0
  184. package/dist/development/src/utils/withDatabaseAdvisoryLock.js.map +1 -0
  185. package/dist/production/index.cjs +104 -0
  186. package/dist/production/index.cjs.map +1 -0
  187. package/dist/production/index.js +92 -0
  188. package/dist/production/index.js.map +1 -0
  189. package/dist/production/src/Literal.cjs +37 -0
  190. package/dist/production/src/Literal.cjs.map +1 -0
  191. package/dist/production/src/Literal.js +37 -0
  192. package/dist/production/src/Literal.js.map +1 -0
  193. package/dist/production/src/builders/CaseStatement.cjs +47 -0
  194. package/dist/production/src/builders/CaseStatement.cjs.map +1 -0
  195. package/dist/production/src/builders/CaseStatement.js +47 -0
  196. package/dist/production/src/builders/CaseStatement.js.map +1 -0
  197. package/dist/production/src/builders/ColumnExpressionFactory.cjs +41 -0
  198. package/dist/production/src/builders/ColumnExpressionFactory.cjs.map +1 -0
  199. package/dist/production/src/builders/ColumnExpressionFactory.js +41 -0
  200. package/dist/production/src/builders/ColumnExpressionFactory.js.map +1 -0
  201. package/dist/production/src/builders/Compiler.cjs +219 -0
  202. package/dist/production/src/builders/Compiler.cjs.map +1 -0
  203. package/dist/production/src/builders/Compiler.js +219 -0
  204. package/dist/production/src/builders/Compiler.js.map +1 -0
  205. package/dist/production/src/builders/ConditionBuilder.cjs +167 -0
  206. package/dist/production/src/builders/ConditionBuilder.cjs.map +1 -0
  207. package/dist/production/src/builders/ConditionBuilder.js +167 -0
  208. package/dist/production/src/builders/ConditionBuilder.js.map +1 -0
  209. package/dist/production/src/builders/ConflictActionType.cjs +9 -0
  210. package/dist/production/src/builders/ConflictActionType.cjs.map +1 -0
  211. package/dist/production/src/builders/ConflictActionType.js +9 -0
  212. package/dist/production/src/builders/ConflictActionType.js.map +1 -0
  213. package/dist/production/src/builders/DeleteBuilder.cjs +54 -0
  214. package/dist/production/src/builders/DeleteBuilder.cjs.map +1 -0
  215. package/dist/production/src/builders/DeleteBuilder.js +54 -0
  216. package/dist/production/src/builders/DeleteBuilder.js.map +1 -0
  217. package/dist/production/src/builders/InsertBuilder.cjs +106 -0
  218. package/dist/production/src/builders/InsertBuilder.cjs.map +1 -0
  219. package/dist/production/src/builders/InsertBuilder.js +106 -0
  220. package/dist/production/src/builders/InsertBuilder.js.map +1 -0
  221. package/dist/production/src/builders/LimitByGroupWrapper.cjs +37 -0
  222. package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -0
  223. package/dist/production/src/builders/LimitByGroupWrapper.js +37 -0
  224. package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -0
  225. package/dist/production/src/builders/LockType.cjs +17 -0
  226. package/dist/production/src/builders/LockType.cjs.map +1 -0
  227. package/dist/production/src/builders/LockType.js +17 -0
  228. package/dist/production/src/builders/LockType.js.map +1 -0
  229. package/dist/production/src/builders/SelectBuilder.cjs +149 -0
  230. package/dist/production/src/builders/SelectBuilder.cjs.map +1 -0
  231. package/dist/production/src/builders/SelectBuilder.js +149 -0
  232. package/dist/production/src/builders/SelectBuilder.js.map +1 -0
  233. package/dist/production/src/builders/UpdateBuilder.cjs +82 -0
  234. package/dist/production/src/builders/UpdateBuilder.cjs.map +1 -0
  235. package/dist/production/src/builders/UpdateBuilder.js +82 -0
  236. package/dist/production/src/builders/UpdateBuilder.js.map +1 -0
  237. package/dist/production/src/builders/WindowFunction.cjs +60 -0
  238. package/dist/production/src/builders/WindowFunction.cjs.map +1 -0
  239. package/dist/production/src/builders/WindowFunction.js +60 -0
  240. package/dist/production/src/builders/WindowFunction.js.map +1 -0
  241. package/dist/production/src/builders/internal/Returning.cjs +34 -0
  242. package/dist/production/src/builders/internal/Returning.cjs.map +1 -0
  243. package/dist/production/src/builders/internal/Returning.js +34 -0
  244. package/dist/production/src/builders/internal/Returning.js.map +1 -0
  245. package/dist/production/src/builders/internal/Subqueries.cjs +15 -0
  246. package/dist/production/src/builders/internal/Subqueries.cjs.map +1 -0
  247. package/dist/production/src/builders/internal/Subqueries.js +15 -0
  248. package/dist/production/src/builders/internal/Subqueries.js.map +1 -0
  249. package/dist/production/src/builders/internal/Where.cjs +53 -0
  250. package/dist/production/src/builders/internal/Where.cjs.map +1 -0
  251. package/dist/production/src/builders/internal/Where.js +54 -0
  252. package/dist/production/src/builders/internal/Where.js.map +1 -0
  253. package/dist/production/src/builders/internal/With.cjs +52 -0
  254. package/dist/production/src/builders/internal/With.cjs.map +1 -0
  255. package/dist/production/src/builders/internal/With.js +53 -0
  256. package/dist/production/src/builders/internal/With.js.map +1 -0
  257. package/dist/production/src/builders/utils.cjs +35 -0
  258. package/dist/production/src/builders/utils.cjs.map +1 -0
  259. package/dist/production/src/builders/utils.js +35 -0
  260. package/dist/production/src/builders/utils.js.map +1 -0
  261. package/dist/production/src/client/AcquiredConnection.cjs +91 -0
  262. package/dist/production/src/client/AcquiredConnection.cjs.map +1 -0
  263. package/dist/production/src/client/AcquiredConnection.js +91 -0
  264. package/dist/production/src/client/AcquiredConnection.js.map +1 -0
  265. package/dist/production/src/client/Client.cjs +87 -0
  266. package/dist/production/src/client/Client.cjs.map +1 -0
  267. package/dist/production/src/client/Client.js +87 -0
  268. package/dist/production/src/client/Client.js.map +1 -0
  269. package/dist/production/src/client/Connection.cjs +62 -0
  270. package/dist/production/src/client/Connection.cjs.map +1 -0
  271. package/dist/production/src/client/Connection.js +62 -0
  272. package/dist/production/src/client/Connection.js.map +1 -0
  273. package/dist/production/src/client/EventManager.cjs +36 -0
  274. package/dist/production/src/client/EventManager.cjs.map +1 -0
  275. package/dist/production/src/client/EventManager.js +36 -0
  276. package/dist/production/src/client/EventManager.js.map +1 -0
  277. package/dist/production/src/client/Pool.cjs +380 -0
  278. package/dist/production/src/client/Pool.cjs.map +1 -0
  279. package/dist/production/src/client/Pool.js +380 -0
  280. package/dist/production/src/client/Pool.js.map +1 -0
  281. package/dist/production/src/client/Transaction.cjs +148 -0
  282. package/dist/production/src/client/Transaction.cjs.map +1 -0
  283. package/dist/production/src/client/Transaction.js +148 -0
  284. package/dist/production/src/client/Transaction.js.map +1 -0
  285. package/dist/production/src/client/errorCodes.cjs +266 -0
  286. package/dist/production/src/client/errorCodes.cjs.map +1 -0
  287. package/dist/production/src/client/errorCodes.js +266 -0
  288. package/dist/production/src/client/errorCodes.js.map +1 -0
  289. package/dist/production/src/client/errors.cjs +68 -0
  290. package/dist/production/src/client/errors.cjs.map +1 -0
  291. package/dist/production/src/client/errors.js +68 -0
  292. package/dist/production/src/client/errors.js.map +1 -0
  293. package/dist/production/src/exceptions.cjs +6 -0
  294. package/dist/production/src/exceptions.cjs.map +1 -0
  295. package/dist/production/src/exceptions.js +6 -0
  296. package/dist/production/src/exceptions.js.map +1 -0
  297. package/dist/production/src/metadata/DatabaseMetadata.cjs +18 -0
  298. package/dist/production/src/metadata/DatabaseMetadata.cjs.map +1 -0
  299. package/dist/production/src/metadata/DatabaseMetadata.js +18 -0
  300. package/dist/production/src/metadata/DatabaseMetadata.js.map +1 -0
  301. package/dist/production/src/metadata/DatabaseMetadataResolver.cjs +103 -0
  302. package/dist/production/src/metadata/DatabaseMetadataResolver.cjs.map +1 -0
  303. package/dist/production/src/metadata/DatabaseMetadataResolver.js +103 -0
  304. package/dist/production/src/metadata/DatabaseMetadataResolver.js.map +1 -0
  305. package/dist/production/src/metadata/ForeignKeyConstraintMetadata.cjs +56 -0
  306. package/dist/production/src/metadata/ForeignKeyConstraintMetadata.cjs.map +1 -0
  307. package/dist/production/src/metadata/ForeignKeyConstraintMetadata.js +56 -0
  308. package/dist/production/src/metadata/ForeignKeyConstraintMetadata.js.map +1 -0
  309. package/dist/production/src/metadata/IndexMetadata.cjs +33 -0
  310. package/dist/production/src/metadata/IndexMetadata.cjs.map +1 -0
  311. package/dist/production/src/metadata/IndexMetadata.js +33 -0
  312. package/dist/production/src/metadata/IndexMetadata.js.map +1 -0
  313. package/dist/production/src/metadata/UniqueConstraintMetadata.cjs +39 -0
  314. package/dist/production/src/metadata/UniqueConstraintMetadata.cjs.map +1 -0
  315. package/dist/production/src/metadata/UniqueConstraintMetadata.js +39 -0
  316. package/dist/production/src/metadata/UniqueConstraintMetadata.js.map +1 -0
  317. package/dist/production/src/metadata/stringArrayEquals.cjs +12 -0
  318. package/dist/production/src/metadata/stringArrayEquals.cjs.map +1 -0
  319. package/dist/production/src/metadata/stringArrayEquals.js +12 -0
  320. package/dist/production/src/metadata/stringArrayEquals.js.map +1 -0
  321. package/dist/production/src/queryable/DatabaseQuery.cjs +16 -0
  322. package/dist/production/src/queryable/DatabaseQuery.cjs.map +1 -0
  323. package/dist/production/src/queryable/DatabaseQuery.js +16 -0
  324. package/dist/production/src/queryable/DatabaseQuery.js.map +1 -0
  325. package/dist/production/src/queryable/DatabaseQueryable.cjs +13 -0
  326. package/dist/production/src/queryable/DatabaseQueryable.cjs.map +1 -0
  327. package/dist/production/src/queryable/DatabaseQueryable.js +13 -0
  328. package/dist/production/src/queryable/DatabaseQueryable.js.map +1 -0
  329. package/dist/production/src/utils/ConstraintHelper.cjs +44 -0
  330. package/dist/production/src/utils/ConstraintHelper.cjs.map +1 -0
  331. package/dist/production/src/utils/ConstraintHelper.js +44 -0
  332. package/dist/production/src/utils/ConstraintHelper.js.map +1 -0
  333. package/dist/production/src/utils/Mutex.cjs +49 -0
  334. package/dist/production/src/utils/Mutex.cjs.map +1 -0
  335. package/dist/production/src/utils/Mutex.js +49 -0
  336. package/dist/production/src/utils/Mutex.js.map +1 -0
  337. package/dist/production/src/utils/assertNever.cjs +7 -0
  338. package/dist/production/src/utils/assertNever.cjs.map +1 -0
  339. package/dist/production/src/utils/assertNever.js +7 -0
  340. package/dist/production/src/utils/assertNever.js.map +1 -0
  341. package/dist/production/src/utils/asyncIterableTransaction.cjs +26 -0
  342. package/dist/production/src/utils/asyncIterableTransaction.cjs.map +1 -0
  343. package/dist/production/src/utils/asyncIterableTransaction.js +26 -0
  344. package/dist/production/src/utils/asyncIterableTransaction.js.map +1 -0
  345. package/dist/production/src/utils/createDatabaseIfNotExists.cjs +34 -0
  346. package/dist/production/src/utils/createDatabaseIfNotExists.cjs.map +1 -0
  347. package/dist/production/src/utils/createDatabaseIfNotExists.js +34 -0
  348. package/dist/production/src/utils/createDatabaseIfNotExists.js.map +1 -0
  349. package/dist/production/src/utils/listen.cjs +118 -0
  350. package/dist/production/src/utils/listen.cjs.map +1 -0
  351. package/dist/production/src/utils/listen.js +118 -0
  352. package/dist/production/src/utils/listen.js.map +1 -0
  353. package/dist/production/src/utils/pgClientFactory.cjs +13 -0
  354. package/dist/production/src/utils/pgClientFactory.cjs.map +1 -0
  355. package/dist/production/src/utils/pgClientFactory.js +13 -0
  356. package/dist/production/src/utils/pgClientFactory.js.map +1 -0
  357. package/dist/production/src/utils/retryTransaction.cjs +49 -0
  358. package/dist/production/src/utils/retryTransaction.cjs.map +1 -0
  359. package/dist/production/src/utils/retryTransaction.js +49 -0
  360. package/dist/production/src/utils/retryTransaction.js.map +1 -0
  361. package/dist/production/src/utils/sql.cjs +30 -0
  362. package/dist/production/src/utils/sql.cjs.map +1 -0
  363. package/dist/production/src/utils/sql.js +30 -0
  364. package/dist/production/src/utils/sql.js.map +1 -0
  365. package/dist/production/src/utils/withDatabaseAdvisoryLock.cjs +15 -0
  366. package/dist/production/src/utils/withDatabaseAdvisoryLock.cjs.map +1 -0
  367. package/dist/production/src/utils/withDatabaseAdvisoryLock.js +15 -0
  368. package/dist/production/src/utils/withDatabaseAdvisoryLock.js.map +1 -0
  369. package/dist/tests/cases/unit/connection.test.d.ts +2 -0
  370. package/dist/tests/cases/unit/connection.test.d.ts.map +1 -0
  371. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +7 -0
  372. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -0
  373. package/dist/tests/cases/unit/eventManager.test.d.ts +2 -0
  374. package/dist/tests/cases/unit/eventManager.test.d.ts.map +1 -0
  375. package/dist/tests/cases/unit/pool.test.d.ts +2 -0
  376. package/dist/tests/cases/unit/pool.test.d.ts.map +1 -0
  377. package/dist/tests/cases/unit/queryBuilder.test.d.ts +2 -0
  378. package/dist/tests/cases/unit/queryBuilder.test.d.ts.map +1 -0
  379. package/dist/tests/src/tags.d.ts +2 -0
  380. package/dist/tests/src/tags.d.ts.map +1 -0
  381. package/dist/tests/tsconfig.tsbuildinfo +1 -0
  382. package/dist/types/Literal.d.ts +12 -0
  383. package/dist/types/Literal.d.ts.map +1 -0
  384. package/dist/types/builders/CaseStatement.d.ts +21 -0
  385. package/dist/types/builders/CaseStatement.d.ts.map +1 -0
  386. package/dist/types/builders/ColumnExpressionFactory.d.ts +15 -0
  387. package/dist/types/builders/ColumnExpressionFactory.d.ts.map +1 -0
  388. package/dist/types/builders/Compiler.d.ts +39 -0
  389. package/dist/types/builders/Compiler.d.ts.map +1 -0
  390. package/dist/types/builders/ConditionBuilder.d.ts +46 -0
  391. package/dist/types/builders/ConditionBuilder.d.ts.map +1 -0
  392. package/dist/types/builders/ConflictActionType.d.ts +5 -0
  393. package/dist/types/builders/ConflictActionType.d.ts.map +1 -0
  394. package/dist/types/builders/DeleteBuilder.d.ts +34 -0
  395. package/dist/types/builders/DeleteBuilder.d.ts.map +1 -0
  396. package/dist/types/builders/InsertBuilder.d.ts +66 -0
  397. package/dist/types/builders/InsertBuilder.d.ts.map +1 -0
  398. package/dist/types/builders/LimitByGroupWrapper.d.ts +14 -0
  399. package/dist/types/builders/LimitByGroupWrapper.d.ts.map +1 -0
  400. package/dist/types/builders/LockType.d.ts +11 -0
  401. package/dist/types/builders/LockType.d.ts.map +1 -0
  402. package/dist/types/builders/QueryBuilder.d.ts +31 -0
  403. package/dist/types/builders/QueryBuilder.d.ts.map +1 -0
  404. package/dist/types/builders/SelectBuilder.d.ts +72 -0
  405. package/dist/types/builders/SelectBuilder.d.ts.map +1 -0
  406. package/dist/types/builders/UpdateBuilder.d.ts +42 -0
  407. package/dist/types/builders/UpdateBuilder.d.ts.map +1 -0
  408. package/dist/types/builders/WindowFunction.d.ts +16 -0
  409. package/dist/types/builders/WindowFunction.d.ts.map +1 -0
  410. package/dist/types/builders/index.d.ts +13 -0
  411. package/dist/types/builders/index.d.ts.map +1 -0
  412. package/dist/types/builders/internal/Returning.d.ts +18 -0
  413. package/dist/types/builders/internal/Returning.d.ts.map +1 -0
  414. package/dist/types/builders/internal/Subqueries.d.ts +8 -0
  415. package/dist/types/builders/internal/Subqueries.d.ts.map +1 -0
  416. package/dist/types/builders/internal/Where.d.ts +26 -0
  417. package/dist/types/builders/internal/Where.d.ts.map +1 -0
  418. package/dist/types/builders/internal/With.d.ts +31 -0
  419. package/dist/types/builders/internal/With.d.ts.map +1 -0
  420. package/dist/types/builders/utils.d.ts +5 -0
  421. package/dist/types/builders/utils.d.ts.map +1 -0
  422. package/dist/types/client/AcquiredConnection.d.ts +19 -0
  423. package/dist/types/client/AcquiredConnection.d.ts.map +1 -0
  424. package/dist/types/client/Client.d.ts +24 -0
  425. package/dist/types/client/Client.d.ts.map +1 -0
  426. package/dist/types/client/Connection.d.ts +76 -0
  427. package/dist/types/client/Connection.d.ts.map +1 -0
  428. package/dist/types/client/EventManager.d.ts +29 -0
  429. package/dist/types/client/EventManager.d.ts.map +1 -0
  430. package/dist/types/client/PgClient.d.ts +11 -0
  431. package/dist/types/client/PgClient.d.ts.map +1 -0
  432. package/dist/types/client/Pool.d.ts +131 -0
  433. package/dist/types/client/Pool.d.ts.map +1 -0
  434. package/dist/types/client/Transaction.d.ts +38 -0
  435. package/dist/types/client/Transaction.d.ts.map +1 -0
  436. package/dist/types/client/errorCodes.d.ts +262 -0
  437. package/dist/types/client/errorCodes.d.ts.map +1 -0
  438. package/dist/types/client/errors.d.ts +34 -0
  439. package/dist/types/client/errors.d.ts.map +1 -0
  440. package/dist/types/client/index.d.ts +8 -0
  441. package/dist/types/client/index.d.ts.map +1 -0
  442. package/dist/types/exceptions.d.ts +3 -0
  443. package/dist/types/exceptions.d.ts.map +1 -0
  444. package/dist/types/index.d.ts +14 -0
  445. package/dist/types/index.d.ts.map +1 -0
  446. package/dist/types/metadata/DatabaseMetadata.d.ts +15 -0
  447. package/dist/types/metadata/DatabaseMetadata.d.ts.map +1 -0
  448. package/dist/types/metadata/DatabaseMetadataResolver.d.ts +8 -0
  449. package/dist/types/metadata/DatabaseMetadataResolver.d.ts.map +1 -0
  450. package/dist/types/metadata/ForeignKeyConstraintMetadata.d.ts +27 -0
  451. package/dist/types/metadata/ForeignKeyConstraintMetadata.d.ts.map +1 -0
  452. package/dist/types/metadata/IndexMetadata.d.ts +15 -0
  453. package/dist/types/metadata/IndexMetadata.d.ts.map +1 -0
  454. package/dist/types/metadata/UniqueConstraintMetadata.d.ts +17 -0
  455. package/dist/types/metadata/UniqueConstraintMetadata.d.ts.map +1 -0
  456. package/dist/types/metadata/index.d.ts +6 -0
  457. package/dist/types/metadata/index.d.ts.map +1 -0
  458. package/dist/types/metadata/stringArrayEquals.d.ts +2 -0
  459. package/dist/types/metadata/stringArrayEquals.d.ts.map +1 -0
  460. package/dist/types/queryable/DatabaseQuery.d.ts +7 -0
  461. package/dist/types/queryable/DatabaseQuery.d.ts.map +1 -0
  462. package/dist/types/queryable/DatabaseQueryable.d.ts +9 -0
  463. package/dist/types/queryable/DatabaseQueryable.d.ts.map +1 -0
  464. package/dist/types/queryable/index.d.ts +3 -0
  465. package/dist/types/queryable/index.d.ts.map +1 -0
  466. package/dist/types/tsconfig.tsbuildinfo +1 -0
  467. package/dist/types/types.d.ts +23 -0
  468. package/dist/types/types.d.ts.map +1 -0
  469. package/dist/types/utils/ConstraintHelper.d.ts +15 -0
  470. package/dist/types/utils/ConstraintHelper.d.ts.map +1 -0
  471. package/dist/types/utils/Mutex.d.ts +11 -0
  472. package/dist/types/utils/Mutex.d.ts.map +1 -0
  473. package/dist/types/utils/assertNever.d.ts +2 -0
  474. package/dist/types/utils/assertNever.d.ts.map +1 -0
  475. package/dist/types/utils/asyncIterableTransaction.d.ts +7 -0
  476. package/dist/types/utils/asyncIterableTransaction.d.ts.map +1 -0
  477. package/dist/types/utils/createDatabaseIfNotExists.d.ts +3 -0
  478. package/dist/types/utils/createDatabaseIfNotExists.d.ts.map +1 -0
  479. package/dist/types/utils/index.d.ts +11 -0
  480. package/dist/types/utils/index.d.ts.map +1 -0
  481. package/dist/types/utils/listen.d.ts +32 -0
  482. package/dist/types/utils/listen.d.ts.map +1 -0
  483. package/dist/types/utils/pgClientFactory.d.ts +6 -0
  484. package/dist/types/utils/pgClientFactory.d.ts.map +1 -0
  485. package/dist/types/utils/retryTransaction.d.ts +7 -0
  486. package/dist/types/utils/retryTransaction.d.ts.map +1 -0
  487. package/dist/types/utils/sql.d.ts +6 -0
  488. package/dist/types/utils/sql.d.ts.map +1 -0
  489. package/dist/types/utils/withDatabaseAdvisoryLock.d.ts +3 -0
  490. package/dist/types/utils/withDatabaseAdvisoryLock.d.ts.map +1 -0
  491. package/package.json +6 -6
@@ -0,0 +1,380 @@
1
+ import { ImplementationException } from "../exceptions.js";
2
+ import { ClientErrorCodes } from "./errorCodes.js";
3
+ import { ClientError, DatabaseError } from "./errors.js";
4
+ var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ const poolStatsDescription = {
8
+ connection_started_count: "Total number of connection attempts when started.",
9
+ connection_established_count: "Total number of established connections.",
10
+ connection_recoverable_error_count: "Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.",
11
+ connection_error_count: "Number of non-recoverable errors or recoverable errors reaching max attempts.",
12
+ connection_disposed_idle_timeout_count: "Number of idle connection, that was disposed after configured timeout.",
13
+ connection_disposed_idle_max_count: "Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.",
14
+ connection_disposed_old_count: "Number of connections, that was too old after it was released.",
15
+ connection_disposed_manual_count: "Number of manually disposed connection (e.g. due to exception on given connection).",
16
+ connection_released_count: "Number of connection returned to the pool.",
17
+ connection_reused_immediately_count: "Number of connections, that was reused by pending item immediately after it was returned to the pool.",
18
+ connection_reused_later_count: "Number of idle connections, that was reused later.",
19
+ connection_established_idle_count: "Number of newly established connections, which was not used (e.g. some connection was returned earlier).",
20
+ item_queued_count: "Number of queued items requesting a connection.",
21
+ item_timeout_count: "Number of items waiting for connection, which timed out.",
22
+ item_rejected_count: "Number of items rejected with an error.",
23
+ item_resolved_new_ms_count: "Number of queued items resolved with newly established connection.",
24
+ item_resolved_new_ms_sum: "Waiting time of queued items, which was resolved with a new connection.",
25
+ item_resolved_released_ms_count: "Number of queued items resolved with released connection.",
26
+ item_resolved_released_ms_sum: "Waiting time of queued items, which was resolved with a released connection."
27
+ };
28
+ class PoolConnection {
29
+ constructor(client) {
30
+ this.client = client;
31
+ __publicField(this, "disposed", false);
32
+ __publicField(this, "uses", 0);
33
+ __publicField(this, "createdAt", Date.now());
34
+ __publicField(this, "timerId", null);
35
+ }
36
+ }
37
+ class PendingItem {
38
+ constructor(resolve, reject) {
39
+ this.resolve = resolve;
40
+ this.reject = reject;
41
+ __publicField(this, "createdAt", Date.now());
42
+ }
43
+ }
44
+ class Pool {
45
+ constructor(clientFactory, poolConfig) {
46
+ this.clientFactory = clientFactory;
47
+ __publicField(this, "ended", false);
48
+ __publicField(this, "connectingCount", 0);
49
+ __publicField(this, "remainingRateLimit");
50
+ __publicField(this, "idle", []);
51
+ __publicField(this, "active", /* @__PURE__ */ new Set());
52
+ __publicField(this, "queue", []);
53
+ __publicField(this, "poolConfig");
54
+ __publicField(this, "poolStats", {
55
+ connection_started_count: 0,
56
+ connection_established_count: 0,
57
+ connection_recoverable_error_count: 0,
58
+ connection_error_count: 0,
59
+ connection_disposed_idle_timeout_count: 0,
60
+ connection_disposed_idle_max_count: 0,
61
+ connection_disposed_old_count: 0,
62
+ connection_disposed_manual_count: 0,
63
+ connection_released_count: 0,
64
+ connection_reused_immediately_count: 0,
65
+ connection_reused_later_count: 0,
66
+ connection_established_idle_count: 0,
67
+ item_queued_count: 0,
68
+ item_timeout_count: 0,
69
+ item_rejected_count: 0,
70
+ item_resolved_new_ms_count: 0,
71
+ item_resolved_new_ms_sum: 0,
72
+ item_resolved_released_ms_count: 0,
73
+ item_resolved_released_ms_sum: 0
74
+ });
75
+ __publicField(this, "lastRecoverableError");
76
+ const maxConnections = poolConfig.maxConnections ?? 10;
77
+ const maxConnecting = Math.ceil(maxConnections / 2);
78
+ this.poolConfig = {
79
+ maxConnections,
80
+ maxConnecting,
81
+ maxIdle: maxConnections,
82
+ rateLimitCount: maxConnecting * 5,
83
+ rateLimitPeriodMs: 1e3,
84
+ idleTimeoutMs: 1e4,
85
+ acquireTimeoutMs: 1e4,
86
+ reconnectIntervalMs: 100,
87
+ ...poolConfig
88
+ };
89
+ this.remainingRateLimit = this.poolConfig.rateLimitCount;
90
+ }
91
+ acquire() {
92
+ if (this.ended) {
93
+ throw new PoolClosedError();
94
+ }
95
+ const poolConnection = this.idle.pop();
96
+ if (poolConnection !== void 0) {
97
+ if (poolConnection.timerId) {
98
+ clearTimeout(poolConnection.timerId);
99
+ }
100
+ poolConnection.uses++;
101
+ this.active.add(poolConnection);
102
+ this.poolStats.connection_reused_later_count++;
103
+ this.log("Item fulfilled with an idle connection.");
104
+ return Promise.resolve(poolConnection);
105
+ }
106
+ const pendingItem = this.createPendingItem();
107
+ this.maybeCreateNew();
108
+ return pendingItem;
109
+ }
110
+ release(poolConnection) {
111
+ if (this.ended) {
112
+ return;
113
+ }
114
+ this.log("Releasing a connection.");
115
+ if (!this.active.delete(poolConnection)) {
116
+ throw new ImplementationException("Connection does not belong to this pool.");
117
+ }
118
+ if (this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses || this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now()) {
119
+ setImmediate(async () => {
120
+ await this.disposeConnection(poolConnection);
121
+ this.poolStats.connection_disposed_old_count++;
122
+ this.log("Connection has reached max age or usage and was disposed.");
123
+ });
124
+ this.maybeCreateNew();
125
+ return;
126
+ }
127
+ this.handleAvailableConnection(poolConnection);
128
+ }
129
+ dispose(poolConnection) {
130
+ if (this.ended) {
131
+ return;
132
+ }
133
+ this.poolStats.connection_disposed_manual_count++;
134
+ this.log("Releasing and disposing a connection.");
135
+ if (!this.active.delete(poolConnection)) {
136
+ throw new ImplementationException("Connection does not belong to this pool.");
137
+ }
138
+ setImmediate(async () => {
139
+ await this.disposeConnection(poolConnection);
140
+ this.log("Connection errored and was disposed.");
141
+ });
142
+ this.maybeCreateNew();
143
+ }
144
+ async end() {
145
+ this.ended = true;
146
+ this.queue.forEach((it) => it.reject(new PoolClosedError()));
147
+ this.queue = [];
148
+ const allConnections = [...this.idle, ...Array.from(this.active)];
149
+ await Promise.allSettled(allConnections.map((it) => this.disposeConnection(it)));
150
+ this.idle = [];
151
+ this.active.clear();
152
+ }
153
+ async closeIdle() {
154
+ this.log("Disposing all idle connection on request.");
155
+ const idle = this.idle;
156
+ this.idle = [];
157
+ await Promise.allSettled(idle.map((it) => this.disposeConnection(it)));
158
+ }
159
+ getPoolStatus() {
160
+ return {
161
+ max: this.poolConfig.maxConnections,
162
+ active: this.active.size,
163
+ idle: this.idle.length,
164
+ pending: this.queue.length,
165
+ connecting: this.connectingCount,
166
+ stats: this.poolStats
167
+ };
168
+ }
169
+ async maybeCreateNew() {
170
+ if (this.ended) {
171
+ return;
172
+ }
173
+ if (this.queue.length === 0) {
174
+ this.log("Not connecting, queue is empty.");
175
+ return;
176
+ }
177
+ const connectingCount = this.connectingCount;
178
+ if (connectingCount >= this.queue.length) {
179
+ this.log("Not connecting, already establishing connection for all queued items.");
180
+ return;
181
+ }
182
+ const idleCount = this.idle.length;
183
+ if (this.active.size + idleCount + connectingCount >= this.poolConfig.maxConnections) {
184
+ this.log("Not connecting, max connections reached.");
185
+ return;
186
+ }
187
+ if (connectingCount >= this.poolConfig.maxConnecting) {
188
+ this.log("Not connecting, maximum concurrent connection attempts in progress.");
189
+ return;
190
+ }
191
+ if (this.remainingRateLimit <= 0) {
192
+ this.log("Not connecting, rate limit reached.");
193
+ return;
194
+ }
195
+ this.log("Creating a new connection");
196
+ const client = this.clientFactory();
197
+ const poolConnection = new PoolConnection(client);
198
+ client.on("error", (e) => {
199
+ this.log("Client error on idle connection has occurred: " + e.message);
200
+ this.poolConfig.logError(new ClientError(e, "runtime error"));
201
+ this.poolStats.connection_error_count++;
202
+ if (!this.active.has(poolConnection)) {
203
+ this.removeIdleConnection(poolConnection);
204
+ this.disposeConnection(poolConnection);
205
+ }
206
+ });
207
+ try {
208
+ this.connectingCount++;
209
+ this.remainingRateLimit--;
210
+ this.poolStats.connection_started_count++;
211
+ await client.connect();
212
+ this.poolStats.connection_established_count++;
213
+ this.connectingCount--;
214
+ this.log("Connection established");
215
+ if (this.ended) {
216
+ return this.disposeConnection(poolConnection);
217
+ }
218
+ this.handleAvailableConnection(poolConnection);
219
+ this.maybeCreateNew();
220
+ } catch (e) {
221
+ this.log("Connection error occurred: " + e.message);
222
+ this.disposeConnection(poolConnection);
223
+ if (e.code === ClientErrorCodes.TOO_MANY_CONNECTIONS || e.code === ClientErrorCodes.CANNOT_CONNECT_NOW || e.message === "timeout expired" || e.code === "ETIMEDOUT") {
224
+ this.lastRecoverableError = { error: e, time: Date.now() };
225
+ this.poolStats.connection_recoverable_error_count++;
226
+ this.log("Recoverable error, retrying in a moment.");
227
+ this.poolConfig.logError(new ClientError(e, "recoverable connection error"));
228
+ setTimeout(() => {
229
+ this.connectingCount--;
230
+ this.log("Retrying");
231
+ this.maybeCreateNew();
232
+ }, this.poolConfig.reconnectIntervalMs);
233
+ } else {
234
+ this.poolStats.connection_error_count++;
235
+ this.connectingCount--;
236
+ const clientError = new ClientError(e, "connection error");
237
+ if (this.active.size === 0 && this.queue.length > 0) {
238
+ const pendingItem = this.queue.shift();
239
+ if (!pendingItem) throw new Error();
240
+ this.log("Connecting failed, rejecting pending item");
241
+ pendingItem.reject(clientError);
242
+ this.poolStats.item_rejected_count++;
243
+ } else {
244
+ this.log("Connecting failed, emitting error");
245
+ this.poolConfig.logError(clientError);
246
+ }
247
+ }
248
+ } finally {
249
+ setTimeout(() => {
250
+ if (this.remainingRateLimit === 0) {
251
+ this.log("Rate limit renewed.");
252
+ }
253
+ this.remainingRateLimit++;
254
+ this.maybeCreateNew();
255
+ }, this.poolConfig.rateLimitPeriodMs);
256
+ }
257
+ }
258
+ createPendingItem() {
259
+ return new Promise((resolve, reject) => {
260
+ const timeout = setTimeout(() => {
261
+ const acquireTimeoutError = new AcquireTimeoutError(
262
+ this.lastRecoverableError && this.lastRecoverableError.time > item.createdAt ? this.lastRecoverableError.error : void 0
263
+ );
264
+ item.reject(acquireTimeoutError);
265
+ const index = this.queue.indexOf(item);
266
+ if (index > -1) {
267
+ this.queue.splice(index, 1);
268
+ }
269
+ this.poolStats.item_timeout_count++;
270
+ this.log("Queued item timed out");
271
+ }, this.poolConfig.acquireTimeoutMs);
272
+ const item = new PendingItem((it) => {
273
+ const duration = Date.now() - item.createdAt;
274
+ const isNew = it.uses === 0;
275
+ this.log(`Queued item fulfilled with ${!isNew ? "released" : "new"} connection.`);
276
+ if (isNew) {
277
+ this.poolStats.item_resolved_new_ms_count++;
278
+ this.poolStats.item_resolved_new_ms_sum += duration;
279
+ } else {
280
+ this.poolStats.item_resolved_released_ms_count++;
281
+ this.poolStats.item_resolved_released_ms_sum += duration;
282
+ }
283
+ clearTimeout(timeout);
284
+ resolve(it);
285
+ }, (it) => {
286
+ clearTimeout(timeout);
287
+ reject(it);
288
+ });
289
+ this.poolStats.item_queued_count++;
290
+ this.queue.push(item);
291
+ this.log(`Item added to a queue.`);
292
+ });
293
+ }
294
+ handleAvailableConnection(poolConnection) {
295
+ const item = this.queue.shift();
296
+ const isNew = poolConnection.uses === 0;
297
+ if (!isNew) {
298
+ this.poolStats.connection_released_count++;
299
+ }
300
+ if (item) {
301
+ this.active.add(poolConnection);
302
+ item.resolve(poolConnection);
303
+ if (!isNew) {
304
+ this.poolStats.connection_reused_immediately_count++;
305
+ }
306
+ poolConnection.uses++;
307
+ return;
308
+ }
309
+ if (isNew) {
310
+ this.poolStats.connection_established_idle_count++;
311
+ }
312
+ if (this.idle.length >= this.poolConfig.maxIdle) {
313
+ setImmediate(async () => {
314
+ await this.disposeConnection(poolConnection);
315
+ this.poolStats.connection_disposed_idle_max_count++;
316
+ this.log("Too many idle connections, connection disposed.");
317
+ });
318
+ } else {
319
+ poolConnection.timerId = setTimeout(async () => {
320
+ if (this.removeIdleConnection(poolConnection)) {
321
+ await this.disposeConnection(poolConnection);
322
+ this.poolStats.connection_disposed_idle_timeout_count++;
323
+ this.log("Idle connection disposed after timeout.");
324
+ }
325
+ }, this.poolConfig.idleTimeoutMs);
326
+ this.idle.push(poolConnection);
327
+ this.log("Connection is idle and available.");
328
+ }
329
+ }
330
+ removeIdleConnection(poolConnection) {
331
+ const index = this.idle.indexOf(poolConnection);
332
+ if (index > -1) {
333
+ this.idle.splice(index, 1);
334
+ return true;
335
+ }
336
+ return false;
337
+ }
338
+ async disposeConnection(connection) {
339
+ if (connection.disposed) {
340
+ throw new PoolError("Connection is already disposed");
341
+ }
342
+ connection.disposed = true;
343
+ const doEnd = async () => {
344
+ try {
345
+ await connection.client.end();
346
+ } catch (e) {
347
+ this.poolConfig.logError(new ClientError(e, "disposal error"));
348
+ }
349
+ };
350
+ await Promise.race([
351
+ doEnd(),
352
+ new Promise((resolve) => setTimeout(resolve, 5e3))
353
+ ]);
354
+ }
355
+ log(message) {
356
+ if (!this.poolConfig.log) return;
357
+ const poolStatus = this.getPoolStatus();
358
+ this.poolConfig.log(message, poolStatus);
359
+ }
360
+ }
361
+ class PoolError extends DatabaseError {
362
+ }
363
+ class AcquireTimeoutError extends PoolError {
364
+ constructor(previous) {
365
+ super("Failed to acquire a connection" + (previous && "message" in previous ? `. Last error: ${previous.message}` : ""), previous);
366
+ }
367
+ }
368
+ class PoolClosedError extends PoolError {
369
+ constructor() {
370
+ super("Pool is already closed");
371
+ }
372
+ }
373
+ export {
374
+ AcquireTimeoutError,
375
+ Pool,
376
+ PoolClosedError,
377
+ PoolError,
378
+ poolStatsDescription
379
+ };
380
+ //# sourceMappingURL=Pool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Pool.js","sources":["../../../../../packages/database/src/client/Pool.ts"],"sourcesContent":["import { ImplementationException } from '../exceptions'\nimport { ClientErrorCodes } from './errorCodes'\nimport { EventEmitter } from 'node:events'\nimport { ClientError, DatabaseError } from './errors'\nimport { PgClientFactory } from '../utils'\nimport { PgClient } from './PgClient'\n\nexport type PoolLogger = (message: string, status: PoolStatus) => void\n\nexport type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>\n\ninterface PoolConfigInternal {\n\t/** maximum number of connections in a pool */\n\tmaxConnections: number\n\t/** maximum number of connections concurrently establishing*/\n\tmaxConnecting: number\n\t/** maximum connection attempts during given period */\n\trateLimitCount: number\n\t/** period for rate limiting */\n\trateLimitPeriodMs: number\n\t/** maximum number of idle connections. when reached, will be disposed immediately */\n\tmaxIdle: number\n\t/** interval between retries of recoverable errors */\n\treconnectIntervalMs: number\n\t/** timeout to dispose idle connections */\n\tidleTimeoutMs: number\n\t/** timeout of pending item waiting for a connection. also used for retries of recoverable errors */\n\tacquireTimeoutMs: number\n\t/** how many times can a single connection be acquired */\n\tmaxUses?: number\n\t/** max age of connection. when reached, connection will be disposed after returning to a pool */\n\tmaxAgeMs?: number\n\t/** internal logging, mainly for debugging and testing */\n\tlog?: PoolLogger\n\t/** logging of out-of-stack errors */\n\tlogError: (error: ClientError) => void\n}\n\nexport type PoolStats = { [K in keyof typeof poolStatsDescription]: number }\n\nexport interface PoolStatus {\n\t/** maximum number of connections in a pool */\n\tmax: number\n\t/** number of items waiting for a connections */\n\tpending: number\n\t/** number of active (acquired) connections */\n\tactive: number\n\t/** number of available idle connections */\n\tidle: number\n\t/** number of currently establishing connections */\n\tconnecting: number\n\tstats: PoolStats\n}\n\nexport const poolStatsDescription = {\n\tconnection_started_count: 'Total number of connection attempts when started.',\n\tconnection_established_count: 'Total number of established connections.',\n\tconnection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',\n\tconnection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',\n\tconnection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',\n\tconnection_disposed_idle_max_count:\n\t\t'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',\n\tconnection_disposed_old_count: 'Number of connections, that was too old after it was released.',\n\tconnection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',\n\tconnection_released_count: 'Number of connection returned to the pool.',\n\tconnection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',\n\tconnection_reused_later_count: 'Number of idle connections, that was reused later.',\n\n\tconnection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',\n\n\titem_queued_count: 'Number of queued items requesting a connection.',\n\titem_timeout_count: 'Number of items waiting for connection, which timed out.',\n\titem_rejected_count: 'Number of items rejected with an error.',\n\n\titem_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',\n\titem_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',\n\titem_resolved_released_ms_count: 'Number of queued items resolved with released connection.',\n\titem_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',\n}\n\nclass PoolConnection {\n\tpublic disposed = false\n\tpublic uses = 0\n\tpublic createdAt = Date.now()\n\tpublic timerId: ReturnType<typeof setTimeout> | null = null\n\n\tconstructor(\n\t\tpublic readonly client: PgClient,\n\t) {\n\t}\n}\n\nclass PendingItem {\n\tpublic readonly createdAt = Date.now()\n\n\tconstructor(\n\t\tpublic resolve: (connection: PoolConnection) => void,\n\t\tpublic reject: (error: Error) => void,\n\t) {\n\t}\n}\n\nclass Pool {\n\t/**\n\t * pool was closed by calling end().\n\t * All connection was disposed, and it is not possible to acquire new one\n\t */\n\tprivate ended = false\n\n\t/**\n\t * current count of connection attempts\n\t * also includes timeout between recoverable retries\n\t */\n\tprivate connectingCount = 0\n\n\t/**\n\t * Remaining number of connections per floating period.\n\t */\n\tprivate remainingRateLimit: number\n\n\t/**\n\t * available idle connections\n\t */\n\tprivate idle: PoolConnection[] = []\n\n\t/**\n\t * currently acquired connections\n\t */\n\tprivate active = new Set<PoolConnection>()\n\n\t/**\n\t * items waiting for released or newly established connection\n\t */\n\tprivate queue: PendingItem[] = []\n\n\tprivate poolConfig: PoolConfigInternal\n\n\tprivate poolStats: PoolStats = {\n\t\tconnection_started_count: 0,\n\t\tconnection_established_count: 0,\n\t\tconnection_recoverable_error_count: 0,\n\t\tconnection_error_count: 0,\n\t\tconnection_disposed_idle_timeout_count: 0,\n\t\tconnection_disposed_idle_max_count: 0,\n\t\tconnection_disposed_old_count: 0,\n\t\tconnection_disposed_manual_count: 0,\n\t\tconnection_released_count: 0,\n\t\tconnection_reused_immediately_count: 0,\n\t\tconnection_reused_later_count: 0,\n\t\tconnection_established_idle_count: 0,\n\t\titem_queued_count: 0,\n\t\titem_timeout_count: 0,\n\t\titem_rejected_count: 0,\n\t\titem_resolved_new_ms_count: 0,\n\t\titem_resolved_new_ms_sum: 0,\n\t\titem_resolved_released_ms_count: 0,\n\t\titem_resolved_released_ms_sum: 0,\n\t}\n\n\tprivate lastRecoverableError: {\n\t\terror: any\n\t\ttime: number\n\t} | undefined\n\n\tconstructor(\n\t\tprivate clientFactory: PgClientFactory,\n\t\tpoolConfig: PoolConfig,\n\t) {\n\t\tconst maxConnections = poolConfig.maxConnections ?? 10\n\t\tconst maxConnecting = Math.ceil(maxConnections / 2)\n\t\tthis.poolConfig = {\n\t\t\tmaxConnections,\n\t\t\tmaxConnecting,\n\t\t\tmaxIdle: maxConnections,\n\t\t\trateLimitCount: maxConnecting * 5,\n\t\t\trateLimitPeriodMs: 1000,\n\t\t\tidleTimeoutMs: 10_000,\n\t\t\tacquireTimeoutMs: 10_000,\n\t\t\treconnectIntervalMs: 100,\n\t\t\t...poolConfig,\n\t\t}\n\t\tthis.remainingRateLimit = this.poolConfig.rateLimitCount\n\t}\n\n\tpublic acquire(): Promise<PoolConnection> {\n\t\tif (this.ended) {\n\t\t\tthrow new PoolClosedError()\n\t\t}\n\t\tconst poolConnection = this.idle.pop()\n\t\tif (poolConnection !== undefined) {\n\t\t\tif (poolConnection.timerId) {\n\t\t\t\tclearTimeout(poolConnection.timerId)\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\tthis.active.add(poolConnection)\n\t\t\tthis.poolStats.connection_reused_later_count++\n\t\t\tthis.log('Item fulfilled with an idle connection.')\n\n\t\t\treturn Promise.resolve(poolConnection)\n\t\t}\n\t\tconst pendingItem = this.createPendingItem()\n\t\tthis.maybeCreateNew()\n\t\treturn pendingItem\n\t}\n\n\tpublic release(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.log('Releasing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tif (\n\t\t\t(this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)\n\t\t\t|| (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())\n\t\t) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_old_count++\n\t\t\t\tthis.log('Connection has reached max age or usage and was disposed.')\n\t\t\t})\n\t\t\tthis.maybeCreateNew()\n\t\t\treturn\n\t\t}\n\t\tthis.handleAvailableConnection(poolConnection)\n\t}\n\n\tpublic dispose(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.poolStats.connection_disposed_manual_count++\n\t\tthis.log('Releasing and disposing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tsetImmediate(async () => {\n\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\tthis.log('Connection errored and was disposed.')\n\t\t})\n\t\tthis.maybeCreateNew()\n\t}\n\n\tpublic async end(): Promise<void> {\n\t\tthis.ended = true\n\t\tthis.queue.forEach(it => it.reject(new PoolClosedError()))\n\t\tthis.queue = []\n\t\tconst allConnections = [...this.idle, ...Array.from(this.active)]\n\t\tawait Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))\n\t\tthis.idle = []\n\t\tthis.active.clear()\n\t}\n\n\tpublic async closeIdle(): Promise<void> {\n\t\tthis.log('Disposing all idle connection on request.')\n\t\tconst idle = this.idle\n\t\tthis.idle = []\n\t\tawait Promise.allSettled(idle.map(it => this.disposeConnection(it)))\n\t}\n\n\tpublic getPoolStatus(): PoolStatus {\n\t\treturn {\n\t\t\tmax: this.poolConfig.maxConnections,\n\t\t\tactive: this.active.size,\n\t\t\tidle: this.idle.length,\n\t\t\tpending: this.queue.length,\n\t\t\tconnecting: this.connectingCount,\n\t\t\tstats: this.poolStats,\n\t\t}\n\t}\n\n\tprivate async maybeCreateNew(): Promise<void> {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tif (this.queue.length === 0) {\n\t\t\tthis.log('Not connecting, queue is empty.')\n\t\t\treturn\n\t\t}\n\t\tconst connectingCount = this.connectingCount\n\t\tif (connectingCount >= this.queue.length) {\n\t\t\tthis.log('Not connecting, already establishing connection for all queued items.')\n\t\t\treturn\n\t\t}\n\t\tconst idleCount = this.idle.length\n\t\tif ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {\n\t\t\tthis.log('Not connecting, max connections reached.')\n\t\t\treturn\n\t\t}\n\t\tif (connectingCount >= this.poolConfig.maxConnecting) {\n\t\t\tthis.log('Not connecting, maximum concurrent connection attempts in progress.')\n\t\t\treturn\n\t\t}\n\t\tif (this.remainingRateLimit <= 0) {\n\t\t\tthis.log('Not connecting, rate limit reached.')\n\t\t\treturn\n\t\t}\n\n\t\tthis.log('Creating a new connection')\n\t\tconst client = this.clientFactory()\n\t\tconst poolConnection = new PoolConnection(client)\n\n\t\tclient.on('error', e => {\n\t\t\tthis.log('Client error on idle connection has occurred: ' + e.message)\n\t\t\tthis.poolConfig.logError(new ClientError(e, 'runtime error'))\n\t\t\tthis.poolStats.connection_error_count++\n\n\t\t\tif (!this.active.has(poolConnection)) {\n\t\t\t\tthis.removeIdleConnection(poolConnection)\n\t\t\t\tthis.disposeConnection(poolConnection)\n\t\t\t}\n\t\t})\n\n\t\ttry {\n\t\t\tthis.connectingCount++\n\t\t\tthis.remainingRateLimit--\n\t\t\tthis.poolStats.connection_started_count++\n\n\t\t\tawait client.connect()\n\n\t\t\tthis.poolStats.connection_established_count++\n\t\t\tthis.connectingCount--\n\n\t\t\tthis.log('Connection established')\n\n\t\t\tif (this.ended) {\n\t\t\t\treturn this.disposeConnection(poolConnection)\n\t\t\t}\n\n\t\t\tthis.handleAvailableConnection(poolConnection)\n\t\t\tthis.maybeCreateNew()\n\t\t} catch (e: any) {\n\t\t\tthis.log('Connection error occurred: ' + e.message)\n\t\t\tthis.disposeConnection(poolConnection)\n\n\t\t\tif (\n\t\t\t\te.code === ClientErrorCodes.TOO_MANY_CONNECTIONS\n\t\t\t\t|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting\n\t\t\t\t|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105\n\t\t\t\t|| e.code === 'ETIMEDOUT'\n\t\t\t) {\n\t\t\t\tthis.lastRecoverableError = { error: e, time: Date.now() }\n\t\t\t\tthis.poolStats.connection_recoverable_error_count++\n\t\t\t\tthis.log('Recoverable error, retrying in a moment.')\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'recoverable connection error'))\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.connectingCount--\n\t\t\t\t\tthis.log('Retrying')\n\t\t\t\t\tthis.maybeCreateNew()\n\t\t\t\t}, this.poolConfig.reconnectIntervalMs)\n\t\t\t} else {\n\t\t\t\tthis.poolStats.connection_error_count++\n\t\t\t\tthis.connectingCount--\n\t\t\t\tconst clientError = new ClientError(e, 'connection error')\n\t\t\t\tif (this.active.size === 0 && this.queue.length > 0) {\n\t\t\t\t\tconst pendingItem = this.queue.shift()\n\t\t\t\t\tif (!pendingItem) throw new Error()\n\t\t\t\t\tthis.log('Connecting failed, rejecting pending item')\n\t\t\t\t\tpendingItem.reject(clientError)\n\t\t\t\t\tthis.poolStats.item_rejected_count++\n\t\t\t\t} else {\n\t\t\t\t\tthis.log('Connecting failed, emitting error')\n\t\t\t\t\tthis.poolConfig.logError(clientError)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (this.remainingRateLimit === 0) {\n\t\t\t\t\tthis.log('Rate limit renewed.')\n\t\t\t\t}\n\t\t\t\tthis.remainingRateLimit++\n\t\t\t\tthis.maybeCreateNew()\n\t\t\t}, this.poolConfig.rateLimitPeriodMs)\n\t\t}\n\t}\n\n\tprivate createPendingItem(): Promise<PoolConnection> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tconst acquireTimeoutError = new AcquireTimeoutError(\n\t\t\t\t\tthis.lastRecoverableError && this.lastRecoverableError.time > item.createdAt\n\t\t\t\t\t\t? this.lastRecoverableError.error\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\titem.reject(acquireTimeoutError)\n\t\t\t\tconst index = this.queue.indexOf(item)\n\t\t\t\tif (index > -1) {\n\t\t\t\t\tthis.queue.splice(index, 1)\n\t\t\t\t}\n\t\t\t\tthis.poolStats.item_timeout_count++\n\t\t\t\tthis.log('Queued item timed out')\n\t\t\t}, this.poolConfig.acquireTimeoutMs)\n\n\t\t\tconst item = new PendingItem(it => {\n\t\t\t\tconst duration = Date.now() - item.createdAt\n\t\t\t\tconst isNew = it.uses === 0\n\t\t\t\tthis.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)\n\n\t\t\t\tif (isNew) {\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_sum += duration\n\t\t\t\t} else {\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_sum += duration\n\t\t\t\t}\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve(it)\n\t\t\t}, it => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\treject(it)\n\t\t\t})\n\n\t\t\tthis.poolStats.item_queued_count++\n\t\t\tthis.queue.push(item)\n\t\t\tthis.log(`Item added to a queue.`)\n\t\t})\n\t}\n\n\tprivate handleAvailableConnection(poolConnection: PoolConnection) {\n\t\tconst item = this.queue.shift()\n\t\tconst isNew = poolConnection.uses === 0\n\t\tif (!isNew) {\n\t\t\tthis.poolStats.connection_released_count++\n\t\t}\n\t\tif (item) {\n\t\t\tthis.active.add(poolConnection)\n\t\t\titem.resolve(poolConnection)\n\t\t\tif (!isNew) {\n\t\t\t\tthis.poolStats.connection_reused_immediately_count++\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\treturn\n\t\t}\n\t\tif (isNew) {\n\t\t\tthis.poolStats.connection_established_idle_count++\n\t\t}\n\t\tif (this.idle.length >= this.poolConfig.maxIdle) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_idle_max_count++\n\t\t\t\tthis.log('Too many idle connections, connection disposed.')\n\t\t\t})\n\t\t} else {\n\t\t\tpoolConnection.timerId = setTimeout(async () => {\n\t\t\t\tif (this.removeIdleConnection(poolConnection)) {\n\t\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\t\tthis.poolStats.connection_disposed_idle_timeout_count++\n\t\t\t\t\tthis.log('Idle connection disposed after timeout.')\n\t\t\t\t}\n\t\t\t}, this.poolConfig.idleTimeoutMs)\n\t\t\tthis.idle.push(poolConnection)\n\t\t\tthis.log('Connection is idle and available.')\n\t\t}\n\t}\n\n\tprivate removeIdleConnection(poolConnection: PoolConnection) {\n\t\tconst index = this.idle.indexOf(poolConnection)\n\t\tif (index > -1) {\n\t\t\tthis.idle.splice(index, 1)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate async disposeConnection(connection: PoolConnection) {\n\t\tif (connection.disposed) {\n\t\t\tthrow new PoolError('Connection is already disposed')\n\t\t}\n\t\tconnection.disposed = true\n\t\tconst doEnd = async () => {\n\t\t\ttry {\n\t\t\t\tawait connection.client.end()\n\t\t\t} catch (e: any) {\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'disposal error'))\n\t\t\t}\n\t\t}\n\t\tawait Promise.race([\n\t\t\tdoEnd(),\n\t\t\tnew Promise(resolve => setTimeout(resolve, 5_000)),\n\t\t])\n\t}\n\n\tprivate log(message: string) {\n\t\tif (!this.poolConfig.log) return\n\t\tconst poolStatus = this.getPoolStatus()\n\t\tthis.poolConfig.log(message, poolStatus)\n\t}\n}\n\nexport { Pool }\n\nexport class PoolError extends DatabaseError {\n}\n\nexport class AcquireTimeoutError extends PoolError {\n\tconstructor(previous: any) {\n\t\tsuper('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)\n\t}\n}\n\nexport class PoolClosedError extends PoolError {\n\tconstructor() {\n\t\tsuper('Pool is already closed')\n\t}\n}\n"],"names":[],"mappings":";;;;;;AAsDO,MAAM,uBAAuB;AAAA,EACnC,0BAA0B;AAAA,EAC1B,8BAA8B;AAAA,EAC9B,oCAAoC;AAAA,EACpC,wBAAwB;AAAA,EACxB,wCAAwC;AAAA,EACxC,oCACC;AAAA,EACD,+BAA+B;AAAA,EAC/B,kCAAkC;AAAA,EAClC,2BAA2B;AAAA,EAC3B,qCAAqC;AAAA,EACrC,+BAA+B;AAAA,EAE/B,mCAAmC;AAAA,EAEnC,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EAErB,4BAA4B;AAAA,EAC5B,0BAA0B;AAAA,EAC1B,iCAAiC;AAAA,EACjC,+BAA+B;AAChC;AAEA,MAAM,eAAe;AAAA,EAMpB,YACiB,QACf;AADe,SAAA,SAAA;AANjB,kBAAA,MAAO,YAAW,KAAA;AAClB,kBAAA,MAAO,QAAO,CAAA;AACd,kBAAA,MAAO,aAAY,KAAK,IAAA,CAAI;AAC5B,kBAAA,MAAO,WAAgD,IAAA;AAAA,EAKvD;AACD;AAEA,MAAM,YAAY;AAAA,EAGjB,YACQ,SACA,QACN;AA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AAc,kBAAkB,YAA4B;AAC3D,QAAI,WAAW,UAAU;AACxB,YAAM,IAAI,UAAU,gCAAgC;AAAA,IACrD;AACA,eAAW,WAAW;AACtB,UAAM,QAAQ,YAAY;AACzB,UAAI;AACH,cAAM,WAAW,OAAO,IAAA;AAAA,MACzB,SAAS,GAAQ;AAChB,aAAK,WAAW,SAAS,IAAI,YAAY,GAAG,gBAAgB,CAAC;AAAA,MAC9D;AAAA,IACD;AACA,UAAM,QAAQ,KAAK;AAAA,MAClB,MAAA;AAAA,MACA,IAAI,QAAQ,CAAA,YAAW,WAAW,SAAS,GAAK,CAAC;AAAA,IAAA,CACjD;AAAA,EACF;AAAA,EAEQ,IAAI,SAAiB;AAC5B,QAAI,CAAC,KAAK,WAAW,IAAK;AAC1B,UAAM,aAAa,KAAK,cAAA;AACxB,SAAK,WAAW,IAAI,SAAS,UAAU;AAAA,EACxC;AACD;AAIO,MAAM,kBAAkB,cAAc;AAC7C;AAEO,MAAM,4BAA4B,UAAU;AAAA,EAClD,YAAY,UAAe;AAC1B,UAAM,oCAAoC,YAAY,aAAa,WAAW,iBAAiB,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,EAClI;AACD;AAEO,MAAM,wBAAwB,UAAU;AAAA,EAC9C,cAAc;AACb,UAAM,wBAAwB;AAAA,EAC/B;AACD;"}
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const sql = require("../utils/sql.cjs");
4
+ require("../builders/Compiler.cjs");
5
+ require("../Literal.cjs");
6
+ require("../builders/SelectBuilder.cjs");
7
+ require("../builders/internal/With.cjs");
8
+ require("../builders/internal/Where.cjs");
9
+ require("./EventManager.cjs");
10
+ require("@contember/queryable");
11
+ const errors = require("./errors.cjs");
12
+ require("./Connection.cjs");
13
+ require("node:timers");
14
+ require("../utils/Mutex.cjs");
15
+ require("pg");
16
+ var __defProp = Object.defineProperty;
17
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
18
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
19
+ class Transaction {
20
+ constructor(connection, savepointManager = new SavepointState(), state = new TransactionLikeState()) {
21
+ this.connection = connection;
22
+ this.savepointManager = savepointManager;
23
+ this.state = state;
24
+ __publicField(this, "on");
25
+ this.on = this.connection.on.bind(this.connection);
26
+ }
27
+ get isClosed() {
28
+ return this.state.isClosed;
29
+ }
30
+ get eventManager() {
31
+ return this.connection.eventManager;
32
+ }
33
+ async scope(callback, { eventManager = this.eventManager } = {}) {
34
+ return await this.connection.scope(async (connection) => {
35
+ return await callback(new Transaction(connection, this.savepointManager, this.state));
36
+ }, { eventManager });
37
+ }
38
+ async transaction(callback, options) {
39
+ return await this.scope(async (connection) => {
40
+ return await this.savepointManager.execute(connection, callback);
41
+ }, options);
42
+ }
43
+ async query(sql2, parameters = [], meta = {}) {
44
+ if (this.isClosed) {
45
+ throw new Error("Transaction is already closed");
46
+ }
47
+ return await this.connection.scope(async (connection) => {
48
+ return connection.query(sql2, parameters, meta);
49
+ }, { eventManager: this.eventManager });
50
+ }
51
+ async rollback() {
52
+ await this.close("ROLLBACK");
53
+ }
54
+ async commit() {
55
+ const commitResult = await this.close("COMMIT");
56
+ if (commitResult.command !== "COMMIT") {
57
+ throw new errors.CannotCommitError("Unexpected commit result: " + commitResult.command);
58
+ }
59
+ }
60
+ async close(command) {
61
+ const result = await this.query(command);
62
+ this.state.close();
63
+ return result;
64
+ }
65
+ }
66
+ class SavePoint {
67
+ constructor(savepointName, savepointManager, connection, state = new TransactionLikeState()) {
68
+ this.savepointName = savepointName;
69
+ this.savepointManager = savepointManager;
70
+ this.connection = connection;
71
+ this.state = state;
72
+ __publicField(this, "on");
73
+ this.on = this.connection.on.bind(this.connection);
74
+ }
75
+ get isClosed() {
76
+ return this.state.isClosed;
77
+ }
78
+ get eventManager() {
79
+ return this.connection.eventManager;
80
+ }
81
+ async scope(callback, { eventManager = this.eventManager } = {}) {
82
+ return this.connection.scope(async (connection) => {
83
+ return await callback(new SavePoint(this.savepointName, this.savepointManager, connection, this.state));
84
+ }, { eventManager });
85
+ }
86
+ async transaction(callback, options = {}) {
87
+ return await this.scope(async (connection) => {
88
+ return await this.savepointManager.execute(connection, callback);
89
+ }, options);
90
+ }
91
+ async query(sql2, parameters = [], meta = {}) {
92
+ if (this.isClosed) {
93
+ throw new Error(`Savepoint ${this.savepointName} is already closed.`);
94
+ }
95
+ return await this.connection.scope((connection) => {
96
+ return connection.query(sql2, parameters, meta);
97
+ }, { eventManager: this.eventManager });
98
+ }
99
+ async rollback() {
100
+ await this.close(`ROLLBACK TO SAVEPOINT ${sql.wrapIdentifier(this.savepointName)}`);
101
+ }
102
+ async commit() {
103
+ await this.close(`RELEASE SAVEPOINT ${sql.wrapIdentifier(this.savepointName)}`);
104
+ }
105
+ async close(sql2) {
106
+ await this.query(sql2);
107
+ this.state.close();
108
+ }
109
+ }
110
+ class TransactionLikeState {
111
+ constructor() {
112
+ __publicField(this, "_isClosed", false);
113
+ }
114
+ get isClosed() {
115
+ return this._isClosed;
116
+ }
117
+ close() {
118
+ this._isClosed = true;
119
+ }
120
+ }
121
+ class SavepointState {
122
+ constructor() {
123
+ __publicField(this, "counter", 1);
124
+ }
125
+ async execute(connection, callback) {
126
+ const savepointName = `savepoint_${this.counter++}`;
127
+ await connection.query(`SAVEPOINT ${sql.wrapIdentifier(savepointName)}`);
128
+ const savepoint = new SavePoint(savepointName, this, connection);
129
+ return await executeTransaction(savepoint, callback);
130
+ }
131
+ }
132
+ const executeTransaction = async (transaction, callback) => {
133
+ try {
134
+ const result = await callback(transaction);
135
+ if (!transaction.isClosed) {
136
+ await transaction.commit();
137
+ }
138
+ return result;
139
+ } catch (e) {
140
+ if (!transaction.isClosed) {
141
+ await transaction.rollback();
142
+ }
143
+ throw e;
144
+ }
145
+ };
146
+ exports.Transaction = Transaction;
147
+ exports.executeTransaction = executeTransaction;
148
+ //# sourceMappingURL=Transaction.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Transaction.cjs","sources":["../../../../../packages/database/src/client/Transaction.ts"],"sourcesContent":["import { Connection } from './Connection'\nimport { EventManager } from './EventManager'\nimport { wrapIdentifier } from '../utils'\nimport { Notification } from 'pg'\nimport { CannotCommitError, DatabaseError } from './errors'\n\nexport class Transaction implements Connection.TransactionLike {\n\tpublic get isClosed(): boolean {\n\t\treturn this.state.isClosed\n\t}\n\n\tpublic on\n\n\tconstructor(\n\t\tprivate readonly connection: Connection.AcquiredConnectionLike,\n\t\tprivate readonly savepointManager = new SavepointState(),\n\t\tprivate readonly state = new TransactionLikeState(),\n\t) {\n\t\tthis.on = this.connection.on.bind(this.connection)\n\t}\n\n\tget eventManager() {\n\t\treturn this.connection.eventManager\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\t{ eventManager = this.eventManager }: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.connection.scope(async connection => {\n\t\t\treturn await callback(new Transaction(connection, this.savepointManager, this.state))\n\t\t}, { eventManager })\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions?: { eventManager?: EventManager },\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await this.savepointManager.execute(connection, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\tif (this.isClosed) {\n\t\t\tthrow new Error('Transaction is already closed')\n\t\t}\n\t\treturn await this.connection.scope(async connection => {\n\t\t\treturn connection.query(sql, parameters, meta)\n\t\t}, { eventManager: this.eventManager })\n\t}\n\n\tasync rollback(): Promise<void> {\n\t\tawait this.close('ROLLBACK')\n\t}\n\n\tasync commit(): Promise<void> {\n\t\tconst commitResult = await this.close('COMMIT')\n\t\tif (commitResult.command !== 'COMMIT') {\n\t\t\tthrow new CannotCommitError('Unexpected commit result: ' + commitResult.command)\n\t\t}\n\t}\n\n\tprivate async close(command: string) {\n\t\tconst result = await this.query(command)\n\t\tthis.state.close()\n\t\treturn result\n\t}\n}\n\nclass SavePoint implements Connection.TransactionLike {\n\tpublic on\n\n\tconstructor(\n\t\tpublic readonly savepointName: string,\n\t\tpublic readonly savepointManager: SavepointState,\n\t\tprivate readonly connection: Connection.AcquiredConnectionLike,\n\t\tprivate readonly state = new TransactionLikeState(),\n\t) {\n\t\tthis.on = this.connection.on.bind(this.connection)\n\t}\n\n\tget isClosed() {\n\t\treturn this.state.isClosed\n\t}\n\n\tget eventManager() {\n\t\treturn this.connection.eventManager\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\t{ eventManager = this.eventManager }: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn this.connection.scope(async connection => {\n\t\t\treturn await callback(new SavePoint(this.savepointName, this.savepointManager, connection, this.state))\n\t\t}, { eventManager })\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await this.savepointManager.execute(connection, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\tif (this.isClosed) {\n\t\t\tthrow new Error(`Savepoint ${this.savepointName} is already closed.`)\n\t\t}\n\t\treturn await this.connection.scope(connection => {\n\t\t\treturn connection.query(sql, parameters, meta)\n\t\t}, { eventManager: this.eventManager })\n\t}\n\n\tasync rollback(): Promise<void> {\n\t\tawait this.close(`ROLLBACK TO SAVEPOINT ${wrapIdentifier(this.savepointName)}`)\n\t}\n\n\tasync commit(): Promise<void> {\n\t\tawait this.close(`RELEASE SAVEPOINT ${wrapIdentifier(this.savepointName)}`)\n\t}\n\n\tprivate async close(sql: string) {\n\t\tawait this.query(sql)\n\t\tthis.state.close()\n\t}\n}\n\nclass TransactionLikeState {\n\tprivate _isClosed = false\n\n\tpublic get isClosed(): boolean {\n\t\treturn this._isClosed\n\t}\n\n\tpublic close(): void {\n\t\tthis._isClosed = true\n\t}\n}\n\nclass SavepointState {\n\tpublic counter = 1\n\n\tpublic async execute<Result>(\n\t\tconnection: Connection.AcquiredConnectionLike,\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t) {\n\t\tconst savepointName = `savepoint_${this.counter++}`\n\n\t\tawait connection.query(`SAVEPOINT ${wrapIdentifier(savepointName)}`)\n\t\tconst savepoint = new SavePoint(savepointName, this, connection)\n\t\treturn await executeTransaction(savepoint, callback)\n\t}\n}\n\nexport const executeTransaction = async <Result>(\n\ttransaction: Connection.TransactionLike,\n\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n) => {\n\ttry {\n\t\tconst result = await callback(transaction)\n\t\tif (!transaction.isClosed) {\n\t\t\tawait transaction.commit()\n\t\t}\n\t\treturn result\n\t} catch (e) {\n\t\tif (!transaction.isClosed) {\n\t\t\tawait transaction.rollback()\n\t\t}\n\t\tthrow e\n\t}\n}\n"],"names":["sql","CannotCommitError","wrapIdentifier"],"mappings":";;;;;;;;;;;;;;;;;;AAMO,MAAM,YAAkD;AAAA,EAO9D,YACkB,YACA,mBAAmB,IAAI,kBACvB,QAAQ,IAAI,wBAC5B;AAHgB,SAAA,aAAA;AACA,SAAA,mBAAA;AACA,SAAA,QAAA;AALlB,kBAAA,MAAO,IAAA;AAON,SAAK,KAAK,KAAK,WAAW,GAAG,KAAK,KAAK,UAAU;AAAA,EAClD;AAAA,EAZA,IAAW,WAAoB;AAC9B,WAAO,KAAK,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