turbine-orm 0.93.1 → 0.94.0

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 (619) hide show
  1. package/README.md +49 -23
  2. package/dist/adapters/cockroachdb.d.ts +3 -3
  3. package/dist/adapters/cockroachdb.js +7 -11
  4. package/dist/adapters/index.d.ts +1 -1
  5. package/dist/adapters/yugabytedb.js +1 -1
  6. package/dist/better-sqlite3.d.ts +132 -0
  7. package/dist/better-sqlite3.js +303 -0
  8. package/dist/catalog-metadata.d.ts +250 -0
  9. package/dist/catalog-metadata.js +730 -0
  10. package/dist/cjs/adapters/cockroachdb.d.ts +3 -3
  11. package/dist/cjs/adapters/cockroachdb.js +7 -11
  12. package/dist/cjs/adapters/index.d.ts +1 -1
  13. package/dist/cjs/adapters/yugabytedb.js +1 -1
  14. package/dist/cjs/better-sqlite3.d.ts +132 -0
  15. package/dist/cjs/better-sqlite3.js +311 -0
  16. package/dist/cjs/catalog-metadata.d.ts +250 -0
  17. package/dist/cjs/catalog-metadata.js +747 -0
  18. package/dist/cjs/cli/compile-query.d.ts +6 -3
  19. package/dist/cjs/cli/compile-query.js +24 -3
  20. package/dist/cjs/cli/config.d.ts +35 -10
  21. package/dist/cjs/cli/config.js +173 -42
  22. package/dist/cjs/cli/d1-config.d.ts +14 -0
  23. package/dist/cjs/cli/d1-config.js +9 -0
  24. package/dist/cjs/cli/d1-local.d.ts +31 -0
  25. package/dist/cjs/cli/d1-local.js +298 -0
  26. package/dist/cjs/cli/d1-migrations.d.ts +16 -0
  27. package/dist/cjs/cli/d1-migrations.js +156 -0
  28. package/dist/cjs/cli/d1-project.d.ts +23 -0
  29. package/dist/cjs/cli/d1-project.js +314 -0
  30. package/dist/cjs/cli/d1-seed.d.ts +35 -0
  31. package/dist/cjs/cli/d1-seed.js +220 -0
  32. package/dist/cjs/cli/destructive.js +1 -2
  33. package/dist/cjs/cli/error-catalog.d.ts +3 -3
  34. package/dist/cjs/cli/error-catalog.js +21 -3
  35. package/dist/cjs/cli/index.d.ts +13 -8
  36. package/dist/cjs/cli/index.js +503 -71
  37. package/dist/cjs/cli/libsql-migrate-command.d.ts +5 -0
  38. package/dist/cjs/cli/libsql-migrate-command.js +82 -0
  39. package/dist/cjs/cli/libsql-migrate-status.d.ts +33 -0
  40. package/dist/cjs/cli/libsql-migrate-status.js +189 -0
  41. package/dist/cjs/cli/libsql-migrate.d.ts +14 -0
  42. package/dist/cjs/cli/libsql-migrate.js +522 -0
  43. package/dist/cjs/cli/libsql-project-config.d.ts +11 -0
  44. package/dist/cjs/cli/libsql-project-config.js +59 -0
  45. package/dist/cjs/cli/libsql-project.d.ts +52 -0
  46. package/dist/cjs/cli/libsql-project.js +409 -0
  47. package/dist/cjs/cli/libsql-seed-command.d.ts +29 -0
  48. package/dist/cjs/cli/libsql-seed-command.js +93 -0
  49. package/dist/cjs/cli/loader.d.ts +6 -5
  50. package/dist/cjs/cli/loader.js +53 -9
  51. package/dist/cjs/cli/mcp.d.ts +16 -1
  52. package/dist/cjs/cli/mcp.js +219 -125
  53. package/dist/cjs/cli/migrate.d.ts +2 -2
  54. package/dist/cjs/cli/migrate.js +29 -14
  55. package/dist/cjs/cli/mssql-doctor.d.ts +44 -0
  56. package/dist/cjs/cli/mssql-doctor.js +277 -0
  57. package/dist/cjs/cli/mssql-migrate-command.d.ts +9 -0
  58. package/dist/cjs/cli/mssql-migrate-command.js +230 -0
  59. package/dist/cjs/cli/mssql-migrate-connection.d.ts +51 -0
  60. package/dist/cjs/cli/mssql-migrate-connection.js +255 -0
  61. package/dist/cjs/cli/mssql-migrate-sql.d.ts +12 -0
  62. package/dist/cjs/cli/mssql-migrate-sql.js +282 -0
  63. package/dist/cjs/cli/mssql-migrate.d.ts +45 -0
  64. package/dist/cjs/cli/mssql-migrate.js +296 -0
  65. package/dist/cjs/cli/mssql-project.d.ts +34 -0
  66. package/dist/cjs/cli/mssql-project.js +171 -0
  67. package/dist/cjs/cli/mssql-seed.d.ts +7 -0
  68. package/dist/cjs/cli/mssql-seed.js +78 -0
  69. package/dist/cjs/cli/mssql-tools.d.ts +37 -0
  70. package/dist/cjs/cli/mssql-tools.js +354 -0
  71. package/dist/cjs/cli/mysql-doctor.d.ts +48 -0
  72. package/dist/cjs/cli/mysql-doctor.js +323 -0
  73. package/dist/cjs/cli/mysql-migrate-command.d.ts +7 -0
  74. package/dist/cjs/cli/mysql-migrate-command.js +290 -0
  75. package/dist/cjs/cli/mysql-migrate-sql.d.ts +18 -0
  76. package/dist/cjs/cli/mysql-migrate-sql.js +166 -0
  77. package/dist/cjs/cli/mysql-migrate.d.ts +77 -0
  78. package/dist/cjs/cli/mysql-migrate.js +619 -0
  79. package/dist/cjs/cli/mysql-project.d.ts +49 -0
  80. package/dist/cjs/cli/mysql-project.js +284 -0
  81. package/dist/cjs/cli/mysql-push-command.d.ts +7 -0
  82. package/dist/cjs/cli/mysql-push-command.js +94 -0
  83. package/dist/cjs/cli/mysql-push.d.ts +15 -0
  84. package/dist/cjs/cli/mysql-push.js +98 -0
  85. package/dist/cjs/cli/mysql-schema-command.d.ts +5 -0
  86. package/dist/cjs/cli/mysql-schema-command.js +58 -0
  87. package/dist/cjs/cli/mysql-schema-ddl.d.ts +37 -0
  88. package/dist/cjs/cli/mysql-schema-ddl.js +234 -0
  89. package/dist/cjs/cli/mysql-schema-snapshot.d.ts +21 -0
  90. package/dist/cjs/cli/mysql-schema-snapshot.js +127 -0
  91. package/dist/cjs/cli/mysql-schema.d.ts +27 -0
  92. package/dist/cjs/cli/mysql-schema.js +206 -0
  93. package/dist/cjs/cli/mysql-seed-loader.cjs +58 -0
  94. package/dist/cjs/cli/mysql-seed-loader.d.cts +3 -0
  95. package/dist/cjs/cli/mysql-seed.d.ts +6 -0
  96. package/dist/cjs/cli/mysql-seed.js +83 -0
  97. package/dist/cjs/cli/mysql-tools.d.ts +44 -0
  98. package/dist/cjs/cli/mysql-tools.js +336 -0
  99. package/dist/cjs/cli/no-follow.d.ts +29 -0
  100. package/dist/cjs/cli/no-follow.js +73 -0
  101. package/dist/cjs/cli/pii-predicate-guard.d.ts +1 -1
  102. package/dist/cjs/cli/pii-predicate-guard.js +2 -2
  103. package/dist/cjs/cli/pii-tags.d.ts +2 -2
  104. package/dist/cjs/cli/pii-tags.js +1 -1
  105. package/dist/cjs/cli/prisma-schema.js +2 -2
  106. package/dist/cjs/cli/sql-statements.d.ts +1 -1
  107. package/dist/cjs/cli/sql-statements.js +1 -1
  108. package/dist/cjs/cli/sqlite-doctor.d.ts +35 -0
  109. package/dist/cjs/cli/sqlite-doctor.js +400 -0
  110. package/dist/cjs/cli/sqlite-migrate-command.d.ts +4 -0
  111. package/dist/cjs/cli/sqlite-migrate-command.js +175 -0
  112. package/dist/cjs/cli/sqlite-migrate.d.ts +61 -0
  113. package/dist/cjs/cli/sqlite-migrate.js +692 -0
  114. package/dist/cjs/cli/sqlite-project.d.ts +42 -0
  115. package/dist/cjs/cli/sqlite-project.js +254 -0
  116. package/dist/cjs/cli/sqlite-schema-command.d.ts +4 -0
  117. package/dist/cjs/cli/sqlite-schema-command.js +82 -0
  118. package/dist/cjs/cli/sqlite-schema-ddl.d.ts +25 -0
  119. package/dist/cjs/cli/sqlite-schema-ddl.js +252 -0
  120. package/dist/cjs/cli/sqlite-schema.d.ts +25 -0
  121. package/dist/cjs/cli/sqlite-schema.js +334 -0
  122. package/dist/cjs/cli/sqlite-seed.d.ts +4 -0
  123. package/dist/cjs/cli/sqlite-seed.js +94 -0
  124. package/dist/cjs/cli/sqlite-tools.d.ts +24 -0
  125. package/dist/cjs/cli/sqlite-tools.js +169 -0
  126. package/dist/cjs/cli/studio.js +9 -9
  127. package/dist/cjs/cli/tool-capabilities.d.ts +72 -0
  128. package/dist/cjs/cli/tool-capabilities.js +120 -0
  129. package/dist/cjs/cli/tool-command.d.ts +11 -0
  130. package/dist/cjs/cli/tool-command.js +49 -0
  131. package/dist/cjs/cli/ui.d.ts +1 -1
  132. package/dist/cjs/cli/ui.js +1 -1
  133. package/dist/cjs/client.d.ts +20 -20
  134. package/dist/cjs/client.js +65 -344
  135. package/dist/cjs/connection-url.d.ts +1 -1
  136. package/dist/cjs/connection-url.js +1 -1
  137. package/dist/cjs/core.d.ts +58 -0
  138. package/dist/cjs/core.js +225 -0
  139. package/dist/cjs/d1/catalog-metadata.d.ts +5 -0
  140. package/dist/cjs/d1/catalog-metadata.js +230 -0
  141. package/dist/cjs/d1/catalog.d.ts +15 -0
  142. package/dist/cjs/d1/catalog.js +88 -0
  143. package/dist/cjs/d1/generate.d.ts +8 -0
  144. package/dist/cjs/d1/generate.js +163 -0
  145. package/dist/cjs/d1/introspect.d.ts +21 -0
  146. package/dist/cjs/d1/introspect.js +74 -0
  147. package/dist/cjs/d1/migrate.d.ts +29 -0
  148. package/dist/cjs/d1/migrate.js +222 -0
  149. package/dist/cjs/d1/migrations/sql.d.ts +2 -0
  150. package/dist/cjs/d1/migrations/sql.js +109 -0
  151. package/dist/cjs/d1/pool.d.ts +14 -0
  152. package/dist/cjs/d1/pool.js +90 -0
  153. package/dist/cjs/d1/sql.d.ts +5 -0
  154. package/dist/cjs/d1/sql.js +140 -0
  155. package/dist/cjs/d1/sqlite-dialect.d.ts +16 -0
  156. package/dist/cjs/d1/sqlite-dialect.js +579 -0
  157. package/dist/cjs/d1/types.d.ts +29 -0
  158. package/dist/cjs/d1/types.js +2 -0
  159. package/dist/cjs/d1.d.ts +53 -0
  160. package/dist/cjs/d1.js +220 -0
  161. package/dist/cjs/dialect.d.ts +33 -5
  162. package/dist/cjs/dialect.js +8 -6
  163. package/dist/cjs/errors.d.ts +38 -1
  164. package/dist/cjs/errors.js +72 -18
  165. package/dist/cjs/generate.d.ts +19 -3
  166. package/dist/cjs/generate.js +330 -97
  167. package/dist/cjs/global-filters-config.js +4 -4
  168. package/dist/cjs/index-advisor.js +6 -6
  169. package/dist/cjs/index.d.ts +1 -1
  170. package/dist/cjs/index.js +3 -2
  171. package/dist/cjs/introspect.d.ts +59 -356
  172. package/dist/cjs/introspect.js +158 -984
  173. package/dist/cjs/libsql/bindings.d.ts +2 -0
  174. package/dist/cjs/libsql/bindings.js +78 -0
  175. package/dist/cjs/libsql/dialect.d.ts +3 -0
  176. package/dist/cjs/libsql/dialect.js +48 -0
  177. package/dist/cjs/libsql/generate.d.ts +4 -0
  178. package/dist/cjs/libsql/generate.js +56 -0
  179. package/dist/cjs/libsql/introspect.d.ts +16 -0
  180. package/dist/cjs/libsql/introspect.js +295 -0
  181. package/dist/cjs/libsql/pool.d.ts +42 -0
  182. package/dist/cjs/libsql/pool.js +275 -0
  183. package/dist/cjs/libsql/seed-cleanup.d.ts +2 -0
  184. package/dist/cjs/libsql/seed-cleanup.js +19 -0
  185. package/dist/cjs/libsql/values.d.ts +20 -0
  186. package/dist/cjs/libsql/values.js +75 -0
  187. package/dist/cjs/libsql-seed.d.ts +19 -0
  188. package/dist/cjs/libsql-seed.js +50 -0
  189. package/dist/cjs/libsql.d.ts +28 -0
  190. package/dist/cjs/libsql.js +88 -0
  191. package/dist/cjs/live-query.d.ts +33 -0
  192. package/dist/cjs/live-query.js +172 -0
  193. package/dist/cjs/log-codes.d.ts +1 -1
  194. package/dist/cjs/log-codes.js +4 -0
  195. package/dist/cjs/mssql-seed.d.ts +27 -0
  196. package/dist/cjs/mssql-seed.js +118 -0
  197. package/dist/cjs/mssql.d.ts +7 -7
  198. package/dist/cjs/mssql.js +365 -53
  199. package/dist/cjs/mysql-seed.d.ts +25 -0
  200. package/dist/cjs/mysql-seed.js +169 -0
  201. package/dist/cjs/mysql.d.ts +18 -6
  202. package/dist/cjs/mysql.js +602 -94
  203. package/dist/cjs/neon-http/client.d.ts +95 -0
  204. package/dist/cjs/neon-http/client.js +291 -0
  205. package/dist/cjs/neon-http/sql.d.ts +3 -0
  206. package/dist/cjs/neon-http/sql.js +116 -0
  207. package/dist/cjs/neon-http.d.ts +5 -0
  208. package/dist/cjs/neon-http.js +8 -0
  209. package/dist/cjs/neon-ws/load-driver.cjs +44 -0
  210. package/dist/cjs/neon-ws/load-driver.d.cts +9 -0
  211. package/dist/cjs/neon-ws/recovery.d.ts +14 -0
  212. package/dist/cjs/neon-ws/recovery.js +69 -0
  213. package/dist/cjs/neon-ws/snapshot.d.ts +3 -0
  214. package/dist/cjs/neon-ws/snapshot.js +17 -0
  215. package/dist/cjs/neon-ws/transport.d.ts +112 -0
  216. package/dist/cjs/neon-ws/transport.js +290 -0
  217. package/dist/cjs/neon-ws.d.ts +26 -0
  218. package/dist/cjs/neon-ws.js +189 -0
  219. package/dist/cjs/nested-write.d.ts +34 -3
  220. package/dist/cjs/nested-write.js +117 -24
  221. package/dist/cjs/notification-hub/consumer.d.ts +22 -0
  222. package/dist/cjs/notification-hub/consumer.js +111 -0
  223. package/dist/cjs/notification-hub.d.ts +41 -0
  224. package/dist/cjs/notification-hub.js +373 -0
  225. package/dist/cjs/pg-catalog-text.d.ts +96 -0
  226. package/dist/cjs/pg-catalog-text.js +213 -0
  227. package/dist/cjs/pg-types.d.ts +46 -2
  228. package/dist/cjs/pipeline-submittable.d.ts +15 -5
  229. package/dist/cjs/pipeline-submittable.js +103 -48
  230. package/dist/cjs/pipeline.d.ts +5 -2
  231. package/dist/cjs/pipeline.js +111 -41
  232. package/dist/cjs/plan-divergence.d.ts +1 -1
  233. package/dist/cjs/plan-divergence.js +1 -1
  234. package/dist/cjs/powdb-introspect.d.ts +1 -1
  235. package/dist/cjs/powdb-introspect.js +5 -5
  236. package/dist/cjs/powdb-shared.d.ts +5 -5
  237. package/dist/cjs/powdb-shared.js +6 -5
  238. package/dist/cjs/powdb.d.ts +28 -10
  239. package/dist/cjs/powdb.js +80 -28
  240. package/dist/cjs/powql.d.ts +50 -28
  241. package/dist/cjs/powql.js +47 -33
  242. package/dist/cjs/prisma-compat.js +4 -5
  243. package/dist/cjs/prisma-schema-fingerprint.d.ts +1 -1
  244. package/dist/cjs/prisma-schema-fingerprint.js +1 -1
  245. package/dist/cjs/query/aggregates.d.ts +0 -13
  246. package/dist/cjs/query/aggregates.js +105 -238
  247. package/dist/cjs/query/batched-loader.d.ts +1 -1
  248. package/dist/cjs/query/batched-loader.js +18 -20
  249. package/dist/cjs/query/builder.d.ts +108 -144
  250. package/dist/cjs/query/builder.js +592 -893
  251. package/dist/cjs/query/compound-unique.d.ts +18 -3
  252. package/dist/cjs/query/compound-unique.js +110 -43
  253. package/dist/cjs/query/cursor-tuple.d.ts +17 -0
  254. package/dist/cjs/query/cursor-tuple.js +121 -0
  255. package/dist/cjs/query/expr.d.ts +2 -0
  256. package/dist/cjs/query/expr.js +40 -23
  257. package/dist/cjs/query/filters.d.ts +39 -7
  258. package/dist/cjs/query/filters.js +77 -19
  259. package/dist/cjs/query/normalize-args.d.ts +1 -1
  260. package/dist/cjs/query/normalize-args.js +7 -5
  261. package/dist/cjs/query/option-surface.d.ts +1 -1
  262. package/dist/cjs/query/option-surface.js +5 -3
  263. package/dist/cjs/query/pg-type-parsers.d.ts +126 -0
  264. package/dist/cjs/query/pg-type-parsers.js +306 -0
  265. package/dist/cjs/query/relation-names.d.ts +4 -2
  266. package/dist/cjs/query/relation-names.js +21 -12
  267. package/dist/cjs/query/relations.d.ts +19 -7
  268. package/dist/cjs/query/relations.js +329 -260
  269. package/dist/cjs/query/row-lock.js +3 -3
  270. package/dist/cjs/query/sql-comment.js +3 -3
  271. package/dist/cjs/query/stream-idle.d.ts +11 -1
  272. package/dist/cjs/query/stream-idle.js +53 -13
  273. package/dist/cjs/query/stream-signal.d.ts +21 -0
  274. package/dist/cjs/query/stream-signal.js +132 -0
  275. package/dist/cjs/query/temporal-parsers.d.ts +101 -0
  276. package/dist/cjs/query/temporal-parsers.js +362 -0
  277. package/dist/cjs/query/types.d.ts +67 -20
  278. package/dist/cjs/query/utils.d.ts +2 -878
  279. package/dist/cjs/query/utils.js +25 -2058
  280. package/dist/cjs/query/warn-registry.d.ts +1 -1
  281. package/dist/cjs/query/warn-registry.js +1 -1
  282. package/dist/cjs/query/where-compile.d.ts +4 -1
  283. package/dist/cjs/query/where-compile.js +18 -14
  284. package/dist/cjs/query/where.d.ts +14 -7
  285. package/dist/cjs/query/where.js +244 -436
  286. package/dist/cjs/query/writes.d.ts +33 -2
  287. package/dist/cjs/query/writes.js +104 -77
  288. package/dist/cjs/query-utils.d.ts +687 -0
  289. package/dist/cjs/query-utils.js +1444 -0
  290. package/dist/cjs/realtime.d.ts +1 -1
  291. package/dist/cjs/realtime.js +3 -3
  292. package/dist/cjs/schema-builder.js +2 -2
  293. package/dist/cjs/schema-metadata.d.ts +13 -3
  294. package/dist/cjs/schema-metadata.js +33 -5
  295. package/dist/cjs/schema-sql.d.ts +15 -24
  296. package/dist/cjs/schema-sql.js +53 -63
  297. package/dist/cjs/schema.d.ts +37 -2
  298. package/dist/cjs/schema.js +29 -2
  299. package/dist/cjs/seed.js +5 -5
  300. package/dist/cjs/serverless.d.ts +24 -71
  301. package/dist/cjs/serverless.js +24 -71
  302. package/dist/cjs/sql.d.ts +111 -0
  303. package/dist/cjs/sql.js +335 -0
  304. package/dist/cjs/sqlite-seed.d.ts +17 -0
  305. package/dist/cjs/sqlite-seed.js +31 -0
  306. package/dist/cjs/sqlite.d.ts +32 -19
  307. package/dist/cjs/sqlite.js +865 -652
  308. package/dist/cjs/supplied-pool-types.js +10 -9
  309. package/dist/cjs/transaction-control.js +6 -1
  310. package/dist/cjs/transaction-outcome.d.ts +61 -0
  311. package/dist/cjs/transaction-outcome.js +239 -0
  312. package/dist/cjs/transaction-state.d.ts +82 -13
  313. package/dist/cjs/transaction-state.js +222 -56
  314. package/dist/cjs/transaction-transport.d.ts +38 -0
  315. package/dist/cjs/transaction-transport.js +157 -0
  316. package/dist/cjs/typed-sql.d.ts +1 -1
  317. package/dist/cjs/typed-sql.js +1 -1
  318. package/dist/cli/compile-query.d.ts +6 -3
  319. package/dist/cli/compile-query.js +25 -4
  320. package/dist/cli/config.d.ts +35 -10
  321. package/dist/cli/config.js +170 -43
  322. package/dist/cli/d1-config.d.ts +14 -0
  323. package/dist/cli/d1-config.js +6 -0
  324. package/dist/cli/d1-local.d.ts +31 -0
  325. package/dist/cli/d1-local.js +285 -0
  326. package/dist/cli/d1-migrations.d.ts +16 -0
  327. package/dist/cli/d1-migrations.js +151 -0
  328. package/dist/cli/d1-project.d.ts +23 -0
  329. package/dist/cli/d1-project.js +304 -0
  330. package/dist/cli/d1-seed.d.ts +35 -0
  331. package/dist/cli/d1-seed.js +213 -0
  332. package/dist/cli/destructive.js +1 -2
  333. package/dist/cli/error-catalog.d.ts +3 -3
  334. package/dist/cli/error-catalog.js +21 -3
  335. package/dist/cli/index.d.ts +13 -8
  336. package/dist/cli/index.js +500 -71
  337. package/dist/cli/libsql-migrate-command.d.ts +5 -0
  338. package/dist/cli/libsql-migrate-command.js +77 -0
  339. package/dist/cli/libsql-migrate-status.d.ts +33 -0
  340. package/dist/cli/libsql-migrate-status.js +182 -0
  341. package/dist/cli/libsql-migrate.d.ts +14 -0
  342. package/dist/cli/libsql-migrate.js +516 -0
  343. package/dist/cli/libsql-project-config.d.ts +11 -0
  344. package/dist/cli/libsql-project-config.js +55 -0
  345. package/dist/cli/libsql-project.d.ts +52 -0
  346. package/dist/cli/libsql-project.js +391 -0
  347. package/dist/cli/libsql-seed-command.d.ts +29 -0
  348. package/dist/cli/libsql-seed-command.js +85 -0
  349. package/dist/cli/loader.d.ts +6 -5
  350. package/dist/cli/loader.js +50 -9
  351. package/dist/cli/mcp.d.ts +16 -1
  352. package/dist/cli/mcp.js +220 -127
  353. package/dist/cli/migrate.d.ts +2 -2
  354. package/dist/cli/migrate.js +29 -14
  355. package/dist/cli/mssql-doctor.d.ts +44 -0
  356. package/dist/cli/mssql-doctor.js +237 -0
  357. package/dist/cli/mssql-migrate-command.d.ts +9 -0
  358. package/dist/cli/mssql-migrate-command.js +192 -0
  359. package/dist/cli/mssql-migrate-connection.d.ts +51 -0
  360. package/dist/cli/mssql-migrate-connection.js +245 -0
  361. package/dist/cli/mssql-migrate-sql.d.ts +12 -0
  362. package/dist/cli/mssql-migrate-sql.js +275 -0
  363. package/dist/cli/mssql-migrate.d.ts +45 -0
  364. package/dist/cli/mssql-migrate.js +290 -0
  365. package/dist/cli/mssql-project.d.ts +34 -0
  366. package/dist/cli/mssql-project.js +160 -0
  367. package/dist/cli/mssql-seed.d.ts +7 -0
  368. package/dist/cli/mssql-seed.js +73 -0
  369. package/dist/cli/mssql-tools.d.ts +37 -0
  370. package/dist/cli/mssql-tools.js +341 -0
  371. package/dist/cli/mysql-doctor.d.ts +48 -0
  372. package/dist/cli/mysql-doctor.js +316 -0
  373. package/dist/cli/mysql-migrate-command.d.ts +7 -0
  374. package/dist/cli/mysql-migrate-command.js +285 -0
  375. package/dist/cli/mysql-migrate-sql.d.ts +18 -0
  376. package/dist/cli/mysql-migrate-sql.js +162 -0
  377. package/dist/cli/mysql-migrate.d.ts +77 -0
  378. package/dist/cli/mysql-migrate.js +606 -0
  379. package/dist/cli/mysql-project.d.ts +49 -0
  380. package/dist/cli/mysql-project.js +272 -0
  381. package/dist/cli/mysql-push-command.d.ts +7 -0
  382. package/dist/cli/mysql-push-command.js +89 -0
  383. package/dist/cli/mysql-push.d.ts +15 -0
  384. package/dist/cli/mysql-push.js +95 -0
  385. package/dist/cli/mysql-schema-command.d.ts +5 -0
  386. package/dist/cli/mysql-schema-command.js +54 -0
  387. package/dist/cli/mysql-schema-ddl.d.ts +37 -0
  388. package/dist/cli/mysql-schema-ddl.js +227 -0
  389. package/dist/cli/mysql-schema-snapshot.d.ts +21 -0
  390. package/dist/cli/mysql-schema-snapshot.js +119 -0
  391. package/dist/cli/mysql-schema.d.ts +27 -0
  392. package/dist/cli/mysql-schema.js +200 -0
  393. package/dist/cli/mysql-seed-loader.cjs +25 -0
  394. package/dist/cli/mysql-seed-loader.d.cts +3 -0
  395. package/dist/cli/mysql-seed.d.ts +6 -0
  396. package/dist/cli/mysql-seed.js +75 -0
  397. package/dist/cli/mysql-tools.d.ts +44 -0
  398. package/dist/cli/mysql-tools.js +290 -0
  399. package/dist/cli/no-follow.d.ts +29 -0
  400. package/dist/cli/no-follow.js +67 -0
  401. package/dist/cli/pii-predicate-guard.d.ts +1 -1
  402. package/dist/cli/pii-predicate-guard.js +2 -2
  403. package/dist/cli/pii-tags.d.ts +2 -2
  404. package/dist/cli/pii-tags.js +1 -1
  405. package/dist/cli/prisma-schema.js +2 -2
  406. package/dist/cli/sql-statements.d.ts +1 -1
  407. package/dist/cli/sql-statements.js +1 -1
  408. package/dist/cli/sqlite-doctor.d.ts +35 -0
  409. package/dist/cli/sqlite-doctor.js +392 -0
  410. package/dist/cli/sqlite-migrate-command.d.ts +4 -0
  411. package/dist/cli/sqlite-migrate-command.js +171 -0
  412. package/dist/cli/sqlite-migrate.d.ts +61 -0
  413. package/dist/cli/sqlite-migrate.js +681 -0
  414. package/dist/cli/sqlite-project.d.ts +42 -0
  415. package/dist/cli/sqlite-project.js +244 -0
  416. package/dist/cli/sqlite-schema-command.d.ts +4 -0
  417. package/dist/cli/sqlite-schema-command.js +79 -0
  418. package/dist/cli/sqlite-schema-ddl.d.ts +25 -0
  419. package/dist/cli/sqlite-schema-ddl.js +248 -0
  420. package/dist/cli/sqlite-schema.d.ts +25 -0
  421. package/dist/cli/sqlite-schema.js +330 -0
  422. package/dist/cli/sqlite-seed.d.ts +4 -0
  423. package/dist/cli/sqlite-seed.js +57 -0
  424. package/dist/cli/sqlite-tools.d.ts +24 -0
  425. package/dist/cli/sqlite-tools.js +163 -0
  426. package/dist/cli/studio.js +9 -9
  427. package/dist/cli/tool-capabilities.d.ts +72 -0
  428. package/dist/cli/tool-capabilities.js +114 -0
  429. package/dist/cli/tool-command.d.ts +11 -0
  430. package/dist/cli/tool-command.js +45 -0
  431. package/dist/cli/ui.d.ts +1 -1
  432. package/dist/cli/ui.js +1 -1
  433. package/dist/client.d.ts +20 -20
  434. package/dist/client.js +62 -341
  435. package/dist/connection-url.d.ts +1 -1
  436. package/dist/connection-url.js +1 -1
  437. package/dist/core.d.ts +58 -0
  438. package/dist/core.js +220 -0
  439. package/dist/d1/catalog-metadata.d.ts +5 -0
  440. package/dist/d1/catalog-metadata.js +227 -0
  441. package/dist/d1/catalog.d.ts +15 -0
  442. package/dist/d1/catalog.js +82 -0
  443. package/dist/d1/generate.d.ts +8 -0
  444. package/dist/d1/generate.js +160 -0
  445. package/dist/d1/introspect.d.ts +21 -0
  446. package/dist/d1/introspect.js +71 -0
  447. package/dist/d1/migrate.d.ts +29 -0
  448. package/dist/d1/migrate.js +217 -0
  449. package/dist/d1/migrations/sql.d.ts +2 -0
  450. package/dist/d1/migrations/sql.js +106 -0
  451. package/dist/d1/pool.d.ts +14 -0
  452. package/dist/d1/pool.js +86 -0
  453. package/dist/d1/sql.d.ts +5 -0
  454. package/dist/d1/sql.js +135 -0
  455. package/dist/d1/sqlite-dialect.d.ts +16 -0
  456. package/dist/d1/sqlite-dialect.js +572 -0
  457. package/dist/d1/types.d.ts +29 -0
  458. package/dist/d1/types.js +1 -0
  459. package/dist/d1.d.ts +53 -0
  460. package/dist/d1.js +215 -0
  461. package/dist/dialect.d.ts +33 -5
  462. package/dist/dialect.js +6 -4
  463. package/dist/errors.d.ts +38 -1
  464. package/dist/errors.js +68 -17
  465. package/dist/generate.d.ts +19 -3
  466. package/dist/generate.js +330 -97
  467. package/dist/global-filters-config.js +2 -2
  468. package/dist/index-advisor.js +1 -1
  469. package/dist/index.d.ts +1 -1
  470. package/dist/index.js +1 -1
  471. package/dist/introspect.d.ts +59 -356
  472. package/dist/introspect.js +116 -943
  473. package/dist/libsql/bindings.d.ts +2 -0
  474. package/dist/libsql/bindings.js +75 -0
  475. package/dist/libsql/dialect.d.ts +3 -0
  476. package/dist/libsql/dialect.js +45 -0
  477. package/dist/libsql/generate.d.ts +4 -0
  478. package/dist/libsql/generate.js +53 -0
  479. package/dist/libsql/introspect.d.ts +16 -0
  480. package/dist/libsql/introspect.js +289 -0
  481. package/dist/libsql/pool.d.ts +42 -0
  482. package/dist/libsql/pool.js +270 -0
  483. package/dist/libsql/seed-cleanup.d.ts +2 -0
  484. package/dist/libsql/seed-cleanup.js +15 -0
  485. package/dist/libsql/values.d.ts +20 -0
  486. package/dist/libsql/values.js +68 -0
  487. package/dist/libsql-seed.d.ts +19 -0
  488. package/dist/libsql-seed.js +46 -0
  489. package/dist/libsql.d.ts +28 -0
  490. package/dist/libsql.js +79 -0
  491. package/dist/live-query.d.ts +33 -0
  492. package/dist/live-query.js +169 -0
  493. package/dist/log-codes.d.ts +1 -1
  494. package/dist/log-codes.js +4 -0
  495. package/dist/mssql-seed.d.ts +27 -0
  496. package/dist/mssql-seed.js +114 -0
  497. package/dist/mssql.d.ts +7 -7
  498. package/dist/mssql.js +366 -54
  499. package/dist/mysql-seed.d.ts +25 -0
  500. package/dist/mysql-seed.js +165 -0
  501. package/dist/mysql.d.ts +18 -6
  502. package/dist/mysql.js +603 -95
  503. package/dist/neon-http/client.d.ts +95 -0
  504. package/dist/neon-http/client.js +286 -0
  505. package/dist/neon-http/sql.d.ts +3 -0
  506. package/dist/neon-http/sql.js +112 -0
  507. package/dist/neon-http.d.ts +5 -0
  508. package/dist/neon-http.js +2 -0
  509. package/dist/neon-ws/load-driver.cjs +11 -0
  510. package/dist/neon-ws/load-driver.d.cts +9 -0
  511. package/dist/neon-ws/recovery.d.ts +14 -0
  512. package/dist/neon-ws/recovery.js +66 -0
  513. package/dist/neon-ws/snapshot.d.ts +3 -0
  514. package/dist/neon-ws/snapshot.js +15 -0
  515. package/dist/neon-ws/transport.d.ts +112 -0
  516. package/dist/neon-ws/transport.js +286 -0
  517. package/dist/neon-ws.d.ts +26 -0
  518. package/dist/neon-ws.js +182 -0
  519. package/dist/nested-write.d.ts +34 -3
  520. package/dist/nested-write.js +114 -22
  521. package/dist/notification-hub/consumer.d.ts +22 -0
  522. package/dist/notification-hub/consumer.js +106 -0
  523. package/dist/notification-hub.d.ts +41 -0
  524. package/dist/notification-hub.js +370 -0
  525. package/dist/pg-catalog-text.d.ts +96 -0
  526. package/dist/pg-catalog-text.js +208 -0
  527. package/dist/pg-types.d.ts +46 -2
  528. package/dist/pipeline-submittable.d.ts +15 -5
  529. package/dist/pipeline-submittable.js +105 -50
  530. package/dist/pipeline.d.ts +5 -2
  531. package/dist/pipeline.js +113 -43
  532. package/dist/plan-divergence.d.ts +1 -1
  533. package/dist/plan-divergence.js +1 -1
  534. package/dist/powdb-introspect.d.ts +1 -1
  535. package/dist/powdb-introspect.js +5 -5
  536. package/dist/powdb-shared.d.ts +5 -5
  537. package/dist/powdb-shared.js +6 -5
  538. package/dist/powdb.d.ts +28 -10
  539. package/dist/powdb.js +80 -28
  540. package/dist/powql.d.ts +50 -28
  541. package/dist/powql.js +49 -35
  542. package/dist/prisma-compat.js +4 -5
  543. package/dist/prisma-schema-fingerprint.d.ts +1 -1
  544. package/dist/prisma-schema-fingerprint.js +1 -1
  545. package/dist/query/aggregates.d.ts +0 -13
  546. package/dist/query/aggregates.js +97 -230
  547. package/dist/query/batched-loader.d.ts +1 -1
  548. package/dist/query/batched-loader.js +5 -7
  549. package/dist/query/builder.d.ts +108 -144
  550. package/dist/query/builder.js +563 -864
  551. package/dist/query/compound-unique.d.ts +18 -3
  552. package/dist/query/compound-unique.js +99 -33
  553. package/dist/query/cursor-tuple.d.ts +17 -0
  554. package/dist/query/cursor-tuple.js +114 -0
  555. package/dist/query/expr.d.ts +2 -0
  556. package/dist/query/expr.js +32 -16
  557. package/dist/query/filters.d.ts +39 -7
  558. package/dist/query/filters.js +69 -14
  559. package/dist/query/normalize-args.d.ts +1 -1
  560. package/dist/query/normalize-args.js +4 -2
  561. package/dist/query/option-surface.d.ts +1 -1
  562. package/dist/query/option-surface.js +4 -2
  563. package/dist/query/pg-type-parsers.d.ts +126 -0
  564. package/dist/query/pg-type-parsers.js +296 -0
  565. package/dist/query/relation-names.d.ts +4 -2
  566. package/dist/query/relation-names.js +15 -7
  567. package/dist/query/relations.d.ts +19 -7
  568. package/dist/query/relations.js +293 -227
  569. package/dist/query/row-lock.js +1 -1
  570. package/dist/query/sql-comment.js +1 -1
  571. package/dist/query/stream-idle.d.ts +11 -1
  572. package/dist/query/stream-idle.js +51 -13
  573. package/dist/query/stream-signal.d.ts +21 -0
  574. package/dist/query/stream-signal.js +125 -0
  575. package/dist/query/temporal-parsers.d.ts +101 -0
  576. package/dist/query/temporal-parsers.js +354 -0
  577. package/dist/query/types.d.ts +67 -20
  578. package/dist/query/utils.d.ts +2 -878
  579. package/dist/query/utils.js +5 -2003
  580. package/dist/query/warn-registry.d.ts +1 -1
  581. package/dist/query/warn-registry.js +1 -1
  582. package/dist/query/where-compile.d.ts +4 -1
  583. package/dist/query/where-compile.js +14 -10
  584. package/dist/query/where.d.ts +14 -7
  585. package/dist/query/where.js +236 -430
  586. package/dist/query/writes.d.ts +33 -2
  587. package/dist/query/writes.js +90 -65
  588. package/dist/query-utils.d.ts +687 -0
  589. package/dist/query-utils.js +1390 -0
  590. package/dist/realtime.d.ts +1 -1
  591. package/dist/realtime.js +3 -3
  592. package/dist/schema-builder.js +2 -2
  593. package/dist/schema-metadata.d.ts +13 -3
  594. package/dist/schema-metadata.js +33 -5
  595. package/dist/schema-sql.d.ts +15 -24
  596. package/dist/schema-sql.js +50 -60
  597. package/dist/schema.d.ts +37 -2
  598. package/dist/schema.js +29 -2
  599. package/dist/seed.js +5 -5
  600. package/dist/serverless.d.ts +24 -71
  601. package/dist/serverless.js +24 -71
  602. package/dist/sql.d.ts +111 -0
  603. package/dist/sql.js +321 -0
  604. package/dist/sqlite-seed.d.ts +17 -0
  605. package/dist/sqlite-seed.js +27 -0
  606. package/dist/sqlite.d.ts +32 -19
  607. package/dist/sqlite.js +859 -648
  608. package/dist/supplied-pool-types.js +2 -1
  609. package/dist/transaction-control.js +6 -1
  610. package/dist/transaction-outcome.d.ts +61 -0
  611. package/dist/transaction-outcome.js +234 -0
  612. package/dist/transaction-state.d.ts +82 -13
  613. package/dist/transaction-state.js +220 -57
  614. package/dist/transaction-transport.d.ts +38 -0
  615. package/dist/transaction-transport.js +153 -0
  616. package/dist/typed-sql.d.ts +1 -1
  617. package/dist/typed-sql.js +1 -1
  618. package/package.json +239 -13
  619. package/skills/turbine-orm/SKILL.md +6 -5
@@ -57,12 +57,15 @@ const index_advisor_js_1 = require("../index-advisor.js");
57
57
  const logger_js_1 = require("../logger.js");
58
58
  const nested_write_js_1 = require("../nested-write.js");
59
59
  const query_channel_js_1 = require("../query-channel.js");
60
+ const query_utils_js_1 = require("../query-utils.js");
60
61
  const schema_js_1 = require("../schema.js");
61
62
  const transaction_client_slot_js_1 = require("../transaction-client-slot.js");
63
+ const transaction_outcome_js_1 = require("../transaction-outcome.js");
62
64
  const transaction_state_js_1 = require("../transaction-state.js");
63
65
  const aggMod = __importStar(require("./aggregates.js"));
64
66
  const batched_loader_js_1 = require("./batched-loader.js");
65
67
  const compound_unique_js_1 = require("./compound-unique.js");
68
+ const cursor_tuple_js_1 = require("./cursor-tuple.js");
66
69
  const expr_js_1 = require("./expr.js");
67
70
  const filters_js_1 = require("./filters.js");
68
71
  const normalize_args_js_1 = require("./normalize-args.js");
@@ -72,8 +75,8 @@ const relationsMod = __importStar(require("./relations.js"));
72
75
  const row_lock_js_1 = require("./row-lock.js");
73
76
  const sql_comment_js_1 = require("./sql-comment.js");
74
77
  const stream_idle_js_1 = require("./stream-idle.js");
78
+ const stream_signal_js_1 = require("./stream-signal.js");
75
79
  const types_js_1 = require("./types.js");
76
- const utils_js_1 = require("./utils.js");
77
80
  const warn_registry_js_1 = require("./warn-registry.js");
78
81
  const whereMod = __importStar(require("./where.js"));
79
82
  const writesMod = __importStar(require("./writes.js"));
@@ -142,8 +145,8 @@ const CACHE_MISMATCH_WARN_NS = 'cacheMismatch';
142
145
  * loopback TCP 0.118ms 0.000711ms ~166-236 between 200 and 400
143
146
  * +1ms/direction 2.683ms 0.000717ms ~3744-3993 between 3000 and 5000
144
147
  *
145
- * The two things that matters most in that table: the per-row penalty is
146
- * essentially IDENTICAL across the two links (it is a property of the plan, not
148
+ * Two measurements matter in that table: the per-row penalty is nearly
149
+ * identical across the two links (it is a property of the plan, not
147
150
  * the wire), while the break-even moved by 17x. So the break-even is a function
148
151
  * of the deployment's round-trip time and NOTHING ELSE that is knowable at plan
149
152
  * time. That is why this is expressed as a per-row cost and a round-trip time
@@ -278,6 +281,8 @@ const ROW_PLAN_CACHE_SIZE = 128;
278
281
  * probe's own limit.
279
282
  */
280
283
  const STREAM_SPECULATION_MAX_BATCH = 1000;
284
+ /** The context-free cell readers, indexed by the shared decode kind. */
285
+ const CELL_READERS = [undefined, undefined, query_utils_js_1.readJsonFloat, query_utils_js_1.readJsonFloatArray, query_utils_js_1.readTextArray];
281
286
  const FLOAT_TYPES = new Set(['float4', 'float8', 'real', 'double precision']);
282
287
  const FLOAT_ARRAY_TYPES = new Set(['_float4', '_float8', 'float4[]', 'float8[]', 'real[]', 'double precision[]']);
283
288
  /**
@@ -285,13 +290,19 @@ const FLOAT_ARRAY_TYPES = new Set(['_float4', '_float8', 'float4[]', 'float8[]',
285
290
  * temporal: a float can arrive from JSON as "NaN" / "Infinity", and an enum
286
291
  * array, which the driver has no parser for, as array text.
287
292
  */
288
- function cellKindOf(pgType, enums) {
293
+ function cellKindOf(pgType, enums, array) {
289
294
  if (FLOAT_TYPES.has(pgType))
290
- return utils_js_1.CELL_FLOAT;
295
+ return query_utils_js_1.CELL_FLOAT;
291
296
  if (FLOAT_ARRAY_TYPES.has(pgType))
292
- return utils_js_1.CELL_FLOAT_ARRAY;
293
- const element = pgType.startsWith('_') ? pgType.slice(1) : pgType.endsWith('[]') ? pgType.slice(0, -2) : undefined;
294
- return element !== undefined && enums !== undefined && Object.hasOwn(enums, element) ? utils_js_1.CELL_TEXT_ARRAY : utils_js_1.CELL_PLAIN;
297
+ return query_utils_js_1.CELL_FLOAT_ARRAY;
298
+ const element = !array
299
+ ? undefined
300
+ : pgType.startsWith('_')
301
+ ? pgType.slice(1)
302
+ : pgType.endsWith('[]')
303
+ ? pgType.slice(0, -2)
304
+ : undefined;
305
+ return element !== undefined && enums !== undefined && Object.hasOwn(enums, element) ? query_utils_js_1.CELL_TEXT_ARRAY : query_utils_js_1.CELL_PLAIN;
295
306
  }
296
307
  /**
297
308
  * Strict structural equality for a single SQL parameter value. Handles the
@@ -334,17 +345,7 @@ function cacheParamValueEqual(a, b) {
334
345
  const aArr = Array.isArray(a);
335
346
  const bArr = Array.isArray(b);
336
347
  if (aArr || bArr) {
337
- if (!aArr || !bArr)
338
- return false;
339
- const arrA = a;
340
- const arrB = b;
341
- if (arrA.length !== arrB.length)
342
- return false;
343
- for (let i = 0; i < arrA.length; i++) {
344
- if (!cacheParamValueEqual(arrA[i], arrB[i]))
345
- return false;
346
- }
347
- return true;
348
+ return aArr && bArr && cacheParamsEqual(a, b);
348
349
  }
349
350
  const objA = a;
350
351
  const objB = b;
@@ -364,8 +365,10 @@ function cacheParamValueEqual(a, b) {
364
365
  function cacheParamsEqual(a, b) {
365
366
  if (a.length !== b.length)
366
367
  return false;
367
- for (let i = 0; i < a.length; i++) {
368
- if (!cacheParamValueEqual(a[i], b[i]))
368
+ for (let i = 0; i < a.length;) {
369
+ const av = a[i];
370
+ const bv = b[i++];
371
+ if (av !== bv && !cacheParamValueEqual(av, bv))
369
372
  return false;
370
373
  }
371
374
  return true;
@@ -391,7 +394,7 @@ function maybeExpandCompoundUnique(meta, args) {
391
394
  * fully-derived predicate (the parent's own FK match, guarded there against a
392
395
  * null reference key), not caller input, and the flag is what lets that
393
396
  * unconditional-looking statement through the empty-`where` guard. Since
394
- * `allowFullTableScan` now only accepts {@link UNSAFE}, that literal `true`
397
+ * `allowFullTableScan` only accepts {@link UNSAFE}, that literal `true`
395
398
  * would throw and every nested `set` would fail.
396
399
  *
397
400
  * Rather than hand the nested-write engine the sentinel (which would put the
@@ -401,9 +404,13 @@ function maybeExpandCompoundUnique(meta, args) {
401
404
  * exactly `true`, so nothing else about the call is touched and no other
402
405
  * operation gains an escape hatch.
403
406
  *
407
+ * `timeout` bounds the nested write as one call: every statement it sends
408
+ * gets what is left of it (see `writeDeadline`).
409
+ *
404
410
  * @internal Exported for its unit test; not part of the public surface.
405
411
  */
406
- function unlockNestedWriteTx(tx) {
412
+ function unlockNestedWriteTx(tx, timeout) {
413
+ const deadline = timeout ? (0, transaction_state_js_1.writeDeadline)(timeout) : undefined;
407
414
  const wrapped = {
408
415
  table(name) {
409
416
  const handle = tx.table(name);
@@ -417,9 +424,15 @@ function unlockNestedWriteTx(tx) {
417
424
  if (typeof value !== 'function')
418
425
  return value;
419
426
  const method = value;
420
- if (prop !== 'updateMany')
427
+ if (prop !== 'updateMany' && !deadline)
421
428
  return method.bind(target);
422
- return (args) => method.call(target, args?.allowFullTableScan === true ? { ...args, allowFullTableScan: types_js_1.UNSAFE } : args);
429
+ return (args) => {
430
+ const unlocked = prop === 'updateMany' && args?.allowFullTableScan === true
431
+ ? { ...args, allowFullTableScan: types_js_1.UNSAFE }
432
+ : args;
433
+ // Every statement of a nested write gets what is left of the call's `timeout`.
434
+ return method.call(target, deadline ? { ...unlocked, timeout: deadline() } : unlocked);
435
+ };
423
436
  },
424
437
  });
425
438
  },
@@ -476,36 +489,14 @@ function relationLoadStrategyMessage(value) {
476
489
  return (`\`relationLoadStrategy\` must be one of ${RELATION_LOAD_STRATEGIES.map((v) => `'${v}'`).join(', ')} ` +
477
490
  `(received ${describeOptionValue(value)}).`);
478
491
  }
479
- /** A value the findUnique simple path may bind as it is: a primitive, Date or Buffer. */
480
- function isFastPathScalar(value) {
481
- switch (typeof value) {
482
- case 'string':
483
- case 'number':
484
- case 'bigint':
485
- case 'boolean':
486
- return true;
487
- case 'object':
488
- return value instanceof Date || (value !== null && ArrayBuffer.isView(value));
489
- default:
490
- return false;
491
- }
492
- }
493
- /** Resolves a race when a deadline passes first. */
494
- const TIMED_OUT = Symbol('timedOut');
495
- /**
496
- * How long a statement that outlived its `timeout` gets, after the cancel
497
- * request is sent, to answer before its connection is destroyed instead of
498
- * reused. A cancel normally lands within a round trip or two.
499
- */
500
- const CANCEL_GRACE_MS = 2000;
501
492
  /** Whether `err` is PostgreSQL's query_canceled (57014), as the driver raised it or as Turbine wrapped it. */
502
493
  function isQueryCanceled(err) {
503
494
  const e = err;
504
495
  return e?.code === '57014' || e?.cause?.code === '57014';
505
496
  }
506
- /** The {@link DeferredQuery.rowLock} marker for a locking read, or nothing. */
497
+ /** A marker only for locking reads; unlocked reads allocate no marker object. */
507
498
  function rowLockMarker(rowLock) {
508
- return rowLock ? { rowLock: true } : {};
499
+ return rowLock ? { rowLock: true } : null;
509
500
  }
510
501
  /** The two accepted {@link JsonEncoding} values, frozen so the check is total. */
511
502
  const JSON_ENCODINGS = Object.freeze(['object', 'positional']);
@@ -537,9 +528,9 @@ function defaultJsonEncoding(dialect) {
537
528
  * SQL template caches shared by every QueryInterface built from ONE options
538
529
  * object, for one schema and one table.
539
530
  *
540
- * A transaction builds its own QueryInterface per table, so before this each
531
+ * A transaction builds its own QueryInterface per table, so previously each
541
532
  * `$transaction` started with an empty cache and rebuilt the SQL of every
542
- * statement it sent. TransactionClient now hands every transaction of a client
533
+ * statement it sent. TransactionClient hands every transaction of a client
543
534
  * the same options object (`txQueryOptions` in client.ts), so they share one
544
535
  * cache per table and a statement is built once per process, as it is outside
545
536
  * a transaction.
@@ -578,7 +569,7 @@ function txQueryOptions(options) {
578
569
  }
579
570
  function templateCacheFor(options, schema, table, capacity) {
580
571
  if (options === undefined)
581
- return new utils_js_1.LRUCache(capacity);
572
+ return new query_utils_js_1.LRUCache(capacity);
582
573
  let bySchema = sharedTemplateCaches.get(options);
583
574
  if (bySchema === undefined) {
584
575
  bySchema = new WeakMap();
@@ -591,7 +582,7 @@ function templateCacheFor(options, schema, table, capacity) {
591
582
  }
592
583
  let cache = byTable.get(table);
593
584
  if (cache === undefined) {
594
- cache = new utils_js_1.LRUCache(capacity);
585
+ cache = new query_utils_js_1.LRUCache(capacity);
595
586
  byTable.set(table, cache);
596
587
  }
597
588
  return cache;
@@ -728,13 +719,15 @@ class QueryInterface {
728
719
  * source but can be assembled per request from user input, so the key space
729
720
  * is not provably finite. Eviction only ever costs a rebuild.
730
721
  */
731
- rowPlanCache = new utils_js_1.LRUCache(ROW_PLAN_CACHE_SIZE);
722
+ /** Only the last executed native projection; descriptors are snapshotted, never retained. */
723
+ arrayReadPlan;
724
+ rowPlanCache = new query_utils_js_1.LRUCache(ROW_PLAN_CACHE_SIZE);
732
725
  /**
733
- * The most recent plan per table, which is the entry `parseRow` actually
734
- * probes. One result set is one shape, so this hits for every row after the
735
- * first without hashing a cache key per row.
726
+ * Each table's row parser holds its most recent shape locally. Flat reads
727
+ * capture the parser once, so neither the table nor parser cache is looked
728
+ * up again for every row. Every row still verifies its exact own key order.
736
729
  */
737
- rowPlanLast = new Map();
730
+ rowParsers = new Map();
738
731
  /**
739
732
  * Client-level automatic WHERE filters keyed by table accessor (soft-delete /
740
733
  * multi-tenancy). AND-merged into every query on the keyed table and every
@@ -770,10 +763,8 @@ class QueryInterface {
770
763
  * to Date as well (otherwise nested dates leak through as strings).
771
764
  */
772
765
  camelDateFieldCache = new Map();
773
- /** Per-table memo of {@link cellKindOf}, keyed by column name and field name. */
766
+ /** Per-table cell kinds and optional dialect readers, keyed by column and field name. */
774
767
  cellKindCache = new Map();
775
- /** The dialect decode of each {@link CELL_DIALECT} column, by table, then by column and field name. */
776
- dialectDecodeCache = new Map();
777
768
  /**
778
769
  * Per-table memo of `Object.entries(meta.relations)`, consumed by the nested
779
770
  * row parser (see `getRelationEntries` in relations.ts). Same rationale and
@@ -843,7 +834,7 @@ class QueryInterface {
843
834
  this.schema = schema;
844
835
  const meta = schema.tables[table];
845
836
  if (!meta) {
846
- throw new errors_js_1.ValidationError(`Unknown table "${table}". ${(0, utils_js_1.availableClause)(Object.keys(schema.tables), 'The schema has no tables.')}`);
837
+ throw new errors_js_1.ValidationError(`Unknown table "${table}". ${(0, query_utils_js_1.availableClause)(Object.keys(schema.tables), 'The schema has no tables.')}`);
847
838
  }
848
839
  this.tableMeta = meta;
849
840
  this.middlewares = middlewares ?? [];
@@ -919,7 +910,7 @@ class QueryInterface {
919
910
  options?.globalFilters && Object.keys(options.globalFilters).length > 0 ? options.globalFilters : undefined;
920
911
  this.txScoped = options?._txScoped ?? false;
921
912
  this.options = options;
922
- // Pre-compute column type lookup maps (TASK-26)
913
+ // Pre-compute column type lookup maps
923
914
  //
924
915
  // Metadata can carry a column's database type in EITHER of two places: on
925
916
  // the column entry (`dialectType` / `pgType`, what introspection and
@@ -939,8 +930,8 @@ class QueryInterface {
939
930
  for (const col of this.tableMeta.columns) {
940
931
  const dbType = col.dialectType ??
941
932
  col.pgType ??
942
- (tableDialectTypes && (0, utils_js_1.ownLookup)(tableDialectTypes, col.name)) ??
943
- (tablePgTypes && (0, utils_js_1.ownLookup)(tablePgTypes, col.name));
933
+ (tableDialectTypes && (0, query_utils_js_1.ownLookup)(tableDialectTypes, col.name)) ??
934
+ (tablePgTypes && (0, query_utils_js_1.ownLookup)(tablePgTypes, col.name));
944
935
  if (dbType !== undefined)
945
936
  this.columnPgTypeMap.set(col.name, dbType);
946
937
  // The array map has the same shape of gap, but TableMetadata carries NO
@@ -960,9 +951,10 @@ class QueryInterface {
960
951
  // the walk needs no public accessors on the class.
961
952
  this.whereHost = {
962
953
  tableMeta: this.tableMeta,
963
- normalizeRelationFilter: (relDef, filterObj) => this.normalizeRelationFilter(relDef, filterObj),
964
- getColumnPgType: (column) => this.getColumnPgType(column),
965
- isJsonColumnType: (colType) => this.isJsonColumnType(colType),
954
+ normalizeRelationFilter: (relDef, filterObj) => whereMod.normalizeRelationFilter(this.ctx, relDef, filterObj),
955
+ getColumnPgType: (column) => whereMod.getColumnPgType(this.ctx, column),
956
+ getColumnKind: whereMod.memoizedKinds(this.tableMeta),
957
+ isJsonColumnType: (colType) => whereMod.isJsonColumnType(this.ctx, colType),
966
958
  };
967
959
  // Bind the privacy-preserving view handed to the extracted WHERE module.
968
960
  // Data fields are immutable after this point; `currentSkip` is reassigned
@@ -1018,15 +1010,15 @@ class QueryInterface {
1018
1010
  return meta ? this.rowDecodePlanFor(table, meta, keys) : undefined;
1019
1011
  },
1020
1012
  decodeCell: (kind, value, table, field) => this.decodeCell(kind, value, table, field),
1021
- nullsSuffix: (nulls) => this.nullsSuffix(nulls),
1022
- isRelationOrderByValue: (value) => this.isRelationOrderByValue(value),
1023
- resolveOrderByColumn: (table, meta, key) => this.resolveOrderByColumn(table, meta, key),
1024
- buildJsonPathOrderEntry: (table, meta, field, spec, prefix, params) => this.buildJsonPathOrderEntry(table, meta, field, spec, prefix, params),
1013
+ nullsSuffix: (nulls) => relationsMod.nullsSuffix(this.ctx, nulls),
1014
+ isRelationOrderByValue: (value) => relationsMod.isRelationOrderByValue(this.ctx, value),
1015
+ resolveOrderByColumn: (table, meta, key) => relationsMod.resolveOrderByColumn(this.ctx, table, meta, key),
1016
+ buildJsonPathOrderEntry: (table, meta, field, spec, prefix, params) => relationsMod.buildJsonPathOrderEntry(this.ctx, table, meta, field, spec, prefix, params),
1025
1017
  toSqlColumn: (field) => this.toSqlColumn(field),
1026
1018
  mutationInsertId: (result) => this.mutationInsertId(result),
1027
1019
  acquireSql: (cacheKey, build) => this.acquireSql(cacheKey, build),
1028
1020
  crossCheckCache: (op, cacheKey, entry, build, collectedParams) => this.crossCheckCache(op, cacheKey, entry, build, collectedParams),
1029
- // LIVE getter, not a copied value: `jsonEncoding` is now a per-query
1021
+ // LIVE getter, not a copied value: `jsonEncoding` is a per-query
1030
1022
  // option, so the module-facing view must see the encoding of the query
1031
1023
  // being built rather than the one the client was constructed with. Same
1032
1024
  // shape and same reason as `currentSkip` above.
@@ -1152,10 +1144,7 @@ class QueryInterface {
1152
1144
  * ROWS ONLY`. No params are pushed, so the collect path is unaffected.
1153
1145
  */
1154
1146
  limitOneClause() {
1155
- if (this.dialect.buildLimitOffset) {
1156
- return this.dialect.buildLimitOffset({ limitPlaceholder: '1', offsetPlaceholder: undefined, hasOrderBy: false });
1157
- }
1158
- return ' LIMIT 1';
1147
+ return this.buildPagination('1', undefined, false);
1159
1148
  }
1160
1149
  /**
1161
1150
  * Coerce a LIMIT/OFFSET argument and validate it as a non-negative safe
@@ -1307,7 +1296,7 @@ class QueryInterface {
1307
1296
  * `findFirstOrThrow`) that refuses a `where` whose every key was `undefined`.
1308
1297
  */
1309
1298
  normalizeArgs(args, refuseEmptiedWhere) {
1310
- const pruned = (0, normalize_args_js_1.pruneUndefinedArgs)(this.schema, this.table, args);
1299
+ const pruned = (0, normalize_args_js_1.pruneUndefinedArgs)(this.schema, this.table, args, this.dialect.capabilities.tupleCursorPredicate === true);
1311
1300
  if (pruned !== args) {
1312
1301
  if (refuseEmptiedWhere)
1313
1302
  (0, normalize_args_js_1.assertWhereNotEmptiedByPruning)(this.table, refuseEmptiedWhere, args, pruned);
@@ -1315,7 +1304,7 @@ class QueryInterface {
1315
1304
  }
1316
1305
  if (pruned)
1317
1306
  this.assertQueryOptions(pruned);
1318
- return (0, utils_js_1.normalizePagination)(this.withRelationPagination(this.withDeclaredRelationNames(pruned)));
1307
+ return (0, query_utils_js_1.normalizePagination)(this.withRelationPagination(this.withDeclaredRelationNames(pruned)));
1319
1308
  }
1320
1309
  /**
1321
1310
  * Validate the per-query options whose bad values used to be ignored or
@@ -1332,14 +1321,6 @@ class QueryInterface {
1332
1321
  throw new errors_js_1.ValidationError(relationLoadStrategyMessage(relationLoadStrategy));
1333
1322
  }
1334
1323
  }
1335
- /**
1336
- * Refuse a `findUnique` whose `where` names no unique key. The rule and the
1337
- * message live in query/compound-unique.ts, beside the definition of what
1338
- * counts as unique and shared with the PowDB engine.
1339
- */
1340
- assertFindUniqueKey(where) {
1341
- (0, compound_unique_js_1.assertWhereIdentifiesOneRow)(this.tableMeta, this.table, where);
1342
- }
1343
1324
  /**
1344
1325
  * Refuse a locking read that is not inside a transaction, at the execute
1345
1326
  * entry of each find method and before any strategy runs. The `build*`
@@ -1364,38 +1345,9 @@ class QueryInterface {
1364
1345
  throw new errors_js_1.ValidationError((0, row_lock_js_1.lockOnStreamMessage)(this.table, operation));
1365
1346
  }
1366
1347
  }
1367
- /**
1368
- * Fill a PK-ascending `orderBy` into every to-many `with` relation that has no
1369
- * explicit one, recursing into nested `with`. Returns a CLONED clause (user
1370
- * args are never mutated); when nothing needs filling it returns the input
1371
- * object unchanged, so the byte-identical fast path stays free. Only called
1372
- * when {@link resolveStableOrder} is true; runs BEFORE `withFingerprint`, so
1373
- * the two orderings get distinct SQL-cache entries automatically. To-one
1374
- * relations are single rows (no array to order) and PK-less targets have
1375
- * nothing stable to order by, so both are left untouched.
1376
- */
1377
- applyStableRelationOrder(withClause, table, depth = 0) {
1378
- // The transform itself lives in ./relation-names.ts as of 0.74.0, so PowDB
1379
- // runs the SAME rule instead of a second copy that accepted the option and
1380
- // did nothing.
1381
- return (0, relation_names_js_1.applyStableRelationOrderTo)(this.schema, withClause, table, depth);
1382
- }
1383
1348
  // -------------------------------------------------------------------------
1384
1349
  // Deterministic pagination (unordered LIMIT/OFFSET)
1385
1350
  // -------------------------------------------------------------------------
1386
- /**
1387
- * The primary key of this table as an ascending `orderBy`, in DECLARATION
1388
- * order (a composite PK orders on every column), or `undefined` for a PK-less
1389
- * table. Field names are the camelCase accessor names, so the emitted SQL goes
1390
- * through the normal column mapping.
1391
- */
1392
- pkOrderBy() {
1393
- const pk = this.tableMeta.primaryKey ?? [];
1394
- if (pk.length === 0)
1395
- return undefined;
1396
- const fields = pk.map((c) => this.tableMeta.reverseColumnMap[c] ?? c);
1397
- return fields.length === 1 ? { [fields[0]]: 'asc' } : fields.map((f) => ({ [f]: 'asc' }));
1398
- }
1399
1351
  /** Memo for {@link totalOrderKeys}; table metadata is immutable. */
1400
1352
  totalOrderKeysMemo;
1401
1353
  /**
@@ -1453,9 +1405,9 @@ class QueryInterface {
1453
1405
  let lastDesc = false;
1454
1406
  for (const [key, dir] of entries) {
1455
1407
  lastDesc = false;
1456
- if ((0, filters_js_1.isVectorOrderBy)(dir) || (0, filters_js_1.isJsonPathOrderBy)(dir) || this.isRelationOrderByValue(dir))
1408
+ if ((0, filters_js_1.isVectorOrderBy)(dir) || (0, filters_js_1.isJsonPathOrderBy)(dir) || relationsMod.isRelationOrderByValue(this.ctx, dir))
1457
1409
  continue;
1458
- const column = (0, utils_js_1.resolveColumnName)(this.tableMeta, key);
1410
+ const column = (0, query_utils_js_1.resolveColumnName)(this.tableMeta, key);
1459
1411
  if (column === undefined)
1460
1412
  continue;
1461
1413
  ordered.add(column);
@@ -1501,6 +1453,9 @@ class QueryInterface {
1501
1453
  */
1502
1454
  planCursor(args) {
1503
1455
  const raw = args.cursor;
1456
+ const tuple = args.cursorPredicate === 'tuple';
1457
+ if (tuple)
1458
+ (0, cursor_tuple_js_1.assertTupleCursorMetadata)(this.tableMeta);
1504
1459
  if (!(0, normalize_args_js_1.hasCursor)(raw))
1505
1460
  return { args, plan: undefined };
1506
1461
  const meta = this.tableMeta;
@@ -1518,7 +1473,7 @@ class QueryInterface {
1518
1473
  const value = (0, filters_js_1.cursorFieldValue)(key, written, {
1519
1474
  column,
1520
1475
  table: this.table,
1521
- kind: (0, filters_js_1.operandColumnKind)(this.getColumnPgType(column)),
1476
+ kind: this.whereHost.getColumnKind(column),
1522
1477
  nullable: nullableColumn(column),
1523
1478
  });
1524
1479
  cursorValues.set(column, value);
@@ -1530,7 +1485,7 @@ class QueryInterface {
1530
1485
  const terms = [];
1531
1486
  const orderEntries = (0, filters_js_1.orderByEntries)(args.orderBy).filter(([, d]) => d !== undefined);
1532
1487
  for (const [key, dir] of orderEntries) {
1533
- if ((0, filters_js_1.isVectorOrderBy)(dir) || (0, filters_js_1.isJsonPathOrderBy)(dir) || this.isRelationOrderByValue(dir)) {
1488
+ if ((0, filters_js_1.isVectorOrderBy)(dir) || (0, filters_js_1.isJsonPathOrderBy)(dir) || relationsMod.isRelationOrderByValue(this.ctx, dir)) {
1534
1489
  throw new errors_js_1.ValidationError(`findMany on "${this.table}" refused: \`cursor\` cannot page past the orderBy entry "${key}", which ` +
1535
1490
  'orders by a relation, a JSON path or a vector distance rather than a column. Order the cursor ' +
1536
1491
  'query by columns only, or page it with `offset`.');
@@ -1544,6 +1499,8 @@ class QueryInterface {
1544
1499
  // Tiebreaker, the same one a first page gets (see tiebreakColumns).
1545
1500
  const tiebreak = this.tiebreakColumns(new Set(terms.map((t) => t.column)));
1546
1501
  if (!tiebreak) {
1502
+ if (tuple)
1503
+ (0, cursor_tuple_js_1.refuseTupleCursor)('Need a non-null unique key.');
1547
1504
  throw new errors_js_1.ValidationError(`findMany on "${this.table}" refused: a \`cursor\` page needs an order with no ties, and "${this.table}" ` +
1548
1505
  'has no primary key or unique key on NOT NULL columns to break them. Add a primary key, or page ' +
1549
1506
  'this table with `offset`.');
@@ -1565,8 +1522,8 @@ class QueryInterface {
1565
1522
  t.pin = true;
1566
1523
  pinned = true;
1567
1524
  }
1525
+ t.nullsFirst = t.nulls !== undefined ? t.nulls === 'first' : nullsSortHigh ? t.desc : !t.desc;
1568
1526
  }
1569
- const nullsFirst = (t) => t.nulls !== undefined ? t.nulls === 'first' : nullsSortHigh ? t.desc : !t.desc;
1570
1527
  let nextArgs = args;
1571
1528
  if (appended || pinned) {
1572
1529
  const orderBy = terms.map((t) => {
@@ -1578,26 +1535,27 @@ class QueryInterface {
1578
1535
  }
1579
1536
  const inclusive = (0, normalize_args_js_1.isCursorInclusive)(args);
1580
1537
  const coerce = (column, value) => whereMod.coerceWhereOperand(this.ctx, meta, column, value);
1581
- const keysetTerms = terms.map((t) => ({
1582
- column: t.column,
1583
- desc: t.desc,
1584
- nullsFirst: nullsFirst(t),
1585
- nullable: t.nullable,
1586
- }));
1538
+ // The placement loop has filled every term before the plan can escape.
1539
+ const keysetTerms = terms;
1540
+ const orderFp = (values) => keysetTerms
1541
+ .map((t, i) => `${t.column}:${t.desc ? 'd' : 'a'}${t.nullable ? (t.nullsFirst ? 'f' : 'l') : ''}${values?.[i] === null ? '0' : ''}`)
1542
+ .join(',');
1543
+ // IndexMetadata.columns can omit expressions and does not prove that an
1544
+ // index uses the column's own equality/collation. Trust constraints only.
1545
+ const tupleFp = tuple ? (0, cursor_tuple_js_1.tupleCursorFingerprint)(meta, terms, cursorValues, args, inclusive, this.schema.enums) : '';
1587
1546
  // An inclusive cursor (prisma-compat) names a ROW, as Prisma's does, so it
1588
1547
  // always reads that row: a deleted cursor row gives an empty page, never a
1589
1548
  // page placed where the row used to be.
1590
- const namesRow = inclusive && (0, compound_unique_js_1.whereIdentifiesOneRow)(meta, flat);
1591
- if (!namesRow && terms.every((t) => cursorValues.has(t.column))) {
1549
+ const namesRow = !tuple && inclusive && (0, compound_unique_js_1.whereIdentifiesOneRow)(meta, flat);
1550
+ if (tuple || (!namesRow && terms.every((t) => cursorValues.has(t.column)))) {
1592
1551
  const values = terms.map((t) => {
1593
1552
  const v = cursorValues.get(t.column);
1594
1553
  return v === null ? null : coerce(t.column, v);
1595
1554
  });
1596
- const fp = `v:${keysetTerms.map((t, i) => `${t.column}:${t.desc ? 'd' : 'a'}${t.nullable ? (t.nullsFirst ? 'f' : 'l') : ''}${values[i] === null ? '0' : ''}`).join(',')}` +
1597
- (inclusive ? ':i' : '');
1555
+ const fp = tupleFp || `v:${orderFp(values)}${inclusive ? ':i' : ''}`;
1598
1556
  return {
1599
1557
  args: nextArgs,
1600
- plan: { mode: 'values', terms: keysetTerms, values, lookup: [], inclusive, fingerprint: fp },
1558
+ plan: { mode: tuple ? 'tuple' : 'values', terms: keysetTerms, values, inclusive, fingerprint: fp },
1601
1559
  };
1602
1560
  }
1603
1561
  if (!(0, compound_unique_js_1.whereIdentifiesOneRow)(meta, flat)) {
@@ -1609,12 +1567,12 @@ class QueryInterface {
1609
1567
  `for every ordered field, or name the cursor row by ${keys.length > 0 ? keys.join(' or ') : 'a unique key'}.`);
1610
1568
  }
1611
1569
  const lookup = [...cursorValues].map(([column, v]) => ({ column, value: v === null ? null : coerce(column, v) }));
1612
- const fp = `r:${keysetTerms.map((t) => `${t.column}:${t.desc ? 'd' : 'a'}${t.nullable ? (t.nullsFirst ? 'f' : 'l') : ''}`).join(',')}` +
1570
+ const fp = `r:${orderFp()}` +
1613
1571
  `|k=${lookup.map((l) => `${l.column}${l.value === null ? '0' : ''}`).join(',')}` +
1614
1572
  (inclusive ? ':i' : '');
1615
1573
  return {
1616
1574
  args: nextArgs,
1617
- plan: { mode: 'row', terms: keysetTerms, values: [], lookup, inclusive, fingerprint: fp },
1575
+ plan: { mode: 'row', terms: keysetTerms, lookup, inclusive, fingerprint: fp },
1618
1576
  };
1619
1577
  }
1620
1578
  /**
@@ -1633,13 +1591,16 @@ class QueryInterface {
1633
1591
  const col = (t) => `${qt}.${this.q(t.column)}`;
1634
1592
  let ref;
1635
1593
  let guard = '';
1636
- if (plan.mode === 'values') {
1594
+ if (plan.mode !== 'row') {
1637
1595
  const refs = plan.values.map((v) => {
1638
1596
  if (v === null)
1639
1597
  return null;
1640
1598
  params.push(v);
1641
1599
  return this.p(params.length);
1642
1600
  });
1601
+ if (plan.mode === 'tuple') {
1602
+ return `(${plan.terms.map(col).join(', ')}) ${plan.terms[0].desc ? '<' : '>'} (${refs.join(', ')})`;
1603
+ }
1643
1604
  ref = (i) => refs[i] ?? null;
1644
1605
  }
1645
1606
  else {
@@ -1752,7 +1713,7 @@ class QueryInterface {
1752
1713
  return undefined;
1753
1714
  if (!this.isUnorderedPage(args))
1754
1715
  return undefined;
1755
- return this.pkOrderBy();
1716
+ return (0, relation_names_js_1.primaryKeyOrderBy)(this.tableMeta);
1756
1717
  }
1757
1718
  /**
1758
1719
  * Advice (`diagnostics.advice`), once per query shape: an unordered paginating findMany returns a
@@ -1846,7 +1807,7 @@ class QueryInterface {
1846
1807
  miss = cv.miss;
1847
1808
  continue;
1848
1809
  }
1849
- const childRel = (0, utils_js_1.ownLookup)(targetMeta?.relations ?? {}, childName);
1810
+ const childRel = (0, query_utils_js_1.ownLookup)(targetMeta?.relations ?? {}, childName);
1850
1811
  if (!childRel)
1851
1812
  continue; // unknown nested relation, let the build path surface it
1852
1813
  const v = this.autoSubtreeVerdict(childRel, childSpec, depth + 1);
@@ -1977,7 +1938,7 @@ class QueryInterface {
1977
1938
  }
1978
1939
  continue;
1979
1940
  }
1980
- const rel = (0, utils_js_1.resolveRelationDef)(this.tableMeta.relations, key);
1941
+ const rel = (0, query_utils_js_1.resolveRelationDef)(this.tableMeta.relations, key);
1981
1942
  if (!rel) {
1982
1943
  joinWith[key] = spec; // unknown relation, let the join path surface E005
1983
1944
  continue;
@@ -2013,7 +1974,7 @@ class QueryInterface {
2013
1974
  if (!(0, index_advisor_js_1.schemaHasIndexInfo)(this.schema) && !parentSetLarge)
2014
1975
  return null;
2015
1976
  const withClause = this.resolveStableOrder(stableFlag)
2016
- ? this.applyStableRelationOrder(withArg, this.table)
1977
+ ? (0, relation_names_js_1.applyStableRelationOrderTo)(this.schema, withArg, this.table)
2017
1978
  : withArg;
2018
1979
  const split = this.partitionWithForAuto(withClause, parentSetLarge, parentBound);
2019
1980
  if (Object.keys(split.batchedWith).length === 0)
@@ -2181,7 +2142,7 @@ class QueryInterface {
2181
2142
  // relation fetch was never affected, because that one goes through the
2182
2143
  // child's own buildFindMany and merges the filter unqualified.
2183
2144
  tableGlobalFilter: (table, ref, precedingParams) => {
2184
- const gf = this.resolveGlobalFilter(table, resolvedSkip);
2145
+ const gf = whereMod.resolveGlobalFilter(this.ctx, table, resolvedSkip);
2185
2146
  if (!gf)
2186
2147
  return null;
2187
2148
  const meta = this.schema.tables[table];
@@ -2243,7 +2204,7 @@ class QueryInterface {
2243
2204
  // orderBy into its follow-up query, so filling the synthesized PK order here
2244
2205
  // makes the batched output deterministic exactly like the join path.
2245
2206
  const withClause = this.resolveStableOrder(args.stableRelationOrder)
2246
- ? this.applyStableRelationOrder(args.with, this.table)
2207
+ ? (0, relation_names_js_1.applyStableRelationOrderTo)(this.schema, args.with, this.table)
2247
2208
  : args.with;
2248
2209
  // Scope-rule parity with the join strategy (which throws at SQL build):
2249
2210
  // reject nested pick-row ordering BEFORE the base query so acceptance
@@ -2372,7 +2333,7 @@ class QueryInterface {
2372
2333
  // With `sqlComment` putting a comment on every statement, the template's own
2373
2334
  // name is never sent (the execute seam sends a `c_` name derived from it),
2374
2335
  // so it is not claimed from the budget: only names that reach the wire do.
2375
- return this.sqlCommenter?.alwaysComments ? (0, utils_js_1.sqlToPreparedName)(sql) : (0, utils_js_1.boundedPreparedName)(sql);
2336
+ return this.sqlCommenter?.alwaysComments ? (0, query_utils_js_1.sqlToPreparedName)(sql) : (0, query_utils_js_1.boundedPreparedName)(sql);
2376
2337
  }
2377
2338
  /**
2378
2339
  * Name a statement the SQL template cache does not hold (`aggregate`,
@@ -2601,6 +2562,65 @@ class QueryInterface {
2601
2562
  readWithTimeout(sql, params, timeout, preparedName) {
2602
2563
  return this.queryWithTimeout(sql, params, timeout, preparedName, true);
2603
2564
  }
2565
+ /** One executor for compiled reads; all paths retain timeout, naming and decoding. */
2566
+ async executeRead(deferred, args) {
2567
+ const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
2568
+ return deferred.transform(result);
2569
+ }
2570
+ /** Native flat reads skip the driver's intermediate object materialization. */
2571
+ async executeFlatRead(deferred, args) {
2572
+ // Only native pg's standard text-row lifecycle is positional. Custom
2573
+ // clients, binary pools, transactions and timed reads keep object rows.
2574
+ const arrayRows = !args?.timeout &&
2575
+ !this.txScoped &&
2576
+ this.dialect.capabilities.connectionDriver === 'pg-compatible' &&
2577
+ (0, query_utils_js_1.canReadArrayRows)(this.pool);
2578
+ if (!arrayRows)
2579
+ return this.executeRead(deferred, args);
2580
+ const result = await this.queryWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName), true, this.pool, true);
2581
+ if (result.fields && Array.isArray(result.rows[0])) {
2582
+ let plan = this.arrayReadPlan;
2583
+ const columns = result.fields;
2584
+ let same = plan !== undefined && plan.names.length === columns.length;
2585
+ if (same) {
2586
+ for (let i = 0; i < columns.length; i++) {
2587
+ if (plan.names[i] !== columns[i].name) {
2588
+ same = false;
2589
+ break;
2590
+ }
2591
+ }
2592
+ }
2593
+ if (!same) {
2594
+ // Object.keys reproduces pg's object enumeration: integer keys sort,
2595
+ // duplicate names retain their first position and their LAST value.
2596
+ const positions = Object.create(null);
2597
+ for (let i = 0; i < columns.length; i++)
2598
+ positions[columns[i].name] = i;
2599
+ this.arrayReadPlan = plan = {
2600
+ names: columns.map((column) => column.name),
2601
+ indices: Object.values(positions),
2602
+ decode: this.rowDecodePlanFor(this.table, this.tableMeta, Object.keys(positions)),
2603
+ };
2604
+ }
2605
+ const { fields, kinds } = plan.decode;
2606
+ const { indices } = plan;
2607
+ return result.rows.map((row) => {
2608
+ const parsed = {};
2609
+ for (let i = 0; i < fields.length; i++) {
2610
+ const field = fields[i];
2611
+ const kind = kinds[i];
2612
+ let value = row[indices[i]];
2613
+ if (field === '__proto__')
2614
+ Object.defineProperty(parsed, field, { writable: true, enumerable: true, configurable: true });
2615
+ if (kind !== query_utils_js_1.CELL_PLAIN && (kind !== query_utils_js_1.CELL_FLOAT || typeof value === 'string'))
2616
+ value = this.decodeCell(kind, value, this.table, field);
2617
+ parsed[field] = value;
2618
+ }
2619
+ return parsed;
2620
+ });
2621
+ }
2622
+ return deferred.transform(result);
2623
+ }
2604
2624
  /**
2605
2625
  * Execute a pool.query with an optional timeout.
2606
2626
  *
@@ -2613,7 +2633,7 @@ class QueryInterface {
2613
2633
  * pg driver errors are translated to typed Turbine errors via wrapPgError.
2614
2634
  * `retryIfStale` is {@link readWithTimeout}'s; nothing else sets it.
2615
2635
  */
2616
- async queryWithTimeout(sql, params, requestedTimeout, preparedName, retryIfStale = false, pool = this.pool) {
2636
+ async queryWithTimeout(sql, params, requestedTimeout, preparedName, retryIfStale = false, pool = this.pool, arrayRows = false) {
2617
2637
  const action = this.currentAction;
2618
2638
  const out = this.outgoing(sql, preparedName, action);
2619
2639
  // 0 is no timeout, as it is for `$transaction`'s option and the server's statement_timeout.
@@ -2621,10 +2641,11 @@ class QueryInterface {
2621
2641
  if (timeout !== undefined && pool === this.pool && this.cancelsOnTimeout()) {
2622
2642
  return this.queryCancellable(out, params, timeout, retryIfStale, action);
2623
2643
  }
2624
- if (timeout !== undefined && pool === this.pool && this.txScoped && this.dialect.capabilities.backendCancel) {
2625
- const state = (0, transaction_state_js_1.transactionStateOf)(this.pool);
2626
- if (state !== undefined && (0, utils_js_1.canCancelBackend)(state.client)) {
2627
- return this.queryCancellableInTransaction(out, params, timeout, state, action);
2644
+ // The caller's transaction, for a timed statement that runs in one.
2645
+ const state = timeout !== undefined && pool === this.pool && this.txScoped ? (0, transaction_state_js_1.transactionStateOf)(pool) : undefined;
2646
+ if (timeout !== undefined && state !== undefined && this.dialect.capabilities.backendCancel) {
2647
+ if ((0, query_utils_js_1.canCancelBackend)(state.client)) {
2648
+ return this.queryCancellable(out, params, timeout, false, action, state);
2628
2649
  }
2629
2650
  }
2630
2651
  let trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
@@ -2637,13 +2658,18 @@ class QueryInterface {
2637
2658
  // cast. Guarded at runtime by `preparedStatementsEnabled`, which only the
2638
2659
  // drivers that accept it turn on.
2639
2660
  const usePrepared = out.name && this.preparedStatementsEnabled;
2640
- const send = () => usePrepared
2641
- ? pool.query({
2642
- name: out.name,
2661
+ const send = () => {
2662
+ if (!arrayRows && !usePrepared)
2663
+ return pool.query(out.text, params);
2664
+ const config = {
2665
+ name: usePrepared ? out.name : undefined,
2643
2666
  text: out.text,
2644
2667
  values: params,
2645
- })
2646
- : pool.query(out.text, params);
2668
+ };
2669
+ if (arrayRows)
2670
+ config.rowMode = 'array';
2671
+ return pool.query(config);
2672
+ };
2647
2673
  let exec = send();
2648
2674
  // Set when the caller's timeout has already answered, so a first attempt
2649
2675
  // that fails AFTER that does not send a retry nobody is waiting for.
@@ -2665,31 +2691,26 @@ class QueryInterface {
2665
2691
  return send();
2666
2692
  });
2667
2693
  }
2668
- if (!timeout) {
2669
- try {
2670
- const result = await exec;
2671
- this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0, undefined, undefined, trace);
2672
- return result;
2673
- }
2674
- catch (err) {
2675
- const wrapped = (0, errors_js_1.wrapPgError)(err);
2676
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, undefined, trace);
2677
- throw wrapped;
2678
- }
2679
- }
2680
2694
  let timer;
2681
- const timeoutPromise = new Promise((_, reject) => {
2682
- timer = setTimeout(() => {
2683
- abandoned = true;
2684
- reject(new errors_js_1.TimeoutError(timeout, 'Query', {
2685
- outcome: 'unknown',
2686
- message: `Query timed out after ${timeout}ms. It could not be cancelled on the server and may still ` +
2687
- 'complete, so a write may have been applied: check before retrying it.',
2688
- }));
2689
- }, timeout);
2690
- });
2695
+ const timeoutPromise = timeout
2696
+ ? new Promise((_, reject) => {
2697
+ timer = setTimeout(() => {
2698
+ abandoned = true;
2699
+ const lead = `Query timed out after ${timeout}ms. It could not be cancelled on the server`;
2700
+ reject(new errors_js_1.TimeoutError(timeout, 'Query', {
2701
+ outcome: 'unknown',
2702
+ // In a write's own savepoint, the rollback to it waits for the statement
2703
+ // to end, so the statement cannot complete after the error is settled
2704
+ // (see settledTimeout in transaction-state.ts).
2705
+ message: state?.inWriteSavepoint
2706
+ ? `${lead}.`
2707
+ : `${lead} and may still complete: check before retrying a write.`,
2708
+ }));
2709
+ }, timeout);
2710
+ })
2711
+ : undefined;
2691
2712
  try {
2692
- const result = await Promise.race([exec, timeoutPromise]);
2713
+ const result = await (timeoutPromise ? Promise.race([exec, timeoutPromise]) : exec);
2693
2714
  this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0, undefined, undefined, trace);
2694
2715
  return result;
2695
2716
  }
@@ -2709,7 +2730,7 @@ class QueryInterface {
2709
2730
  * method's to cancel or destroy).
2710
2731
  */
2711
2732
  cancelsOnTimeout() {
2712
- return !this.txScoped && this.dialect.capabilities.backendCancel && (0, utils_js_1.isNodePostgresPool)(this.pool);
2733
+ return !this.txScoped && this.dialect.capabilities.backendCancel && (0, query_utils_js_1.isNodePostgresPool)(this.pool);
2713
2734
  }
2714
2735
  /**
2715
2736
  * {@link queryWithTimeout} with a timeout the server enforces. The statement
@@ -2727,8 +2748,12 @@ class QueryInterface {
2727
2748
  * A deadline that passes while still waiting for a connection sends nothing
2728
2749
  * (`'not-executed'`). Either way the connection goes back to the pool only
2729
2750
  * once its backend is idle, so timed-out statements cannot hold the pool.
2751
+ *
2752
+ * With `state`, the transaction owns the connection: skip checkout/release
2753
+ * and retry, and cancel through its existing rollback-only settlement path.
2754
+ * The shared runner keeps statement naming, timing and query events identical.
2730
2755
  */
2731
- async queryCancellable(out, params, timeout, retryIfStale, action) {
2756
+ async queryCancellable(out, params, timeout, retryIfStale, action, state) {
2732
2757
  let trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2733
2758
  let start = performance.now();
2734
2759
  const config = out.name && this.preparedStatementsEnabled ? { name: out.name, text: out.text, values: params } : null;
@@ -2745,7 +2770,7 @@ class QueryInterface {
2745
2770
  });
2746
2771
  const timer = setTimeout(() => {
2747
2772
  expired = true;
2748
- expire(TIMED_OUT);
2773
+ expire(stream_signal_js_1.TIMED_OUT);
2749
2774
  }, timeout);
2750
2775
  const neverSent = () => new errors_js_1.TimeoutError(timeout, 'Query', {
2751
2776
  outcome: 'not-executed',
@@ -2753,27 +2778,37 @@ class QueryInterface {
2753
2778
  });
2754
2779
  try {
2755
2780
  for (let attempt = 0;; attempt++) {
2756
- const checkingOut = (0, checkout_js_1.acquireConnection)(this.pool);
2781
+ // Ambient transactions own their checkout. Only a standalone statement
2782
+ // races pool admission against the deadline and returns late checkouts.
2757
2783
  let held;
2758
- try {
2759
- held = await Promise.race([checkingOut, deadline]);
2760
- }
2761
- catch (err) {
2762
- throw report(err);
2763
- }
2764
- if (held === TIMED_OUT) {
2765
- checkingOut.then((late) => late.checkout.release(), () => { });
2766
- throw report(neverSent());
2784
+ if (!state) {
2785
+ const checkingOut = (0, checkout_js_1.acquireConnection)(this.pool);
2786
+ let admission;
2787
+ try {
2788
+ admission = await Promise.race([checkingOut, deadline]);
2789
+ }
2790
+ catch (err) {
2791
+ throw report(err);
2792
+ }
2793
+ if (admission === stream_signal_js_1.TIMED_OUT) {
2794
+ checkingOut.then((late) => late.checkout.release(), () => { });
2795
+ throw report(neverSent());
2796
+ }
2797
+ held = admission;
2767
2798
  }
2768
- const { client, checkout } = held;
2799
+ const client = held?.client ?? this.pool;
2769
2800
  const running = (config
2770
2801
  ? client.query(config)
2771
2802
  : client.query(out.text, params)).then((result) => ({ result }), (error) => ({ error }));
2772
2803
  const first = await Promise.race([running, deadline]);
2773
- const settled = first === TIMED_OUT ? await this.cancelTimedOut(held, running, timeout) : first;
2804
+ const settled = first === stream_signal_js_1.TIMED_OUT
2805
+ ? state
2806
+ ? await this.cancelInTransaction(state, running, timeout)
2807
+ : await this.cancelTimedOut(held, running, timeout)
2808
+ : first;
2774
2809
  if ('result' in settled) {
2775
- if (first !== TIMED_OUT)
2776
- checkout.release();
2810
+ if (first !== stream_signal_js_1.TIMED_OUT)
2811
+ held?.checkout.release();
2777
2812
  const rows = settled.result.rowCount ?? 0;
2778
2813
  this.emitQueryEvent(out, params, performance.now() - start, action, rows, undefined, undefined, trace);
2779
2814
  return settled.result;
@@ -2781,10 +2816,10 @@ class QueryInterface {
2781
2816
  if ('timeout' in settled)
2782
2817
  throw report(settled.timeout);
2783
2818
  const err = settled.error;
2784
- if (first === TIMED_OUT)
2819
+ if (first === stream_signal_js_1.TIMED_OUT)
2785
2820
  throw report(err);
2786
- checkout.release(err instanceof Error ? err : true);
2787
- if (!(retryIfStale && attempt === 0 && (0, errors_js_1.isStaleConnectionError)(err)))
2821
+ held?.checkout.release(err instanceof Error ? err : true);
2822
+ if (!(retryIfStale && !state && attempt === 0 && (0, errors_js_1.isStaleConnectionError)(err)))
2788
2823
  throw report(err);
2789
2824
  report(err, true);
2790
2825
  await (0, connection_guard_js_1.settleEventLoop)();
@@ -2798,128 +2833,68 @@ class QueryInterface {
2798
2833
  clearTimeout(timer);
2799
2834
  }
2800
2835
  }
2801
- /**
2802
- * A timed statement inside a transaction, cancelled on the server when the
2803
- * deadline passes, on the transaction's own connection.
2804
- *
2805
- * A cancelled statement made no change, but PostgreSQL aborts the
2806
- * transaction it ran in, so the timeout ends the transaction too: it is
2807
- * marked to roll back ({@link TransactionState.abort}), which also covers a
2808
- * cancel that arrived after the statement finished. The error is
2809
- * `outcome: 'not-executed'` either way, because nothing it did can commit.
2810
- * A statement that finishes before the deadline is returned as usual.
2811
- */
2812
- async queryCancellableInTransaction(out, params, timeout, state, action) {
2813
- const trace = (0, query_channel_js_1.startQueryTrace)(this.table, action, out.sql, params.length);
2814
- const start = performance.now();
2815
- const running = (out.name && this.preparedStatementsEnabled
2816
- ? this.pool.query({
2817
- name: out.name,
2818
- text: out.text,
2819
- values: params,
2820
- })
2821
- : this.pool.query(out.text, params)).then((result) => ({ result }), (error) => ({ error }));
2822
- let timer;
2823
- const deadline = new Promise((resolve) => {
2824
- timer = setTimeout(() => resolve(TIMED_OUT), timeout);
2825
- });
2826
- let settled;
2827
- try {
2828
- const first = await Promise.race([running, deadline]);
2829
- settled = first === TIMED_OUT ? await this.cancelInTransaction(state, running, timeout) : first;
2830
- }
2831
- finally {
2832
- clearTimeout(timer);
2833
- }
2834
- if ('result' in settled) {
2835
- const rows = settled.result.rowCount ?? 0;
2836
- this.emitQueryEvent(out, params, performance.now() - start, action, rows, undefined, undefined, trace);
2837
- return settled.result;
2838
- }
2839
- const err = 'timeout' in settled ? settled.timeout : (0, errors_js_1.wrapPgError)(settled.error);
2840
- const error = err instanceof Error ? err : undefined;
2841
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, undefined, trace);
2842
- throw err;
2843
- }
2844
- /** Cancel a timed-out statement in a transaction and end the transaction. See {@link queryCancellableInTransaction}. */
2836
+ /** Cancel a timed-out statement in a transaction and end the transaction. See {@link queryCancellable}. */
2845
2837
  async cancelInTransaction(state, running, timeout) {
2846
- let graceTimer;
2847
- const graceOver = new Promise((resolve) => {
2848
- graceTimer = setTimeout(() => resolve(TIMED_OUT), CANCEL_GRACE_MS);
2838
+ const { answer } = await (0, stream_signal_js_1.settleBackendCancel)((0, query_utils_js_1.sendCancelRequest)(state.client, stream_signal_js_1.CANCEL_GRACE_MS), running);
2839
+ if (answer !== stream_signal_js_1.TIMED_OUT && 'result' in answer)
2840
+ return answer;
2841
+ const cancelled = answer !== stream_signal_js_1.TIMED_OUT && isQueryCanceled(answer.error);
2842
+ if (answer !== stream_signal_js_1.TIMED_OUT && !cancelled)
2843
+ return answer;
2844
+ const lead = cancelled
2845
+ ? `Query timed out after ${timeout}ms and was cancelled on the server`
2846
+ : `Query timed out after ${timeout}ms, and the server did not confirm its cancellation within ${stream_signal_js_1.CANCEL_GRACE_MS}ms`;
2847
+ // In a write's own savepoint the write's other statements are still in the
2848
+ // transaction until the rollback to that savepoint answers, which then
2849
+ // decides what the error says (see settledTimeout in transaction-state.ts).
2850
+ const inWrite = state.inWriteSavepoint;
2851
+ const error = new errors_js_1.TimeoutError(timeout, 'Query', {
2852
+ outcome: inWrite ? 'unknown' : 'not-executed',
2853
+ ...(cancelled ? { cause: answer.error } : {}),
2854
+ message: inWrite
2855
+ ? `${lead}.`
2856
+ : `${lead}${cancelled ? ', so it made no change' : ''}. The transaction it ran in rolls back instead of committing.`,
2849
2857
  });
2850
- try {
2851
- await Promise.race([(0, utils_js_1.sendCancelRequest)(state.client, CANCEL_GRACE_MS), graceOver]);
2852
- const answer = await Promise.race([running, graceOver]);
2853
- if (answer !== TIMED_OUT && 'result' in answer)
2854
- return answer;
2855
- const cancelled = answer !== TIMED_OUT && isQueryCanceled(answer.error);
2856
- if (answer !== TIMED_OUT && !cancelled)
2857
- return answer;
2858
- const error = new errors_js_1.TimeoutError(timeout, 'Query', {
2859
- outcome: 'not-executed',
2860
- ...(cancelled ? { cause: answer.error } : {}),
2861
- message: (cancelled
2862
- ? `Query timed out after ${timeout}ms and was cancelled on the server, so it made no change. `
2863
- : `Query timed out after ${timeout}ms, and the server did not confirm its cancellation within ` +
2864
- `${CANCEL_GRACE_MS}ms. `) +
2865
- 'The transaction it ran in is over: it rolls back instead of committing, and no statement in it is ' +
2866
- 'kept. Let this error leave the transaction callback and retry the whole transaction, or run a ' +
2867
- 'statement that may time out in a nested `tx.$transaction(...)`, which rolls back only that block.',
2868
- });
2869
- state.abort(error);
2870
- return { timeout: error };
2871
- }
2872
- finally {
2873
- clearTimeout(graceTimer);
2874
- }
2858
+ state.abort(error);
2859
+ return { timeout: error };
2875
2860
  }
2876
2861
  /**
2877
2862
  * Cancel a statement that outlived its timeout, wait for it to answer, and
2878
2863
  * release its connection accordingly. See {@link queryCancellable}.
2879
2864
  */
2880
2865
  async cancelTimedOut(held, running, timeout) {
2881
- let graceTimer;
2882
- const graceOver = new Promise((resolve) => {
2883
- graceTimer = setTimeout(() => resolve(TIMED_OUT), CANCEL_GRACE_MS);
2884
- });
2885
- try {
2886
- const delivered = await Promise.race([(0, utils_js_1.sendCancelRequest)(held.client, CANCEL_GRACE_MS), graceOver]);
2887
- const answer = await Promise.race([running, graceOver]);
2888
- if (answer === TIMED_OUT) {
2889
- held.checkout.release(new Error('the statement did not stop after a cancel request'));
2890
- return {
2891
- timeout: new errors_js_1.TimeoutError(timeout, 'Query', {
2892
- outcome: 'unknown',
2893
- message: `Query timed out after ${timeout}ms and the server did not confirm its cancellation within ` +
2894
- `${CANCEL_GRACE_MS}ms, so it may still complete and a write may have been applied: check before ` +
2895
- 'retrying it. The connection was closed.',
2896
- }),
2897
- };
2898
- }
2899
- // A cancel that was sent but not confirmed could still land on the NEXT
2900
- // statement this connection runs, so such a connection is not reused.
2901
- const reusable = delivered === true;
2902
- if ('result' in answer) {
2903
- held.checkout.release(reusable ? undefined : true);
2904
- return answer;
2905
- }
2906
- const err = answer.error;
2907
- if (reusable && err?.code === '57014') {
2908
- held.checkout.release();
2909
- return {
2910
- timeout: new errors_js_1.TimeoutError(timeout, 'Query', {
2911
- outcome: 'not-executed',
2912
- cause: err,
2913
- message: `Query timed out after ${timeout}ms and was cancelled on the server. It made no change.`,
2914
- }),
2915
- };
2916
- }
2917
- held.checkout.release(err instanceof Error ? err : true);
2866
+ const { delivered, answer } = await (0, stream_signal_js_1.settleBackendCancel)((0, query_utils_js_1.sendCancelRequest)(held.client, stream_signal_js_1.CANCEL_GRACE_MS), running);
2867
+ if (answer === stream_signal_js_1.TIMED_OUT) {
2868
+ held.checkout.release(new Error('the statement did not stop after a cancel request'));
2869
+ return {
2870
+ timeout: new errors_js_1.TimeoutError(timeout, 'Query', {
2871
+ outcome: 'unknown',
2872
+ message: `Query timed out after ${timeout}ms and the server did not confirm its cancellation within ` +
2873
+ `${stream_signal_js_1.CANCEL_GRACE_MS}ms, so it may still complete and a write may have been applied: check before ` +
2874
+ 'retrying it. The connection was closed.',
2875
+ }),
2876
+ };
2877
+ }
2878
+ // A cancel that was sent but not confirmed could still land on the NEXT
2879
+ // statement this connection runs, so such a connection is not reused.
2880
+ const reusable = delivered === true;
2881
+ if ('result' in answer) {
2882
+ held.checkout.release(reusable ? undefined : true);
2918
2883
  return answer;
2919
2884
  }
2920
- finally {
2921
- clearTimeout(graceTimer);
2885
+ const err = answer.error;
2886
+ if (reusable && err?.code === '57014') {
2887
+ held.checkout.release();
2888
+ return {
2889
+ timeout: new errors_js_1.TimeoutError(timeout, 'Query', {
2890
+ outcome: 'not-executed',
2891
+ cause: err,
2892
+ message: `Query timed out after ${timeout}ms and was cancelled on the server. It made no change.`,
2893
+ }),
2894
+ };
2922
2895
  }
2896
+ held.checkout.release(err instanceof Error ? err : true);
2897
+ return answer;
2923
2898
  }
2924
2899
  /**
2925
2900
  * Execute a write `DeferredQuery` (create/update/delete/upsert) according to
@@ -2951,82 +2926,46 @@ class QueryInterface {
2951
2926
  * deadline is not sent. `onClient` routes them to a held connection.
2952
2927
  */
2953
2928
  deadlineExec(timeout, onClient) {
2954
- const deadline = timeout ? performance.now() + timeout : undefined;
2929
+ const left = timeout ? (0, transaction_state_js_1.writeDeadline)(timeout) : undefined;
2955
2930
  return async (sql, params, preparedName) => {
2956
- let left = timeout;
2957
- if (deadline !== undefined) {
2958
- left = Math.ceil(deadline - performance.now());
2959
- if (left <= 0) {
2960
- throw new errors_js_1.TimeoutError(timeout, 'Query', {
2961
- outcome: 'not-executed',
2962
- message: `Query timed out after ${timeout}ms: the write's statements share one deadline, and it passed ` +
2963
- 'before the next one was sent. Its earlier statements are rolled back, so it makes no change.',
2964
- });
2965
- }
2966
- }
2931
+ const ms = left?.();
2967
2932
  return onClient
2968
- ? this.queryWithTimeout(sql, params, left, preparedName, false, onClient)
2969
- : this.queryWithTimeout(sql, params, left, preparedName);
2933
+ ? this.queryWithTimeout(sql, params, ms, preparedName, false, onClient)
2934
+ : this.queryWithTimeout(sql, params, ms, preparedName);
2970
2935
  };
2971
2936
  }
2972
2937
  /**
2973
2938
  * Run a write that takes several statements as one transaction on one
2974
2939
  * connection: the caller's transaction when there is one, else one opened
2975
- * here. A statement that times out is cancelled where the engine allows it,
2976
- * and its connection is closed rather than rolled back (a ROLLBACK would wait
2977
- * behind it); the transaction never commits, so the write made no change.
2978
- * `timeout` is one deadline for every statement (see {@link deadlineExec}).
2940
+ * here and settled by {@link completeTransaction}. A statement that times
2941
+ * out ends that transaction: its running statement is cancelled where the
2942
+ * engine allows it and ROLLBACK sent, and the error says whether the server
2943
+ * confirmed the rollback. `timeout` is one deadline for every statement (see
2944
+ * {@link deadlineExec}).
2979
2945
  */
2980
2946
  async inOneTransaction(work, timeout, operation, alternative) {
2981
2947
  if (this.txScoped) {
2982
2948
  // In the caller's transaction, a savepoint keeps the write whole: a later
2983
2949
  // statement that fails and is caught cannot leave the earlier ones behind.
2950
+ // A deadline between statements made no change only once the rollback
2951
+ // to that savepoint is acknowledged (see writeDeadline).
2984
2952
  return (0, transaction_state_js_1.withSavepoint)(this.pool, () => work(this.deadlineExec(timeout)));
2985
2953
  }
2986
2954
  if (typeof this.pool.connect !== 'function') {
2987
2955
  throw new errors_js_1.UnsupportedFeatureError(`${operation} on a pool without connect()`, this.dialect.name, `${operation} runs several statements in one transaction, which needs a connection of its own, and ` +
2988
2956
  `this pool cannot check one out (a stateless HTTP driver). ${alternative}`);
2989
2957
  }
2990
- const { client, checkout } = await (0, checkout_js_1.openCheckout)(this.pool, (c) => c.query(this.dialect.beginStatement()));
2958
+ const held = await (0, checkout_js_1.openCheckout)(this.pool, (c) => (0, transaction_state_js_1.sendControl)(c, this.dialect.beginStatement()));
2959
+ const { client } = held;
2960
+ const state = new transaction_state_js_1.TransactionState(client, this.dialect);
2961
+ // Statements go through the state, so the settlement knows one is still
2962
+ // running when a timeout cuts the write short.
2991
2963
  const onClient = {
2992
- query: (text, values) => typeof text === 'string'
2964
+ query: (text, values) => state.run(() => typeof text === 'string'
2993
2965
  ? client.query(text, values)
2994
- : client.query(text),
2966
+ : client.query(text)),
2995
2967
  };
2996
- try {
2997
- const value = await work(this.deadlineExec(timeout, onClient));
2998
- await client.query(this.dialect.commitStatement());
2999
- checkout.release();
3000
- return value;
3001
- }
3002
- catch (err) {
3003
- if (err instanceof errors_js_1.TimeoutError) {
3004
- if (await (0, utils_js_1.sendCancelRequest)(client, CANCEL_GRACE_MS)) {
3005
- checkout.release(err);
3006
- }
3007
- else {
3008
- // No cancel reached the server (or the engine has none), so the
3009
- // statement may still be running. The ROLLBACK queues behind it on
3010
- // this connection, and the connection goes back to the pool only
3011
- // after it: never with the transaction still open.
3012
- client.query(this.dialect.rollbackStatement()).then(() => checkout.release(), (e) => checkout.release(e instanceof Error ? e : true));
3013
- }
3014
- throw new errors_js_1.TimeoutError(err.timeoutMs, 'Query', {
3015
- outcome: 'not-executed',
3016
- cause: err,
3017
- message: `Query timed out after ${err.timeoutMs}ms. Its transaction is rolled back rather than committed, ` +
3018
- 'so it makes no change.',
3019
- });
3020
- }
3021
- try {
3022
- await client.query(this.dialect.rollbackStatement());
3023
- }
3024
- catch {
3025
- // Best effort: the connection may be gone.
3026
- }
3027
- checkout.release();
3028
- throw (0, errors_js_1.explainConnectionLoss)((0, errors_js_1.wrapPgError)(err), checkout.lostWith);
3029
- }
2968
+ return (0, transaction_outcome_js_1.completeTransaction)(held, state, this.dialect, undefined, () => work(this.deadlineExec(timeout, onClient)));
3030
2969
  }
3031
2970
  // ---------------------------------------------------------------------------
3032
2971
  // Write compilation (extracted to writes.ts).
@@ -3124,11 +3063,11 @@ class QueryInterface {
3124
3063
  }
3125
3064
  // A copy: the query is compiled from `args`, not from what middleware
3126
3065
  // sees, so `next()` throws on a changed copy rather than doing nothing.
3127
- const params = (0, utils_js_1.readOnlyMiddlewareParams)(this.table, action, args);
3066
+ const params = (0, query_utils_js_1.readOnlyMiddlewareParams)(this.table, action, args);
3128
3067
  // Build middleware chain
3129
3068
  let index = 0;
3130
3069
  const next = async (p) => {
3131
- (0, utils_js_1.assertMiddlewareArgsKept)(params, p);
3070
+ (0, query_utils_js_1.assertMiddlewareArgsKept)(params, p);
3132
3071
  if (index < this.middlewares.length) {
3133
3072
  const mw = this.middlewares[index++];
3134
3073
  return mw(p, next);
@@ -3152,7 +3091,7 @@ class QueryInterface {
3152
3091
  // depending on every consumer to re-establish it.
3153
3092
  args = this.normalizeArgs(args);
3154
3093
  this.assertLockInTransaction(args, 'findUnique');
3155
- return this.executeWithMiddleware('findUnique', args, async () => {
3094
+ return this.executeWithMiddleware('findUnique', args, () => {
3156
3095
  if (args.with) {
3157
3096
  const strategy = this.resolveLoadStrategy(args.relationLoadStrategy);
3158
3097
  if (strategy === 'batched')
@@ -3168,8 +3107,7 @@ class QueryInterface {
3168
3107
  }
3169
3108
  }
3170
3109
  const deferred = this.buildFindUnique(args);
3171
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args.timeout, this.preparedNameFor(args, deferred.preparedName));
3172
- return deferred.transform(result);
3110
+ return this.executeRead(deferred, args);
3173
3111
  });
3174
3112
  }
3175
3113
  /**
@@ -3183,7 +3121,7 @@ class QueryInterface {
3183
3121
  args = this.normalizeArgs(args);
3184
3122
  // Stable relation order (opt-in), see runFindManyBatched.
3185
3123
  const withClause = this.resolveStableOrder(args.stableRelationOrder)
3186
- ? this.applyStableRelationOrder(args.with, this.table)
3124
+ ? (0, relation_names_js_1.applyStableRelationOrderTo)(this.schema, args.with, this.table)
3187
3125
  : args.with;
3188
3126
  // Same scope-rule parity as runFindManyBatched: reject before querying.
3189
3127
  (0, batched_loader_js_1.rejectNestedPickOrder)(withClause);
@@ -3213,6 +3151,7 @@ class QueryInterface {
3213
3151
  // Prisma compound-unique selector expansion (before global-filter merge and
3214
3152
  // fingerprinting, so the cache only ever sees the canonical expanded where).
3215
3153
  args = maybeExpandCompoundUnique(this.tableMeta, args);
3154
+ const userWhere = (args.where ?? {});
3216
3155
  // A findUnique whose `where` carries NO predicate must not run.
3217
3156
  //
3218
3157
  // `{ id: undefined }` is what `{ id: req.params.id }` becomes on a request
@@ -3232,7 +3171,7 @@ class QueryInterface {
3232
3171
  // filter" is its contract, and `where: {}` or no `where` asks for any row.
3233
3172
  // It refuses only a `where` that was emptied by `undefined` values (see
3234
3173
  // normalizeArgs), which never meant "any row".
3235
- if (whereMod.userPredicateIsEmpty(this.ctx, (args.where ?? {}))) {
3174
+ if (whereMod.userPredicateIsEmpty(this.ctx, userWhere)) {
3236
3175
  throw new errors_js_1.ValidationError(`findUnique on "${this.table}" refused: the \`where\` clause has no predicate, ` +
3237
3176
  'so this would return an arbitrary row rather than a specific one. ' +
3238
3177
  'A key whose value is `undefined` does not count, check that the value you are looking up is defined. ' +
@@ -3250,14 +3189,14 @@ class QueryInterface {
3250
3189
  // Checked against the USER's where for the same reason as the guard above:
3251
3190
  // a global filter is not an identity, and letting one satisfy this would
3252
3191
  // hand back an arbitrary row from inside the tenant.
3253
- this.assertFindUniqueKey(args.where);
3192
+ (0, compound_unique_js_1.assertWhereIdentifiesOneRow)(this.tableMeta, this.table, userWhere);
3254
3193
  // The locking clause, read by the cache key and all three SQL paths below.
3255
3194
  const rowLock = (0, row_lock_js_1.resolveRowLock)(args.lock, this.dialect, this.table);
3256
3195
  const lockSql = rowLock?.sql ?? '';
3257
3196
  // Stable relation order (opt-in): fill PK-asc orderBy into unordered to-many
3258
3197
  // relations before fingerprinting (see buildFindMany).
3259
3198
  if (args.with && this.resolveStableOrder(args.stableRelationOrder)) {
3260
- const normalized = this.applyStableRelationOrder(args.with, this.table);
3199
+ const normalized = (0, relation_names_js_1.applyStableRelationOrderTo)(this.schema, args.with, this.table);
3261
3200
  if (normalized !== args.with)
3262
3201
  args = { ...args, with: normalized };
3263
3202
  }
@@ -3269,11 +3208,9 @@ class QueryInterface {
3269
3208
  if (args.with && this.resolveLoadStrategy(args.relationLoadStrategy) === 'flatten') {
3270
3209
  this.warnFlattenBlocked('findUnique reads a single parent row, where the correlated subquery already runs once');
3271
3210
  }
3272
- const columnsList = this.resolveColumns(args.select, args.omit, includePii);
3273
- // A global filter turns the where into `{ AND: [...] }`, which the
3274
- // `isSimpleWhere` test below rejects → the general (buildWhereClause) path
3275
- // handles the merge and its params uniformly.
3276
- const whereObj = (this.mergeGlobalFilter(args.where) ?? {});
3211
+ const columnsList = relationsMod.resolveColumns(this.ctx, args.select, args.omit, includePii);
3212
+ // A global filter wraps the user where in an AND before compilation.
3213
+ const whereObj = (whereMod.mergeGlobalFilter(this.ctx, userWhere) ?? {});
3277
3214
  const colKey = columnsList ? columnsList.join(',') : '*';
3278
3215
  const whereFingerprint = this.fingerprintWhere(whereObj);
3279
3216
  const withFp = args.with ? this.withFingerprint(args.with) : '';
@@ -3285,115 +3222,33 @@ class QueryInterface {
3285
3222
  const encodingFp = `|je=${jsonEncoding === 'positional' ? 'p' : 'o'}`;
3286
3223
  // Empty without a lock, so every unlocked key is unchanged.
3287
3224
  const lockFp = rowLock ? `|lk=${rowLock.fp}` : '';
3288
- const ck = `fu:${whereFingerprint}|c=${colKey}|w=${withFp}|pii=${includePii ? 1 : 0}${encodingFp}${lockFp}${this.globalFilterCacheSegment()}`;
3225
+ const ck = `fu:${whereFingerprint}|c=${colKey}|w=${withFp}|pii=${includePii ? 1 : 0}${encodingFp}${lockFp}${whereMod.globalFilterCacheSegment(this.ctx)}`;
3289
3226
  const params = [];
3290
- // Check if all where values are simple (plain equality, no operators/null/OR).
3291
- // Keys are sorted to match fingerprintWhere, insertion order here would let
3292
- // permuted where literals share a cache entry with misaligned params.
3293
- const whereKeys = Object.keys(whereObj)
3294
- .filter((k) => whereObj[k] !== undefined)
3295
- .sort();
3296
- // Only a scalar the general path would accept as it is (a primitive, Date
3297
- // or Buffer) on a non-JSON column takes the simple path, so no operand
3298
- // reaches SQL without the general path's validation. Resolved, not looked
3299
- // up: a relation filter spelled the snake_case way must not read as a
3300
- // plain equality.
3301
- const isSimpleWhere = !whereObj.OR &&
3302
- !whereObj.AND &&
3303
- !whereObj.NOT &&
3304
- whereKeys.every((k) => {
3305
- if (!isFastPathScalar(whereObj[k]) || (0, utils_js_1.resolveRelationDef)(this.tableMeta.relations, k))
3306
- return false;
3307
- const column = (0, utils_js_1.resolveColumnName)(this.tableMeta, k);
3308
- return column !== undefined && !this.isJsonColumnType(this.getColumnPgType(column));
3309
- });
3310
- // Simple path: plain equality, no operators/null/OR.
3311
- //
3312
- // This path pushes its own params instead of going through
3313
- // `buildWhereClause`, so every VALUE transform the general walker applies
3314
- // has to be mirrored here or the two paths disagree on the same predicate.
3315
- // `coerceWhereOperand` is the one that matters: without it a `Date` keyed on
3316
- // a zone-less `date`/`timestamp`/`time` column binds raw, and a row that
3317
- // `findFirst` matches, `findUnique` silently misses. It is a value-only
3318
- // transform, so the emitted SQL and the cache key are untouched.
3319
- if (!args.with && isSimpleWhere) {
3320
- const coerce = (k, v) => whereMod.coerceWhereOperand(this.ctx, this.tableMeta, this.toColumn(k), v);
3321
- const buildSql = (freshParams) => {
3322
- const qt = this.q(this.table);
3323
- const whereClauses = whereKeys.map((k, i) => {
3324
- freshParams.push(coerce(k, whereObj[k]));
3325
- return `${this.toSqlColumn(k)} = ${this.p(i + 1)}`;
3326
- });
3327
- const whereSql = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
3328
- const selectExpr = columnsList ? columnsList.map((c) => `${qt}.${this.q(c)}`).join(', ') : `${qt}.*`;
3329
- return `SELECT ${selectExpr} FROM ${qt}${whereSql}${this.limitOneClause()}${lockSql}`;
3330
- };
3331
- const entry = this.acquireSql(ck, buildSql);
3332
- // Collect params (same order and same coercion as build)
3333
- for (const k of whereKeys) {
3334
- params.push(coerce(k, whereObj[k]));
3335
- }
3336
- this.crossCheckCache('findUnique', ck, entry, buildSql, params);
3337
- return {
3338
- sql: entry.sql,
3339
- params,
3340
- transform: (result) => {
3341
- const row = result.rows[0];
3342
- return row ? this.parseRow(row, this.table) : null;
3343
- },
3344
- tag: `${this.table}.findUnique`,
3345
- preparedName: entry.name,
3346
- ...rowLockMarker(rowLock),
3347
- };
3348
- }
3349
- // General path (with operators, null, OR, with clause)
3350
- if (!args.with) {
3351
- const buildSql = (freshParams) => {
3352
- const clause = this.buildWhereClause(whereObj, freshParams);
3353
- const whereSql = clause ? ` WHERE ${clause}` : '';
3354
- const qt = this.q(this.table);
3355
- const selectExpr = columnsList ? columnsList.map((c) => `${qt}.${this.q(c)}`).join(', ') : `${qt}.*`;
3356
- return `SELECT ${selectExpr} FROM ${qt}${whereSql}${this.limitOneClause()}${lockSql}`;
3357
- };
3358
- const entry = this.acquireSql(ck, buildSql);
3359
- // Collect params
3360
- this.collectWhereParams(whereObj, params);
3361
- this.crossCheckCache('findUnique', ck, entry, buildSql, params);
3362
- return {
3363
- sql: entry.sql,
3364
- params,
3365
- transform: (result) => {
3366
- const row = result.rows[0];
3367
- return row ? this.parseRow(row, this.table) : null;
3368
- },
3369
- tag: `${this.table}.findUnique`,
3370
- preparedName: entry.name,
3371
- ...rowLockMarker(rowLock),
3372
- };
3373
- }
3374
- // Nested queries with `with` clause.
3375
- // The param order in the original code is:
3376
- // 1. buildWhere pushes where params
3377
- // 2. buildSelectWithRelations pushes relation params to same array
3378
- // We must preserve this exact order.
3227
+ // Scalar equalities share the general compiler's validation and bind order.
3379
3228
  const buildSql = (freshParams) => {
3380
- const clause = this.buildWhereClause(whereObj, freshParams);
3381
- const whereSql = clause ? ` WHERE ${clause}` : '';
3382
- const selectClause = this.buildSelectWithRelations(this.table, args.with, freshParams, columnsList, undefined, undefined, includePii);
3383
- return `SELECT ${selectClause} FROM ${this.q(this.table)}${whereSql}${this.limitOneClause()}${lockSql}`;
3229
+ const clause = whereMod.buildWhereClause(this.ctx, whereObj, freshParams);
3230
+ const qt = this.q(this.table);
3231
+ const selectClause = args.with
3232
+ ? relationsMod.buildSelectWithRelations(this.ctx, this.table, args.with, freshParams, columnsList, undefined, undefined, includePii, undefined)
3233
+ : columnsList
3234
+ ? relationsMod.qualifiedColumns(this.ctx, columnsList, qt)
3235
+ : `${qt}.*`;
3236
+ return `SELECT ${selectClause} FROM ${qt}${clause ? ` WHERE ${clause}` : ''}${this.limitOneClause()}${lockSql}`;
3384
3237
  };
3385
3238
  const entry = this.acquireSql(ck, buildSql);
3386
- // Collect params in exact build order: where first, then with-clause relations
3387
3239
  this.collectWhereParams(whereObj, params);
3388
- this.collectWithParams(args.with, params);
3240
+ if (args.with)
3241
+ relationsMod.collectWithParams(this.ctx, args.with, params, undefined, undefined);
3389
3242
  this.crossCheckCache('findUnique', ck, entry, buildSql, params);
3390
- const parseWith = this.makeNestedParser(args.with, includePii);
3243
+ const parse = args.with
3244
+ ? relationsMod.makeNestedParser(this.ctx, args.with, includePii, undefined)
3245
+ : this.makeRowParser(this.table);
3391
3246
  return {
3392
3247
  sql: entry.sql,
3393
3248
  params,
3394
3249
  transform: (result) => {
3395
3250
  const row = result.rows[0];
3396
- return row ? parseWith(row) : null;
3251
+ return row ? parse(row) : null;
3397
3252
  },
3398
3253
  tag: `${this.table}.findUnique`,
3399
3254
  preparedName: entry.name,
@@ -3429,7 +3284,7 @@ class QueryInterface {
3429
3284
  'is by default in production.', { code: 'deep-with', table: this.table, operation: 'findMany', depth });
3430
3285
  }
3431
3286
  }
3432
- return this.executeWithMiddleware('findMany', (args ?? {}), async () => {
3287
+ return this.executeWithMiddleware('findMany', (args ?? {}), () => {
3433
3288
  if (args?.with) {
3434
3289
  const strategy = this.resolveLoadStrategy(args.relationLoadStrategy);
3435
3290
  if (strategy === 'batched')
@@ -3441,8 +3296,7 @@ class QueryInterface {
3441
3296
  }
3442
3297
  }
3443
3298
  const deferred = this.buildFindMany(args);
3444
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
3445
- return deferred.transform(result);
3299
+ return args?.with ? this.executeRead(deferred, args) : this.executeFlatRead(deferred, args);
3446
3300
  });
3447
3301
  }
3448
3302
  /**
@@ -3569,7 +3423,7 @@ class QueryInterface {
3569
3423
  // FIELD spelling, so `where: { user_id: 1 }` on a unique column did not
3570
3424
  // count as pinning it and drew a spurious unlimited-read warning the
3571
3425
  // camelCase spelling of the same query did not.
3572
- const column = (0, utils_js_1.resolveColumnName)(this.tableMeta, field);
3426
+ const column = (0, query_utils_js_1.resolveColumnName)(this.tableMeta, field);
3573
3427
  if (column === undefined)
3574
3428
  return false;
3575
3429
  pinned.add(column);
@@ -3606,7 +3460,7 @@ class QueryInterface {
3606
3460
  // relations BEFORE fingerprinting, so the two orderings get distinct cache
3607
3461
  // entries and every downstream path (SQL build, collect, parser) inherits it.
3608
3462
  if (args?.with && this.resolveStableOrder(args.stableRelationOrder)) {
3609
- const normalized = this.applyStableRelationOrder(args.with, this.table);
3463
+ const normalized = (0, relation_names_js_1.applyStableRelationOrderTo)(this.schema, args.with, this.table);
3610
3464
  if (normalized !== args.with)
3611
3465
  args = { ...args, with: normalized };
3612
3466
  }
@@ -3632,7 +3486,7 @@ class QueryInterface {
3632
3486
  if (args?.orderBy !== undefined) {
3633
3487
  const deduped = (0, filters_js_1.dedupeOrderEntries)(this.tableMeta, (0, filters_js_1.orderByEntries)(args.orderBy), this.table);
3634
3488
  if (deduped) {
3635
- (0, utils_js_1.warnRedundantSortTerm)(this.advice, this.table, 'orderBy', deduped.dropped);
3489
+ (0, query_utils_js_1.warnRedundantSortTerm)(this.advice, this.table, 'orderBy', deduped.dropped);
3636
3490
  args = {
3637
3491
  ...args,
3638
3492
  orderBy: deduped.entries.map(([k, v]) => ({ [k]: v })),
@@ -3642,7 +3496,7 @@ class QueryInterface {
3642
3496
  if (args?.distinct && args.distinct.length > 0) {
3643
3497
  const deduped = (0, filters_js_1.dedupeColumnList)(this.tableMeta, args.distinct);
3644
3498
  if (deduped) {
3645
- (0, utils_js_1.warnRedundantSortTerm)(this.advice, this.table, 'distinct', deduped.dropped);
3499
+ (0, query_utils_js_1.warnRedundantSortTerm)(this.advice, this.table, 'distinct', deduped.dropped);
3646
3500
  args = { ...args, distinct: deduped.columns };
3647
3501
  }
3648
3502
  }
@@ -3696,7 +3550,7 @@ class QueryInterface {
3696
3550
  // identically (same rule as the vector guard inside the distinct branch).
3697
3551
  if (args?.distinct && args.distinct.length > 0 && args.orderBy) {
3698
3552
  for (const [, d] of (0, filters_js_1.orderByEntries)(args.orderBy)) {
3699
- if (this.isRelationOrderByValue(d)) {
3553
+ if (relationsMod.isRelationOrderByValue(this.ctx, d)) {
3700
3554
  throw new errors_js_1.ValidationError('`distinct` cannot be combined with relation orderBy (pick-row, `_count`, or ' +
3701
3555
  'to-one relation ordering): the outer re-order cannot reference the parent table.');
3702
3556
  }
@@ -3706,12 +3560,12 @@ class QueryInterface {
3706
3560
  // the UNSAFE sentinel or nothing: a literal `true` (what a spread request
3707
3561
  // body carries) throws here rather than unlocking the projection.
3708
3562
  const includePii = (0, types_js_1.resolveUnsafeFlag)(args?.includePii, 'includePii');
3709
- const columnsList = this.resolveColumns(args?.select, args?.omit, includePii);
3563
+ const columnsList = relationsMod.resolveColumns(this.ctx, args?.select, args?.omit, includePii);
3710
3564
  const colKey = columnsList ? columnsList.join(',') : '*';
3711
3565
  // AND-merge this table's global filter into the user where; `hasWhere` gates
3712
3566
  // the build/collect just like `args?.where` did (a merged filter can make
3713
3567
  // an otherwise-absent where present).
3714
- const effWhere = this.mergeGlobalFilter(args?.where);
3568
+ const effWhere = whereMod.mergeGlobalFilter(this.ctx, args?.where);
3715
3569
  const hasWhere = effWhere !== undefined;
3716
3570
  const whereObj = (effWhere ?? {});
3717
3571
  // Build fingerprint for cache lookup
@@ -3728,8 +3582,8 @@ class QueryInterface {
3728
3582
  // itself for a column), so the two spellings of one orderBy share a
3729
3583
  // cache entry instead of minting two templates for one query.
3730
3584
  .map(([k, d]) => {
3731
- const rel = (0, utils_js_1.resolveRelation)(this.tableMeta.relations, k);
3732
- return `${rel?.name ?? k}:${this.orderByEntryFingerprint(d, rel?.def.to)}`;
3585
+ const rel = (0, query_utils_js_1.resolveRelation)(this.tableMeta.relations, k);
3586
+ return `${rel?.name ?? k}:${relationsMod.orderByEntryFingerprint(this.ctx, d, rel?.def.to)}`;
3733
3587
  })
3734
3588
  .join(',')
3735
3589
  : '';
@@ -3778,16 +3632,11 @@ class QueryInterface {
3778
3632
  const encodingFp = `|je=${jsonEncoding === 'positional' ? 'p' : 'o'}`;
3779
3633
  // Empty without a lock, so every unlocked key is unchanged.
3780
3634
  const lockFp = rowLock ? `|lk=${rowLock.fp}` : '';
3781
- const ck = `fm:${whereFp}|c=${colKey}|o=${orderFp}|l=${limitFp}|off=${offsetFp}|cur=${cursorFp}|d=${distinctFp}|w=${withFp}|pii=${includePii ? 1 : 0}${flattenFp}${encodingFp}${lockFp}${this.globalFilterCacheSegment()}`;
3635
+ const ck = `fm:${whereFp}|c=${colKey}|o=${orderFp}|l=${limitFp}|off=${offsetFp}|cur=${cursorFp}|d=${distinctFp}|w=${withFp}|pii=${includePii ? 1 : 0}${flattenFp}${encodingFp}${lockFp}${whereMod.globalFilterCacheSegment(this.ctx)}`;
3782
3636
  const params = [];
3783
3637
  const buildSql = (freshParams) => {
3784
3638
  // Fresh build: generates SQL and populates freshParams
3785
- const { sql: freshWhereSql } = hasWhere
3786
- ? (() => {
3787
- const clause = this.buildWhereClause(whereObj, freshParams);
3788
- return { sql: clause ? ` WHERE ${clause}` : '' };
3789
- })()
3790
- : { sql: '' };
3639
+ const freshWhereSql = hasWhere ? whereMod.buildWhereSql(this.ctx, whereObj, freshParams) : '';
3791
3640
  const qt = this.q(this.table);
3792
3641
  let distinctPrefix = '';
3793
3642
  let distinctCols = [];
@@ -3827,10 +3676,10 @@ class QueryInterface {
3827
3676
  const relationJoins = [];
3828
3677
  let selectClause;
3829
3678
  if (args?.with) {
3830
- selectClause = this.buildSelectWithRelations(this.table, args.with, freshParams, columnsList, undefined, undefined, includePii, flattenPlan ? { plan: flattenPlan, joinSink: relationJoins } : undefined);
3679
+ selectClause = relationsMod.buildSelectWithRelations(this.ctx, this.table, args.with, freshParams, columnsList, undefined, undefined, includePii, flattenPlan ? { plan: flattenPlan, joinSink: relationJoins } : undefined);
3831
3680
  }
3832
3681
  else if (columnsList) {
3833
- selectClause = columnsList.map((c) => `${qt}.${this.q(c)}`).join(', ');
3682
+ selectClause = relationsMod.qualifiedColumns(this.ctx, columnsList, qt);
3834
3683
  }
3835
3684
  else {
3836
3685
  selectClause = `${qt}.*`;
@@ -3863,7 +3712,7 @@ class QueryInterface {
3863
3712
  if ((0, filters_js_1.orderByEntries)(args.orderBy).some(([, d]) => (0, filters_js_1.isVectorOrderBy)(d))) {
3864
3713
  throw new errors_js_1.ValidationError('`distinct` cannot be combined with vector distance ordering.');
3865
3714
  }
3866
- const userOrder = this.buildOrderBy(args.orderBy, freshParams);
3715
+ const userOrder = relationsMod.buildOrderBy(this.ctx, args.orderBy, freshParams, undefined);
3867
3716
  // The outer level re-orders by the user's columns, which must therefore
3868
3717
  // exist in the derived table. A NARROWED projection (`select`, `omit`,
3869
3718
  // or the PII rule, which narrows with no user projection at all) left
@@ -3890,7 +3739,7 @@ class QueryInterface {
3890
3739
  extras.push(col);
3891
3740
  }
3892
3741
  if (extras.length > 0) {
3893
- innerSelect = `${selectClause}, ${extras.map((c) => `${qt}.${this.q(c)}`).join(', ')}`;
3742
+ innerSelect = `${selectClause}, ${relationsMod.qualifiedColumns(this.ctx, extras, qt)}`;
3894
3743
  outerSelect = this.distinctOuterSelectList(columnsList, args.with).join(', ');
3895
3744
  }
3896
3745
  }
@@ -3904,7 +3753,7 @@ class QueryInterface {
3904
3753
  // vector at the correct position (after cursor params, before LIMIT), and
3905
3754
  // lateralJoins so a lateral pick splices its join into the FROM clause.
3906
3755
  const orderBySql = args?.orderBy
3907
- ? ` ORDER BY ${this.buildOrderBy(args.orderBy, freshParams, lateralJoins)}`
3756
+ ? ` ORDER BY ${relationsMod.buildOrderBy(this.ctx, args.orderBy, freshParams, lateralJoins)}`
3908
3757
  : '';
3909
3758
  sql = `SELECT ${distinctPrefix}${selectClause} FROM ${qt}${relationJoins.join('')}${lateralJoins.join('')}${tail}${orderBySql}`;
3910
3759
  }
@@ -3933,7 +3782,7 @@ class QueryInterface {
3933
3782
  }
3934
3783
  // 2. WITH relation params
3935
3784
  if (args?.with) {
3936
- this.collectWithParams(args.with, params, undefined, flattenPlan);
3785
+ relationsMod.collectWithParams(this.ctx, args.with, params, undefined, flattenPlan);
3937
3786
  }
3938
3787
  // 3. Cursor params: the build's own renderer, SQL discarded.
3939
3788
  if (cursorPlan)
@@ -3957,11 +3806,13 @@ class QueryInterface {
3957
3806
  }
3958
3807
  this.crossCheckCache('findMany', ck, entry, buildSql, params);
3959
3808
  // Build the row parser once (positional shapes are computed here, not per row).
3960
- const parseWith = args?.with ? this.makeNestedParser(args.with, includePii, flattenPlan) : null;
3809
+ const parse = args?.with
3810
+ ? relationsMod.makeNestedParser(this.ctx, args.with, includePii, flattenPlan)
3811
+ : this.makeRowParser(this.table);
3961
3812
  return {
3962
3813
  sql: entry.sql,
3963
3814
  params,
3964
- transform: (result) => result.rows.map((row) => (parseWith ? parseWith(row) : this.parseRow(row, this.table))),
3815
+ transform: (result) => result.rows.map(parse),
3965
3816
  tag: `${this.table}.findMany`,
3966
3817
  preparedName: entry.name,
3967
3818
  ...rowLockMarker(rowLock),
@@ -3997,11 +3848,10 @@ class QueryInterface {
3997
3848
  // throw also lands here first, before a connection is taken.
3998
3849
  this.resolveJsonEncoding(args?.jsonEncoding);
3999
3850
  if (!args?.with) {
4000
- const table = this.table;
4001
- return (row) => this.parseRow(row, table);
3851
+ return this.makeRowParser(this.table);
4002
3852
  }
4003
3853
  const streamFlattenPlan = this.planFlatten(args, streamPii);
4004
- return this.makeNestedParser(args.with, streamPii, streamFlattenPlan);
3854
+ return relationsMod.makeNestedParser(this.ctx, args.with, streamPii, streamFlattenPlan);
4005
3855
  }
4006
3856
  /**
4007
3857
  * Everything a stream does to the DATABASE, and nothing it does to a row.
@@ -4029,7 +3879,16 @@ class QueryInterface {
4029
3879
  // Canonical args BEFORE the speculative build below, which spreads `args`
4030
3880
  // and sets its own `limit`: a surviving `take` would reach that spread
4031
3881
  // beside it and be read as a second value for one bound.
3882
+ const signal = args?.signal;
4032
3883
  args = this.normalizeArgs(args);
3884
+ const state = this.txScoped ? (0, transaction_state_js_1.transactionStateOf)(this.pool) : undefined;
3885
+ if (signal &&
3886
+ this.dialect.capabilities.backendCancel &&
3887
+ (this.txScoped
3888
+ ? !state || !this.pool.runStreamQuery || !(0, query_utils_js_1.canCancelBackend)(state.client)
3889
+ : !(0, query_utils_js_1.isNodePostgresPool)(this.pool))) {
3890
+ throw new errors_js_1.UnsupportedFeatureError('Stream cancellation', this.dialect.name, 'A native pg pool, or a scoped transaction with a protocol-cancel target, is required.');
3891
+ }
4033
3892
  const batchSize = Math.max(1, Math.floor(Number(args?.batchSize ?? 1000)));
4034
3893
  // Validated on every path, so a bad value is refused whether or not this
4035
3894
  // stream turns out to need a cursor.
@@ -4069,13 +3928,13 @@ class QueryInterface {
4069
3928
  // most expensive exactly where it was least likely to pay off: raising
4070
3929
  // `batchSize` for throughput made every large drain slower, and the stream
4071
3930
  // was the only thing here that got slower as `batchSize` went up. So the
4072
- // speculation is now bounded BY `batchSize` rather than scaled by it. At or
3931
+ // speculation is bounded BY `batchSize` rather than scaled by it. At or
4073
3932
  // below the default it is unchanged; above it, a caller asking for large
4074
- // batches has told us not to expect a one-batch result, and we go straight
3933
+ // batches has indicated a one-batch result is unlikely, so go straight
4075
3934
  // to the cursor and waste nothing. The cost of being wrong about that is
4076
3935
  // four round trips on a drain that would have fit, never any transferred
4077
3936
  // rows.
4078
- if (batchSize <= STREAM_SPECULATION_MAX_BATCH) {
3937
+ if (!signal && batchSize <= STREAM_SPECULATION_MAX_BATCH) {
4079
3938
  // The caller's bound (or the client's `defaultLimit`, exactly as findMany
4080
3939
  // applies it) caps the speculative fetch. When the bound fits in a batch
4081
3940
  // the speculative fetch IS the whole answer; otherwise `rows <= batchSize`
@@ -4101,19 +3960,38 @@ class QueryInterface {
4101
3960
  const deferred = this.buildFindMany(args);
4102
3961
  // Acquire a dedicated connection: cursors require a single connection in a
4103
3962
  // transaction. The dialect owns the streaming SQL (Postgres: BEGIN → DECLARE
4104
- // … NO SCROLL CURSOR FOR → FETCH n → CLOSE → COMMIT, ROLLBACK on error); we
4105
- // just yield the row batches it produces.
3963
+ // … NO SCROLL CURSOR FOR → FETCH n → CLOSE → COMMIT, ROLLBACK on error);
3964
+ // yield the row batches it produces.
4106
3965
  //
4107
3966
  // Inside a caller-owned transaction there is nothing to check out: the
4108
3967
  // transaction-scoped pool pins every query to the transaction's own
4109
3968
  // connection, so `pool.query` already IS that connection. The stream rides
4110
3969
  // on it, is never released here, and the dialect is told to emit no
4111
3970
  // transaction control of its own (`ambientTransaction`).
4112
- const held = this.txScoped ? null : await this.acquireConnection();
3971
+ const held = this.txScoped ? null : await this.acquireConnection(signal);
4113
3972
  const client = held?.client ?? null;
4114
- const base = client ?? {
4115
- query: async (text, values) => (await this.pool.query(text, values)),
4116
- };
3973
+ let discard = false;
3974
+ let base = client ?? this.pool;
3975
+ try {
3976
+ signal?.throwIfAborted();
3977
+ if (signal && !this.dialect.capabilities.backendCancel && !base.streamBatches)
3978
+ throw new errors_js_1.UnsupportedFeatureError('Stream cancellation', this.dialect.name, 'A native streaming handle is required.');
3979
+ if (signal && this.dialect.capabilities.backendCancel) {
3980
+ const target = state?.client ?? client;
3981
+ if (!(0, query_utils_js_1.canCancelBackend)(target))
3982
+ throw new errors_js_1.UnsupportedFeatureError('Stream cancellation', this.dialect.name, 'The acquired connection has no native protocol-cancel target.');
3983
+ base = (0, stream_signal_js_1.cancellableStreamConnection)(base, target, signal, (error) => {
3984
+ discard = true;
3985
+ state?.abort(error);
3986
+ if (error instanceof errors_js_1.ConnectionError)
3987
+ held?.checkout.release(error);
3988
+ }, state ? (send, settled) => this.pool.runStreamQuery(send, settled) : undefined);
3989
+ }
3990
+ }
3991
+ catch (error) {
3992
+ held?.checkout.release();
3993
+ throw error;
3994
+ }
4117
3995
  // The idle guard watches only a stream that holds a connection of its own
4118
3996
  // between pulls. Inside a caller's transaction the connection is theirs and
4119
3997
  // their transaction's timeout bounds it. On PostgreSQL the stream's BEGIN
@@ -4133,53 +4011,62 @@ class QueryInterface {
4133
4011
  const streamSql = this.outgoing(deferred.sql, undefined, action).text;
4134
4012
  const stream = this.dialect.openStream(conn, streamSql, deferred.params, batchSize, {
4135
4013
  ambientTransaction: this.txScoped,
4014
+ ...(signal ? { signal } : {}),
4136
4015
  });
4016
+ let closing;
4017
+ const close = () => (closing ??= (async () => {
4018
+ guard?.stop();
4019
+ signal?.removeEventListener('abort', onAbort);
4020
+ let failure;
4021
+ try {
4022
+ await stream.return(undefined);
4023
+ }
4024
+ catch (error) {
4025
+ failure = error;
4026
+ throw (0, errors_js_1.explainConnectionLoss)((0, errors_js_1.wrapPgError)(error), held?.checkout.lostWith);
4027
+ }
4028
+ finally {
4029
+ held?.checkout.release(discard || failure !== undefined ? (failure instanceof Error ? failure : true) : undefined);
4030
+ }
4031
+ })());
4032
+ const onAbort = () => {
4033
+ if (closing || idle.expired)
4034
+ return;
4035
+ idle.cancelled = { reason: signal.reason };
4036
+ // return() queues behind an active pull; the transport listener wakes it.
4037
+ // Observe a suspended consumer's cleanup failure again in finally below.
4038
+ void close().catch(() => { });
4039
+ };
4137
4040
  if (watched) {
4138
- guard = new stream_idle_js_1.StreamIdleGuard(idle, idleTimeoutMs, () => (0, stream_idle_js_1.streamIdleExpiredError)(action, this.table, idleTimeoutMs, unit), () => this.expireIdleStream(stream, held, action, idleTimeoutMs, idle, unit), backstop ? () => base.query('SELECT 1') : undefined);
4041
+ guard = new stream_idle_js_1.StreamIdleGuard(idle, idleTimeoutMs, () => (0, stream_idle_js_1.streamIdleExpiredError)(action, this.table, idleTimeoutMs, unit), () => this.expireIdleStream(close, action, idleTimeoutMs, idle, unit), backstop ? () => base.query('SELECT 1') : undefined);
4139
4042
  }
4043
+ signal?.addEventListener('abort', onAbort, { once: true });
4044
+ if (signal?.aborted)
4045
+ onAbort();
4140
4046
  try {
4141
4047
  // Driven by hand rather than `yield*`, so an expired stream's cleanup can
4142
4048
  // run from the timer while this generator is suspended.
4143
4049
  while (true) {
4050
+ (0, stream_idle_js_1.assertStreamActive)(idle);
4144
4051
  const step = await stream.next();
4052
+ (0, stream_idle_js_1.assertStreamActive)(idle);
4145
4053
  if (step.done)
4146
4054
  break;
4147
4055
  yield step.value;
4148
- if (idle.expired)
4149
- throw idle.expired;
4056
+ (0, stream_idle_js_1.assertStreamActive)(idle);
4150
4057
  }
4151
4058
  }
4152
4059
  catch (err) {
4153
- if (err === idle.expired)
4060
+ if (err === idle.expired || (idle.cancelled && err === idle.cancelled.reason))
4154
4061
  throw err;
4155
4062
  // Wrap pg constraint errors so streaming surfaces typed errors like the rest of the API
4156
4063
  throw (0, errors_js_1.explainConnectionLoss)((0, errors_js_1.wrapPgError)(err), held?.checkout.lostWith);
4157
4064
  }
4158
4065
  finally {
4159
- guard?.stop();
4160
- if (guard?.expiry) {
4161
- // The timer already closed the stream and released the connection;
4162
- // wait for that so the connection is never handed back mid-cleanup.
4066
+ if (guard?.expiry)
4163
4067
  await guard.expiry;
4164
- }
4165
- else {
4166
- try {
4167
- // An early exit (`break`) closes the cursor here; after a full drain
4168
- // or an error the dialect's generator has finished and this is a no-op.
4169
- await stream.return(undefined);
4170
- }
4171
- catch (err) {
4172
- // Only an early exit can reach this throw: after an error or a full
4173
- // drain the dialect's generator has finished and return() resolves.
4174
- // A failed CLOSE / COMMIT on an early exit must reach the caller, as
4175
- // it did when this loop was a `yield*`.
4176
- // biome-ignore lint/correctness/noUnsafeFinally: it replaces only an early-exit return, see above
4177
- throw (0, errors_js_1.explainConnectionLoss)((0, errors_js_1.wrapPgError)(err), held?.checkout.lostWith);
4178
- }
4179
- finally {
4180
- held?.checkout.release();
4181
- }
4182
- }
4068
+ else
4069
+ await close();
4183
4070
  }
4184
4071
  }
4185
4072
  /**
@@ -4189,16 +4076,12 @@ class QueryInterface {
4189
4076
  * log `stream-idle-timeout`. The log line matters: an abandoned consumer
4190
4077
  * never pulls again, so it never sees the E002 waiting for it.
4191
4078
  */
4192
- async expireIdleStream(stream, held, action, timeoutMs, idle, unit) {
4193
- let failure;
4079
+ async expireIdleStream(close, action, timeoutMs, idle, unit) {
4194
4080
  try {
4195
- await stream.return(undefined);
4196
- }
4197
- catch (err) {
4198
- failure = err;
4081
+ await close();
4199
4082
  }
4200
- finally {
4201
- held.checkout.release(failure === undefined ? undefined : failure instanceof Error ? failure : true);
4083
+ catch {
4084
+ // The idle timeout already owns the terminal error; close discarded the checkout.
4202
4085
  }
4203
4086
  (0, logger_js_1.logTo)(this.logger, 'warn', `${action} on "${this.table}" had no ${unit} requested for ${timeoutMs} ms, so Turbine closed its cursor ` +
4204
4087
  `and released its connection (${idle.rows} ${idle.rows === 1 ? 'row' : 'rows'} handed out before that). ` +
@@ -4241,10 +4124,14 @@ class QueryInterface {
4241
4124
  */
4242
4125
  async *findManyStreamBatches(args) {
4243
4126
  args = this.normalizeArgs(args);
4127
+ (0, stream_signal_js_1.resolveStreamSignal)(args?.signal);
4244
4128
  this.assertNoStreamLock(args, 'findManyStreamBatches');
4245
4129
  const parse = this.makeStreamRowParser(args);
4246
4130
  const idle = (0, stream_idle_js_1.newStreamIdleState)();
4131
+ const assertStreamOpen = this.pool.assertStreamOpen;
4247
4132
  for await (const batch of this.streamRaw(args, 'findManyStreamBatches', idle, 'batch')) {
4133
+ (0, stream_idle_js_1.assertStreamActive)(idle);
4134
+ assertStreamOpen?.();
4248
4135
  const parsed = new Array(batch.length);
4249
4136
  for (let i = 0; i < batch.length; i++) {
4250
4137
  parsed[i] = parse(batch[i]);
@@ -4256,8 +4143,8 @@ class QueryInterface {
4256
4143
  yield parsed;
4257
4144
  idle.suspended = false;
4258
4145
  idle.pulls++;
4259
- if (idle.expired)
4260
- throw idle.expired;
4146
+ (0, stream_idle_js_1.assertStreamActive)(idle);
4147
+ assertStreamOpen?.();
4261
4148
  }
4262
4149
  }
4263
4150
  /**
@@ -4297,6 +4184,7 @@ class QueryInterface {
4297
4184
  */
4298
4185
  async *findManyStream(args) {
4299
4186
  args = this.normalizeArgs(args);
4187
+ (0, stream_signal_js_1.resolveStreamSignal)(args?.signal);
4300
4188
  this.assertNoStreamLock(args, 'findManyStream');
4301
4189
  const parse = this.makeStreamRowParser(args);
4302
4190
  // Parsed one row at a time, INSIDE the yield loop rather than a batch ahead
@@ -4304,8 +4192,11 @@ class QueryInterface {
4304
4192
  // took. That laziness is the reason this loop is not written over
4305
4193
  // `findManyStreamBatches`.
4306
4194
  const idle = (0, stream_idle_js_1.newStreamIdleState)();
4195
+ const assertStreamOpen = this.pool.assertStreamOpen;
4307
4196
  for await (const batch of this.streamRaw(args, 'findManyStream', idle, 'row')) {
4308
4197
  for (let i = 0; i < batch.length; i++) {
4198
+ (0, stream_idle_js_1.assertStreamActive)(idle);
4199
+ assertStreamOpen?.();
4309
4200
  const row = parse(batch[i]);
4310
4201
  idle.rows++;
4311
4202
  // See findManyStreamBatches: the idle guard's view of the consumer.
@@ -4313,8 +4204,8 @@ class QueryInterface {
4313
4204
  yield row;
4314
4205
  idle.suspended = false;
4315
4206
  idle.pulls++;
4316
- if (idle.expired)
4317
- throw idle.expired;
4207
+ (0, stream_idle_js_1.assertStreamActive)(idle);
4208
+ assertStreamOpen?.();
4318
4209
  }
4319
4210
  }
4320
4211
  }
@@ -4349,8 +4240,7 @@ class QueryInterface {
4349
4240
  }
4350
4241
  }
4351
4242
  const deferred = this.buildFindFirst(args);
4352
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
4353
- return deferred.transform(result);
4243
+ return this.executeRead(deferred, args);
4354
4244
  });
4355
4245
  }
4356
4246
  buildFindFirst(args) {
@@ -4384,33 +4274,14 @@ class QueryInterface {
4384
4274
  async findFirstOrThrow(args) {
4385
4275
  args = this.normalizeArgs(args, 'findFirstOrThrow');
4386
4276
  this.assertLockInTransaction(args, 'findFirstOrThrow');
4387
- return this.executeWithMiddleware('findFirstOrThrow', (args ?? {}), async () => {
4277
+ return this.executeWithMiddleware('findFirstOrThrow', (args ?? {}), () => {
4388
4278
  const deferred = this.buildFindFirstOrThrow(args);
4389
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
4390
- return deferred.transform(result);
4279
+ return this.executeRead(deferred, args);
4391
4280
  });
4392
4281
  }
4393
4282
  buildFindFirstOrThrow(args) {
4394
4283
  args = this.normalizeArgs(args, 'findFirstOrThrow');
4395
- const inner = this.buildFindFirstAs(args, 'findFirstOrThrow');
4396
- return {
4397
- sql: inner.sql,
4398
- params: inner.params,
4399
- transform: (result) => {
4400
- const row = inner.transform(result);
4401
- if (row === null) {
4402
- throw new errors_js_1.NotFoundError({
4403
- table: this.table,
4404
- where: args?.where,
4405
- operation: 'findFirstOrThrow',
4406
- });
4407
- }
4408
- return row;
4409
- },
4410
- tag: `${this.table}.findFirstOrThrow`,
4411
- ...(inner.preparedName !== undefined ? { preparedName: inner.preparedName } : {}),
4412
- ...(inner.rowLock ? { rowLock: true } : {}),
4413
- };
4284
+ return this.requireFound(this.buildFindFirstAs(args, 'findFirstOrThrow'), args?.where, 'findFirstOrThrow');
4414
4285
  }
4415
4286
  // -------------------------------------------------------------------------
4416
4287
  // findUniqueOrThrow, like findUnique but throws if no record found
@@ -4418,30 +4289,27 @@ class QueryInterface {
4418
4289
  async findUniqueOrThrow(args) {
4419
4290
  args = this.normalizeArgs(args);
4420
4291
  this.assertLockInTransaction(args, 'findUniqueOrThrow');
4421
- return this.executeWithMiddleware('findUniqueOrThrow', args, async () => {
4292
+ return this.executeWithMiddleware('findUniqueOrThrow', args, () => {
4422
4293
  const deferred = this.buildFindUniqueOrThrow(args);
4423
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args.timeout, this.preparedNameFor(args, deferred.preparedName));
4424
- return deferred.transform(result);
4294
+ return this.executeRead(deferred, args);
4425
4295
  });
4426
4296
  }
4427
4297
  buildFindUniqueOrThrow(args) {
4428
4298
  args = this.normalizeArgs(args);
4429
- const inner = this.buildFindUnique(args);
4299
+ return this.requireFound(this.buildFindUnique(args), args.where, 'findUniqueOrThrow');
4300
+ }
4301
+ /** The throwing read wrappers retain the inner statement and its markers. */
4302
+ requireFound(inner, where, operation) {
4430
4303
  return {
4431
4304
  sql: inner.sql,
4432
4305
  params: inner.params,
4433
4306
  transform: (result) => {
4434
4307
  const row = inner.transform(result);
4435
- if (row === null) {
4436
- throw new errors_js_1.NotFoundError({
4437
- table: this.table,
4438
- where: args.where,
4439
- operation: 'findUniqueOrThrow',
4440
- });
4441
- }
4308
+ if (row === null)
4309
+ throw new errors_js_1.NotFoundError({ table: this.table, where, operation });
4442
4310
  return row;
4443
4311
  },
4444
- tag: `${this.table}.findUniqueOrThrow`,
4312
+ tag: `${this.table}.${operation}`,
4445
4313
  ...(inner.preparedName !== undefined ? { preparedName: inner.preparedName } : {}),
4446
4314
  ...(inner.rowLock ? { rowLock: true } : {}),
4447
4315
  };
@@ -4533,33 +4401,44 @@ class QueryInterface {
4533
4401
  // Nested write helpers (shared by create + update)
4534
4402
  // -------------------------------------------------------------------------
4535
4403
  async nestedCreate(args) {
4404
+ // Refuse before a belongsTo write or transaction can produce effects.
4405
+ writesMod.assertWritable(this.ctx, 'create');
4536
4406
  const data = args.data;
4407
+ (0, nested_write_js_1.assertNestedArrayWrites)(this.schema, this.table, data);
4537
4408
  // Validated up front, before any row is written, and then applied by the
4538
4409
  // nested engine's final read-back, which already speaks select/omit.
4539
4410
  this.resolveWriteProjection(args);
4540
4411
  const shape = { select: args.select, omit: args.omit };
4541
4412
  if (this.txScoped) {
4542
- const ctx = this.buildNestedCtx();
4413
+ const ctx = this.buildNestedCtx(args.timeout);
4543
4414
  return (0, nested_write_js_1.executeNestedCreate)(ctx, this.table, data, 0, [], shape);
4544
4415
  }
4545
4416
  return this.runInImplicitTx(async (ctx) => {
4546
4417
  const result = await (0, nested_write_js_1.executeNestedCreate)(ctx, this.table, data, 0, [], shape);
4547
4418
  return result;
4548
- });
4419
+ }, args.timeout);
4549
4420
  }
4550
4421
  async nestedUpdate(args) {
4422
+ writesMod.assertWritable(this.ctx, 'update');
4551
4423
  const data = args.data;
4552
4424
  const where = args.where;
4425
+ // The lock goes to the parent's own UPDATE, which the nested engine runs
4426
+ // before any relation write; its version column is refused in `data`
4427
+ // here, before a transaction opens, as on the flat path.
4428
+ const lock = args.optimisticLock;
4429
+ if (lock)
4430
+ writesMod.assertLockColumnNotWritten(this.tableMeta, this.table, data, lock.field);
4431
+ (0, nested_write_js_1.assertNestedArrayWrites)(this.schema, this.table, data);
4553
4432
  this.resolveWriteProjection(args);
4554
4433
  const shape = { select: args.select, omit: args.omit };
4555
4434
  if (this.txScoped) {
4556
- const ctx = this.buildNestedCtx();
4557
- return (0, nested_write_js_1.executeNestedUpdate)(ctx, this.table, where, data, 0, [], shape);
4435
+ const ctx = this.buildNestedCtx(args.timeout);
4436
+ return (0, nested_write_js_1.executeNestedUpdate)(ctx, this.table, where, data, 0, [], shape, lock);
4558
4437
  }
4559
4438
  return this.runInImplicitTx(async (ctx) => {
4560
- const result = await (0, nested_write_js_1.executeNestedUpdate)(ctx, this.table, where, data, 0, [], shape);
4439
+ const result = await (0, nested_write_js_1.executeNestedUpdate)(ctx, this.table, where, data, 0, [], shape, lock);
4561
4440
  return result;
4562
- });
4441
+ }, args.timeout);
4563
4442
  }
4564
4443
  /**
4565
4444
  * Check out a guarded pooled connection, as a typed error when that fails.
@@ -4567,10 +4446,10 @@ class QueryInterface {
4567
4446
  * matters); the cursor stream holds it, and a nested write opens its
4568
4447
  * implicit transaction on one through `openCheckout`.
4569
4448
  */
4570
- acquireConnection() {
4571
- return (0, checkout_js_1.acquireConnection)(this.pool);
4449
+ acquireConnection(signal) {
4450
+ return signal ? (0, stream_signal_js_1.acquireStreamConnection)(this.pool, signal) : (0, checkout_js_1.acquireConnection)(this.pool);
4572
4451
  }
4573
- async runInImplicitTx(fn) {
4452
+ async runInImplicitTx(fn, timeout) {
4574
4453
  // client.ts registers TransactionClient when it is evaluated (it cannot be
4575
4454
  // imported from here, see transaction-client-slot.ts). Read before the
4576
4455
  // checkout, so a program that never loaded client.ts gets a typed error
@@ -4578,14 +4457,15 @@ class QueryInterface {
4578
4457
  const TransactionClient = (0, transaction_client_slot_js_1.transactionClientFor)(`A nested write or lookup-first upsert on "${this.table}"`);
4579
4458
  // BEGIN runs inside openCheckout, which sends it once more on a fresh
4580
4459
  // connection when the first one turns out to be dead and releases the
4581
- // connection itself when BEGIN fails for good. The catch below therefore
4460
+ // connection itself when BEGIN fails for good. The settlement therefore
4582
4461
  // only sees a transaction that began, and never emits a stray ROLLBACK on
4583
4462
  // a connection that opened none.
4584
- const { client, checkout } = await (0, checkout_js_1.openCheckout)(this.pool, (c) => c.query(this.dialect.beginStatement()));
4585
- try {
4463
+ const held = await (0, checkout_js_1.openCheckout)(this.pool, (c) => (0, transaction_state_js_1.sendControl)(c, this.dialect.beginStatement()));
4464
+ const state = new transaction_state_js_1.TransactionState(held.client, this.dialect);
4465
+ return (0, transaction_outcome_js_1.completeTransaction)(held, state, this.dialect, undefined, async () => {
4586
4466
  const tx = new TransactionClient(
4587
4467
  // biome-ignore lint/suspicious/noExplicitAny: MiddlewareFn and Middleware are structurally identical
4588
- client, this.schema,
4468
+ held.client, this.schema,
4589
4469
  // biome-ignore lint/suspicious/noExplicitAny: MiddlewareFn and Middleware are structurally identical
4590
4470
  this.middlewares, this.options,
4591
4471
  // Pass the source pool so its read-only guard + capabilities carry into
@@ -4593,31 +4473,16 @@ class QueryInterface {
4593
4473
  // read-only client's nested writes bypass the E018 guard and an
4594
4474
  // older-engine client falls back to the full capability set inside the
4595
4475
  // implicit transaction.
4596
- this.pool);
4597
- const ctx = {
4476
+ this.pool, state);
4477
+ return fn({
4598
4478
  schema: this.schema,
4599
4479
  // biome-ignore lint/suspicious/noExplicitAny: TransactionClient satisfies NestedWriteContext['tx'] at runtime
4600
- tx: unlockNestedWriteTx(tx),
4480
+ tx: unlockNestedWriteTx(tx, timeout),
4601
4481
  scopedConnect: this.scopedConnect,
4602
- };
4603
- const result = await fn(ctx);
4604
- await client.query(this.dialect.commitStatement());
4605
- return result;
4606
- }
4607
- catch (err) {
4608
- try {
4609
- await client.query(this.dialect.rollbackStatement());
4610
- }
4611
- catch {
4612
- // Best-effort rollback: connection may have died.
4613
- }
4614
- throw (0, errors_js_1.explainConnectionLoss)(err, checkout.lostWith);
4615
- }
4616
- finally {
4617
- checkout.release();
4618
- }
4482
+ });
4483
+ });
4619
4484
  }
4620
- buildNestedCtx() {
4485
+ buildNestedCtx(timeout) {
4621
4486
  const pool = this.pool;
4622
4487
  const schema = this.schema;
4623
4488
  const middlewares = this.middlewares;
@@ -4627,7 +4492,7 @@ class QueryInterface {
4627
4492
  const opts = txQueryOptions(this.options);
4628
4493
  return {
4629
4494
  schema,
4630
- tx: unlockNestedWriteTx(this.makeTxProxy(pool, schema, middlewares, opts)),
4495
+ tx: unlockNestedWriteTx(this.makeTxProxy(pool, schema, middlewares, opts), timeout),
4631
4496
  };
4632
4497
  }
4633
4498
  // biome-ignore lint/suspicious/noExplicitAny: bridges MiddlewareFn[] ↔ Middleware[] and QI ↔ NestedWriteContext type gap
@@ -4655,6 +4520,7 @@ class QueryInterface {
4655
4520
  // First: the nested-write branch below decides before upsertLookupReason
4656
4521
  // would have refused it.
4657
4522
  writesMod.assertNoOptimisticLock(this.ctx, args, 'upsert');
4523
+ writesMod.assertWritable(this.ctx, 'upsert');
4658
4524
  if (this.upsertNeedsLookup(args)) {
4659
4525
  return this.upsertLookupFirst(args);
4660
4526
  }
@@ -4678,10 +4544,10 @@ class QueryInterface {
4678
4544
  * `upsert` as Prisma defines it: find the row `where` names, update it if it
4679
4545
  * exists, else insert `create`, in one transaction (the caller's, when there
4680
4546
  * is one). Taken whenever the single conflict statement would mean something
4681
- * else (`upsertLookupReason`: `where` not pinned to `create`'s values, an
4682
- * empty `update`, a global filter the engine's statement cannot carry) and
4683
- * whenever `create` or `update` holds nested relation writes, which only the
4684
- * nested-write engine can run.
4547
+ * else (`upsertLookupReason`: `where` not pinned to `create`'s values or not
4548
+ * exactly one unique key, an empty `update`, a global filter the engine's
4549
+ * statement cannot carry) and whenever `create` or `update` holds nested
4550
+ * relation writes, which only the nested-write engine can run.
4685
4551
  *
4686
4552
  * Validation is DATA-INDEPENDENT, as it is for the batched relation loader:
4687
4553
  * both halves are compiled before the lookup runs, so an unknown field in
@@ -4710,6 +4576,7 @@ class QueryInterface {
4710
4576
  const shape = { select: args.select, omit: args.omit, timeout: args.timeout };
4711
4577
  const scalarCreate = (0, nested_write_js_1.extractRelationFields)(create, this.tableMeta).scalars;
4712
4578
  const scalarUpdate = (0, nested_write_js_1.extractRelationFields)(update, this.tableMeta).scalars;
4579
+ (0, nested_write_js_1.assertNestedArrayWrites)(this.schema, this.table, [create, update]);
4713
4580
  const updateIsEmpty = Object.values(update).every((v) => v === undefined);
4714
4581
  if (Object.keys(scalarCreate).length > 0)
4715
4582
  this.buildCreate({ data: scalarCreate });
@@ -4759,24 +4626,22 @@ class QueryInterface {
4759
4626
  // -------------------------------------------------------------------------
4760
4627
  async count(args) {
4761
4628
  args = this.normalizeArgs(args);
4762
- return this.executeWithMiddleware('count', (args ?? {}), async () => {
4629
+ return this.executeWithMiddleware('count', (args ?? {}), () => {
4763
4630
  const deferred = this.buildCount(args);
4764
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
4765
- return deferred.transform(result);
4631
+ return this.executeRead(deferred, args);
4766
4632
  });
4767
4633
  }
4768
4634
  buildCount(args) {
4769
4635
  args = this.normalizeArgs(args);
4770
4636
  this.currentSkip = (0, types_js_1.resolveSkipGlobalFilters)(args?.skipGlobalFilters);
4771
- const effWhere = this.mergeGlobalFilter(args?.where);
4637
+ const effWhere = whereMod.mergeGlobalFilter(this.ctx, args?.where);
4772
4638
  const hasWhere = effWhere !== undefined;
4773
4639
  const whereObj = (effWhere ?? {});
4774
4640
  const whereFp = hasWhere ? this.fingerprintWhere(whereObj) : '';
4775
- const ck = `cnt:${whereFp}${this.globalFilterCacheSegment()}`;
4641
+ const ck = `cnt:${whereFp}${whereMod.globalFilterCacheSegment(this.ctx)}`;
4776
4642
  const params = [];
4777
4643
  const buildSql = (freshParams) => {
4778
- const clause = hasWhere ? this.buildWhereClause(whereObj, freshParams) : null;
4779
- const whereSql = clause ? ` WHERE ${clause}` : '';
4644
+ const whereSql = hasWhere ? whereMod.buildWhereSql(this.ctx, whereObj, freshParams) : '';
4780
4645
  return `SELECT ${this.castAgg('COUNT(*)', 'int')} AS count FROM ${this.q(this.table)}${whereSql}`;
4781
4646
  };
4782
4647
  const entry = this.acquireSql(ck, buildSql);
@@ -4794,10 +4659,9 @@ class QueryInterface {
4794
4659
  }
4795
4660
  async groupBy(args) {
4796
4661
  args = this.normalizeArgs(args);
4797
- return this.executeWithMiddleware('groupBy', args, async () => {
4662
+ return this.executeWithMiddleware('groupBy', args, () => {
4798
4663
  const deferred = this.buildGroupBy(args);
4799
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args.timeout, this.preparedNameFor(args, deferred.preparedName));
4800
- return deferred.transform(result);
4664
+ return this.executeRead(deferred, args);
4801
4665
  });
4802
4666
  }
4803
4667
  buildGroupBy(args) {
@@ -4810,63 +4674,14 @@ class QueryInterface {
4810
4674
  }
4811
4675
  async aggregate(args) {
4812
4676
  args = this.normalizeArgs(args);
4813
- return this.executeWithMiddleware('aggregate', args, async () => {
4677
+ return this.executeWithMiddleware('aggregate', args, () => {
4814
4678
  const deferred = this.buildAggregate(args);
4815
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args.timeout, this.preparedNameFor(args, deferred.preparedName));
4816
- return deferred.transform(result);
4679
+ return this.executeRead(deferred, args);
4817
4680
  });
4818
4681
  }
4819
- // =========================================================================
4820
- // Internal helpers
4821
- // =========================================================================
4822
- // ---------------------------------------------------------------------------
4823
- // Relation + orderBy compilation (extracted to relations.ts).
4824
- // ---------------------------------------------------------------------------
4825
- resolveColumns(select, omit, includePii) {
4826
- return relationsMod.resolveColumns(this.ctx, select, omit, includePii);
4827
- }
4828
4682
  withFingerprint(withClause, table, depth = 0) {
4829
4683
  return relationsMod.withFingerprint(this.ctx, withClause, table, depth);
4830
4684
  }
4831
- collectWithParams(withClause, params, table, flattenPlan) {
4832
- relationsMod.collectWithParams(this.ctx, withClause, params, table, flattenPlan);
4833
- }
4834
- orderByEntryFingerprint(d, targetTable) {
4835
- return relationsMod.orderByEntryFingerprint(this.ctx, d, targetTable);
4836
- }
4837
- buildOrderBy(orderBy, params, lateralSink) {
4838
- return relationsMod.buildOrderBy(this.ctx, orderBy, params, lateralSink);
4839
- }
4840
- isRelationOrderByValue(value) {
4841
- return relationsMod.isRelationOrderByValue(this.ctx, value);
4842
- }
4843
- nullsSuffix(nulls) {
4844
- return relationsMod.nullsSuffix(this.ctx, nulls);
4845
- }
4846
- resolveOrderByColumn(table, meta, key) {
4847
- return relationsMod.resolveOrderByColumn(this.ctx, table, meta, key);
4848
- }
4849
- validateJsonPathOrderBy(table, meta, field, spec) {
4850
- return relationsMod.validateJsonPathOrderBy(this.ctx, table, meta, field, spec);
4851
- }
4852
- buildJsonPathOrderEntry(table, meta, field, spec, prefix, params) {
4853
- return relationsMod.buildJsonPathOrderEntry(this.ctx, table, meta, field, spec, prefix, params);
4854
- }
4855
- collectRelationPickOrderParams(relName, relDef, spec, params) {
4856
- relationsMod.collectRelationPickOrderParams(this.ctx, relName, relDef, spec, params);
4857
- }
4858
- collectRelationCountParams(relDef, params) {
4859
- relationsMod.collectRelationCountParams(this.ctx, relDef, params);
4860
- }
4861
- getCamelDateFields(table, meta) {
4862
- return relationsMod.getCamelDateFields(this.ctx, table, meta);
4863
- }
4864
- makeNestedParser(withClause, includePii, flattenPlan) {
4865
- return relationsMod.makeNestedParser(this.ctx, withClause, includePii, flattenPlan);
4866
- }
4867
- buildSelectWithRelations(table, withClause, params, columnsList, depth, path, includePii, flatten) {
4868
- return relationsMod.buildSelectWithRelations(this.ctx, table, withClause, params, columnsList, depth, path, includePii, flatten);
4869
- }
4870
4685
  /**
4871
4686
  * Compile the `relationLoadStrategy: 'flatten'` plan for a findMany-shaped
4872
4687
  * query, or `null` to emit exactly the SQL (and cache key) the default
@@ -4884,7 +4699,7 @@ class QueryInterface {
4884
4699
  * strategy, silently and byte-identically):
4885
4700
  * - the resolved strategy is not `'flatten'`;
4886
4701
  * - `jsonEncoding: 'positional'` (a flattened relation emits no JSON at all,
4887
- * so the two are not composed in this version). NOTE that this is the
4702
+ * so the two are not composed in this version). This is the
4888
4703
  * PostgreSQL DEFAULT, so on Postgres `'flatten'` engages only when the
4889
4704
  * caller ALSO passes `jsonEncoding: 'object'`. The fallback is silent and
4890
4705
  * byte-identical, and `warnFlattenBlocked` names the encoding and the
@@ -4952,10 +4767,10 @@ class QueryInterface {
4952
4767
  * "column does not exist".
4953
4768
  */
4954
4769
  toColumn(field) {
4955
- const column = (0, utils_js_1.resolveColumnName)(this.tableMeta, field);
4770
+ const column = (0, query_utils_js_1.resolveColumnName)(this.tableMeta, field);
4956
4771
  if (column)
4957
4772
  return column;
4958
- throw new errors_js_1.ValidationError((0, utils_js_1.unknownFieldMessage)(this.table, field, this.tableMeta));
4773
+ throw new errors_js_1.ValidationError((0, query_utils_js_1.unknownFieldMessage)(this.table, field, this.tableMeta));
4959
4774
  }
4960
4775
  /** Convert camelCase field name to a double-quoted SQL identifier */
4961
4776
  toSqlColumn(field) {
@@ -4997,10 +4812,8 @@ class QueryInterface {
4997
4812
  // ---------------------------------------------------------------------------
4998
4813
  // WHERE-clause compilation (extracted to where.ts).
4999
4814
  //
5000
- // These thin delegators forward to the free functions in where.ts, passing
5001
- // this.ctx (the BuilderCtx view built in the constructor). Methods called
5002
- // only from within where.ts itself were moved out entirely; only the
5003
- // cross-module + public + @internal entry points keep a delegator here.
4815
+ // Public fingerprint/collect entry points retain their delegators. Private
4816
+ // compiler calls use the module functions directly with the same ctx.
5004
4817
  // ---------------------------------------------------------------------------
5005
4818
  fingerprintWhere(where) {
5006
4819
  return whereMod.fingerprintWhere(this.ctx, where);
@@ -5008,42 +4821,6 @@ class QueryInterface {
5008
4821
  collectWhereParams(where, params) {
5009
4822
  whereMod.collectWhereParams(this.ctx, where, params);
5010
4823
  }
5011
- resolveGlobalFilter(table, skip = this.currentSkip) {
5012
- return whereMod.resolveGlobalFilter(this.ctx, table, skip);
5013
- }
5014
- mergeGlobalFilter(userWhere) {
5015
- return whereMod.mergeGlobalFilter(this.ctx, userWhere);
5016
- }
5017
- collectTargetGlobalFilterAlias(targetTable, params) {
5018
- whereMod.collectTargetGlobalFilterAlias(this.ctx, targetTable, params);
5019
- }
5020
- globalFilterCacheSegment() {
5021
- return whereMod.globalFilterCacheSegment(this.ctx);
5022
- }
5023
- buildWhereClause(where, params) {
5024
- return whereMod.buildWhereClause(this.ctx, where, params);
5025
- }
5026
- buildAliasWhere(targetTable, targetMeta, alias, where, params) {
5027
- return whereMod.buildAliasWhere(this.ctx, targetTable, targetMeta, alias, where, params);
5028
- }
5029
- vectorOperator(field, rawColumn, metric) {
5030
- return whereMod.vectorOperator(this.ctx, field, rawColumn, metric);
5031
- }
5032
- pushVectorParam(field, _rawColumn, to, params) {
5033
- return whereMod.pushVectorParam(this.ctx, field, _rawColumn, to, params);
5034
- }
5035
- normalizeRelationFilter(relDef, filterObj) {
5036
- return whereMod.normalizeRelationFilter(this.ctx, relDef, filterObj);
5037
- }
5038
- isJsonColumnType(colType) {
5039
- return whereMod.isJsonColumnType(this.ctx, colType);
5040
- }
5041
- getColumnPgType(column) {
5042
- return whereMod.getColumnPgType(this.ctx, column);
5043
- }
5044
- jsonPathParam(path, nativeForm) {
5045
- return whereMod.jsonPathParam(this.ctx, path, nativeForm);
5046
- }
5047
4824
  /**
5048
4825
  * Collect params for an orderBy clause. Vector KNN ordering pushes the
5049
4826
  * `$n::vector` query vector and JSON-path ordering pushes its text[] path;
@@ -5051,43 +4828,7 @@ class QueryInterface {
5051
4828
  * order exactly so the cached-SQL param re-collection stays in lockstep.
5052
4829
  */
5053
4830
  collectOrderByParams(orderBy, params) {
5054
- for (const [key, dir] of (0, filters_js_1.orderByEntries)(orderBy)) {
5055
- if ((0, filters_js_1.isVectorOrderBy)(dir)) {
5056
- const rawColumn = this.toColumn(key);
5057
- // Re-run the same validation as buildOrderBy so the collect path can
5058
- // never push a param that the build path rejected (or vice versa).
5059
- this.vectorOperator(key, rawColumn, dir.distance.metric);
5060
- this.pushVectorParam(key, rawColumn, dir.distance.to, params);
5061
- continue;
5062
- }
5063
- // JSON-path ordering: mirrors buildJsonPathOrderEntry: same validation,
5064
- // then the path bound as one text[] param.
5065
- if ((0, filters_js_1.isJsonPathOrderBy)(dir)) {
5066
- this.validateJsonPathOrderBy(this.table, this.tableMeta, key, dir);
5067
- params.push(this.jsonPathParam(dir.path));
5068
- continue;
5069
- }
5070
- // To-many relation orderBy (`{ posts: { _count } }`) uses the same count
5071
- // subquery as `_count`: mirror its global-filter params. Pick-row
5072
- // ordering mirrors its full param chain (by-path / global filter /
5073
- // pick.where / pick.orderBy paths). To-one relation orderBy is mirrored
5074
- // by running its build (see collectToOneRelationOrderParams).
5075
- if (this.isRelationOrderByValue(dir)) {
5076
- // Mirrors the build path's resolution, so a cache HIT binds params for
5077
- // the same relation the cached SQL was built from.
5078
- const resolvedRel = (0, utils_js_1.resolveRelation)(this.tableMeta.relations, key);
5079
- const relDef = resolvedRel?.def;
5080
- if (relDef && (0, filters_js_1.isRelationPickOrderBy)(dir)) {
5081
- this.collectRelationPickOrderParams(resolvedRel.name, relDef, dir, params);
5082
- }
5083
- else if (relDef && (relDef.type === 'hasMany' || relDef.type === 'manyToMany')) {
5084
- this.collectRelationCountParams(relDef, params);
5085
- }
5086
- else if (relDef) {
5087
- relationsMod.collectToOneRelationOrderParams(this.ctx, key, dir, params);
5088
- }
5089
- }
5090
- }
4831
+ relationsMod.collectOrderParams(this.ctx, (0, filters_js_1.orderByEntries)(orderBy), params);
5091
4832
  }
5092
4833
  // -------------------------------------------------------------------------
5093
4834
  // Global filters (soft-delete / multi-tenancy, WS-G)
@@ -5192,7 +4933,7 @@ class QueryInterface {
5192
4933
  mapArrayTemporalInfinity(value, table, field) {
5193
4934
  let hit = false;
5194
4935
  for (let i = 0; i < value.length; i++) {
5195
- if ((0, utils_js_1.isTemporalInfinity)(value[i])) {
4936
+ if ((0, query_utils_js_1.isTemporalInfinity)(value[i])) {
5196
4937
  hit = true;
5197
4938
  break;
5198
4939
  }
@@ -5200,7 +4941,7 @@ class QueryInterface {
5200
4941
  if (!hit)
5201
4942
  return value;
5202
4943
  this.warnTemporalInfinity(table, field);
5203
- return value.map((el) => ((0, utils_js_1.isTemporalInfinity)(el) ? this.readTemporalInfinity(el) : el));
4944
+ return value.map((el) => ((0, query_utils_js_1.isTemporalInfinity)(el) ? this.readTemporalInfinity(el) : el));
5204
4945
  }
5205
4946
  /**
5206
4947
  * The configured reading of one infinity value: the JS number (`'preserve'`,
@@ -5226,7 +4967,7 @@ class QueryInterface {
5226
4967
  decodeTemporalCell(value, table, field) {
5227
4968
  if (value === null || value instanceof Date)
5228
4969
  return value;
5229
- if ((0, utils_js_1.isTemporalInfinity)(value)) {
4970
+ if ((0, query_utils_js_1.isTemporalInfinity)(value)) {
5230
4971
  // Postgres `infinity` / `-infinity`. No JS Date means either, so both
5231
4972
  // readings cost something and the default is the one that is not lossy.
5232
4973
  // `'preserve'` hands back the JS number, which breaks the declared `Date`
@@ -5260,91 +5001,53 @@ class QueryInterface {
5260
5001
  return value;
5261
5002
  // Offset-less strings (Postgres `timestamp`, json_agg output) are pinned to
5262
5003
  // UTC so results don't depend on the server's time zone.
5263
- return this.utcTimestamps ? (0, utils_js_1.parseDbDate)(String(value)) : new Date(value);
5004
+ return this.utcTimestamps ? (0, query_utils_js_1.parseDbDate)(String(value)) : new Date(value);
5264
5005
  }
5265
- /** The non-temporal decode kinds of `table`'s columns, by column and by field name. */
5006
+ /** The non-temporal decode kinds and dialect readers of one immutable table. */
5266
5007
  getCellKinds(table, meta) {
5267
- let kinds = this.cellKindCache.get(table);
5268
- if (!kinds) {
5269
- kinds = new Map();
5008
+ let cached = this.cellKindCache.get(table);
5009
+ if (!cached) {
5010
+ cached = { kinds: new Map() };
5270
5011
  for (const column of meta.columns) {
5271
5012
  // Metadata may carry the type on the column or only in the table map.
5272
5013
  const pgType = column.pgType ?? meta.pgTypes?.[column.name];
5273
5014
  if (typeof pgType !== 'string')
5274
5015
  continue;
5275
- let kind = cellKindOf(pgType, this.schema.enums);
5276
- const decode = kind === utils_js_1.CELL_PLAIN ? this.dialect.decodeColumnValue?.(pgType) : undefined;
5016
+ let kind = cellKindOf(pgType, this.schema.enums, (0, filters_js_1.columnOperandKind)(meta, column.name) === 'array');
5017
+ const decode = kind === query_utils_js_1.CELL_PLAIN ? this.dialect.decodeColumnValue?.(pgType) : undefined;
5277
5018
  if (decode !== undefined) {
5278
- kind = utils_js_1.CELL_DIALECT;
5279
- let decoders = this.dialectDecodeCache.get(table);
5280
- if (!decoders) {
5281
- decoders = new Map();
5282
- this.dialectDecodeCache.set(table, decoders);
5283
- }
5284
- decoders.set(column.name, decode);
5285
- decoders.set(column.field, decode);
5019
+ kind = query_utils_js_1.CELL_DIALECT;
5020
+ cached.decoders ??= new Map();
5021
+ cached.decoders.set(column.name, decode);
5022
+ cached.decoders.set(column.field, decode);
5286
5023
  }
5287
- if (kind === utils_js_1.CELL_PLAIN)
5024
+ if (kind === query_utils_js_1.CELL_PLAIN)
5288
5025
  continue;
5289
- kinds.set(column.name, kind);
5290
- kinds.set(column.field, kind);
5026
+ cached.kinds.set(column.name, kind);
5027
+ cached.kinds.set(column.field, kind);
5291
5028
  }
5292
- this.cellKindCache.set(table, kinds);
5029
+ this.cellKindCache.set(table, cached);
5293
5030
  }
5294
- return kinds;
5031
+ return cached;
5295
5032
  }
5296
5033
  /** One cell's decode, for every kind but {@link CELL_PLAIN}. */
5297
5034
  decodeCell(kind, value, table, field) {
5298
- switch (kind) {
5299
- case utils_js_1.CELL_TEMPORAL:
5300
- return this.decodeTemporalCell(value, table, field);
5301
- case utils_js_1.CELL_FLOAT:
5302
- return (0, utils_js_1.readJsonFloat)(value);
5303
- case utils_js_1.CELL_FLOAT_ARRAY:
5304
- return (0, utils_js_1.readJsonFloatArray)(value);
5305
- case utils_js_1.CELL_TEXT_ARRAY:
5306
- return (0, utils_js_1.readTextArray)(value);
5307
- case utils_js_1.CELL_DIALECT:
5308
- return this.decodeDialectCell(value, table, field);
5309
- default:
5035
+ if (kind === query_utils_js_1.CELL_TEMPORAL)
5036
+ return this.decodeTemporalCell(value, table, field);
5037
+ if (kind === query_utils_js_1.CELL_DIALECT) {
5038
+ if (value === null || value === undefined)
5310
5039
  return value;
5040
+ const decode = this.cellKindCache.get(table)?.decoders?.get(field);
5041
+ return decode ? decode(value) : value;
5311
5042
  }
5043
+ const read = CELL_READERS[kind];
5044
+ return read === undefined ? value : read(value);
5312
5045
  }
5313
5046
  /**
5314
- * A {@link CELL_DIALECT} cell: the dialect's decode for the column's declared
5315
- * type, recorded by {@link getCellKinds} when it classified the column.
5316
- */
5317
- decodeDialectCell(value, table, field) {
5318
- if (value === null || value === undefined)
5319
- return value;
5320
- const decode = this.dialectDecodeCache.get(table)?.get(field);
5321
- return decode ? decode(value) : value;
5322
- }
5323
- /**
5324
- * Build the decode plan for one exact column list, and remember it as this
5325
- * table's most recent shape so the next row of the same result set hits the
5326
- * fast path in {@link parseRow}.
5327
- *
5328
- * The shape key's delimiter is NUL because it is the one byte a Postgres
5329
- * identifier cannot contain, even quoted, so no table or column name can
5330
- * forge a collision. It MUST be written as the six-character escape, never
5331
- * as a literal NUL byte: a raw NUL makes byte-oriented tools classify this
5332
- * file as binary, and `grep` then reports ZERO matches for a term that is
5333
- * present rather than saying it declined to look. This is the largest file
5334
- * in the repo, and that silent empty result has already sent more than one
5335
- * search down the wrong path.
5336
- */
5337
- buildRowDecodePlan(table, meta, keys) {
5338
- const plan = this.rowDecodePlanFor(table, meta, keys);
5339
- this.rowPlanLast.set(table, plan);
5340
- return plan;
5341
- }
5342
- /**
5343
- * The cached decode plan for one exact column list, without touching the
5344
- * per-table most-recent slot. {@link buildRowDecodePlan} is the per-row entry;
5345
- * this is also what the positional nested-row plan in relations.ts reads
5346
- * (through the ctx) when it is built, so a nested row decodes by exactly the
5347
- * field names and cell kinds {@link parseRow} would give the same keys.
5047
+ * The bounded decode plan for one exact column list. Both the object parser
5048
+ * and positional relation parser use these same names and cell kinds.
5049
+ * NUL separates identifiers because it cannot occur in a SQL identifier;
5050
+ * keep it escaped in source so text tools never classify this file as binary.
5348
5051
  */
5349
5052
  rowDecodePlanFor(table, meta, keys) {
5350
5053
  const shapeKey = `${table}\u0000${keys.join('\u0000')}`;
@@ -5354,8 +5057,8 @@ class QueryInterface {
5354
5057
  const dateCols = meta.dateColumns;
5355
5058
  // camelCase-keyed date fields, so nested json_build_object rows (whose
5356
5059
  // keys are already camelCase) get the same Date coercion as top-level rows.
5357
- const camelDateFields = this.getCamelDateFields(table, meta);
5358
- const cellKinds = this.getCellKinds(table, meta);
5060
+ const camelDateFields = relationsMod.getCamelDateFields(this.ctx, table, meta);
5061
+ const { kinds: cellKinds } = this.getCellKinds(table, meta);
5359
5062
  const cols = keys.slice();
5360
5063
  const fields = [];
5361
5064
  const kinds = [];
@@ -5364,71 +5067,67 @@ class QueryInterface {
5364
5067
  fields.push(field);
5365
5068
  // Top-level rows are snake_case (dateCols); nested rows are camelCase.
5366
5069
  kinds.push(dateCols.has(col) || camelDateFields.has(field)
5367
- ? utils_js_1.CELL_TEMPORAL
5368
- : (cellKinds.get(col) ?? cellKinds.get(field) ?? utils_js_1.CELL_PLAIN));
5070
+ ? query_utils_js_1.CELL_TEMPORAL
5071
+ : (cellKinds.get(col) ?? cellKinds.get(field) ?? query_utils_js_1.CELL_PLAIN));
5369
5072
  }
5370
5073
  plan = { cols, fields, kinds };
5371
5074
  this.rowPlanCache.set(shapeKey, plan);
5372
5075
  }
5373
5076
  return plan;
5374
5077
  }
5375
- /**
5376
- * Whether a cached plan describes exactly this row's column list, in order.
5377
- * A pointer compare per column: both sides are the driver's own interned
5378
- * column-name strings, so this is far cheaper than the reverse-map lookup and
5379
- * two Set probes per column that it replaces, and unlike a length check or a
5380
- * fingerprint it CANNOT accept a different projection that happens to look
5381
- * similar. That matters more than the speed: a positional plan applied to the
5382
- * wrong column list would silently write each value under a neighbouring
5383
- * field's name, which is the one failure mode worth paying a full comparison
5384
- * to make impossible.
5385
- */
5386
- static rowPlanMatches(plan, keys) {
5387
- const cols = plan.cols;
5388
- if (cols.length !== keys.length)
5389
- return false;
5390
- for (let i = 0; i < keys.length; i++) {
5391
- if (cols[i] !== keys[i])
5392
- return false;
5393
- }
5394
- return true;
5395
- }
5396
5078
  parseRow(row, table) {
5397
- const parsed = {};
5079
+ return this.makeRowParser(table)(row);
5080
+ }
5081
+ makeRowParser(table) {
5082
+ const cached = this.rowParsers.get(table);
5083
+ if (cached)
5084
+ return cached;
5398
5085
  const meta = this.schema.tables[table];
5399
- if (meta) {
5400
- // Every row of one result set has the same columns in the same order (a
5401
- // SQL result set has fixed field descriptors, and a nested row decoded
5402
- // from `json_build_object` has a fixed key list), so the per-column
5403
- // name resolution and date-column membership tests are the same answer
5404
- // recomputed for every row. Resolve them ONCE per column shape and keep
5405
- // the plan; the shape is verified against each row rather than assumed,
5406
- // so a caller that does hand this function heterogeneous rows gets a
5407
- // rebuilt plan instead of a mis-mapped one.
5408
- const keys = Object.keys(row);
5409
- const last = this.rowPlanLast.get(table);
5410
- const plan = last !== undefined && QueryInterface.rowPlanMatches(last, keys)
5411
- ? last
5412
- : this.buildRowDecodePlan(table, meta, keys);
5413
- const { cols, fields, kinds } = plan;
5414
- for (let i = 0; i < cols.length; i++) {
5415
- const field = fields[i];
5416
- const value = row[cols[i]];
5417
- const kind = kinds[i];
5418
- // A float from the driver is already a number; only JSON's strings need reading.
5419
- parsed[field] =
5420
- kind === utils_js_1.CELL_PLAIN || (kind === utils_js_1.CELL_FLOAT && typeof value !== 'string')
5421
- ? value
5422
- : this.decodeCell(kind, value, table, field);
5086
+ let last;
5087
+ let plain;
5088
+ const parse = (row) => {
5089
+ const parsed = {};
5090
+ if (meta) {
5091
+ // Every row of one result set has the same columns in the same order (a
5092
+ // SQL result set has fixed field descriptors, and a nested row decoded
5093
+ // from `json_build_object` has a fixed key list), so the per-column
5094
+ // name resolution and date-column membership tests are the same answer
5095
+ // recomputed for every row. Resolve them ONCE per column shape and keep
5096
+ // the plan; the shape is verified against each row rather than assumed,
5097
+ // so a caller that does hand this function heterogeneous rows gets a
5098
+ // rebuilt plan instead of a mis-mapped one.
5099
+ const keys = Object.keys(row);
5100
+ // String keys use the shared comparator's exact, ordered === checks.
5101
+ if (last === undefined || !cacheParamsEqual(last.cols, keys)) {
5102
+ last = this.rowDecodePlanFor(table, meta, keys);
5103
+ plain = last.kinds.map((kind, i) => kind === query_utils_js_1.CELL_PLAIN && last.fields[i] !== '__proto__');
5104
+ }
5105
+ const { cols, fields, kinds } = last;
5106
+ // Keep this row's classification across reentrant reads of another shape.
5107
+ const plainColumns = plain;
5108
+ for (let i = 0; i < cols.length; i++) {
5109
+ const field = fields[i];
5110
+ let value = row[cols[i]];
5111
+ if (!plainColumns[i]) {
5112
+ const kind = kinds[i];
5113
+ if (field === '__proto__')
5114
+ Object.defineProperty(parsed, field, { writable: true, enumerable: true, configurable: true });
5115
+ if (kind !== query_utils_js_1.CELL_PLAIN && (kind !== query_utils_js_1.CELL_FLOAT || typeof value === 'string'))
5116
+ value = this.decodeCell(kind, value, table, field);
5117
+ }
5118
+ parsed[field] = value;
5119
+ }
5423
5120
  }
5424
- }
5425
- else {
5426
- // Fallback: no metadata, use regex conversion
5427
- for (const [col, value] of Object.entries(row)) {
5428
- parsed[(0, schema_js_1.snakeToCamel)(col)] = value;
5121
+ else {
5122
+ // Fallback: no metadata, use regex conversion
5123
+ for (const [col, value] of Object.entries(row)) {
5124
+ parsed[(0, schema_js_1.snakeToCamel)(col)] = value;
5125
+ }
5429
5126
  }
5430
- }
5431
- return parsed;
5127
+ return parsed;
5128
+ };
5129
+ this.rowParsers.set(table, parse);
5130
+ return parse;
5432
5131
  }
5433
5132
  }
5434
5133
  exports.QueryInterface = QueryInterface;