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
@@ -14,28 +14,31 @@ import { acquireConnection, openCheckout } from '../checkout.js';
14
14
  import { settleEventLoop } from '../connection-guard.js';
15
15
  import { resolveDiagnostics } from '../diagnostics.js';
16
16
  import { assertDialectCapabilities, postgresDialect } from '../dialect.js';
17
- import { explainConnectionLoss, INVARIANT_REPORT_HINT, InvariantError, isStaleConnectionError, NotFoundError, TimeoutError, UnsupportedFeatureError, ValidationError, wrapPgError, } from '../errors.js';
17
+ import { ConnectionError, explainConnectionLoss, INVARIANT_REPORT_HINT, InvariantError, isStaleConnectionError, NotFoundError, TimeoutError, UnsupportedFeatureError, ValidationError, wrapPgError, } from '../errors.js';
18
18
  import { missingIndexForRelation, schemaHasIndexInfo } from '../index-advisor.js';
19
19
  import { consoleLogger, logTo } from '../logger.js';
20
- import { executeNestedCreate, executeNestedUpdate, extractRelationFields, hasRelationFields, } from '../nested-write.js';
20
+ import { assertNestedArrayWrites, executeNestedCreate, executeNestedUpdate, extractRelationFields, hasRelationFields, } from '../nested-write.js';
21
21
  import { settleQueryTrace, startQueryTrace } from '../query-channel.js';
22
+ import { assertMiddlewareArgsKept, availableClause, boundedPreparedName, CELL_DIALECT, CELL_FLOAT, CELL_FLOAT_ARRAY, CELL_PLAIN, CELL_TEMPORAL, CELL_TEXT_ARRAY, canCancelBackend, canReadArrayRows, isNodePostgresPool, isTemporalInfinity, LRUCache, normalizePagination, ownLookup, parseDbDate, readJsonFloat, readJsonFloatArray, readOnlyMiddlewareParams, readTextArray, resolveColumnName, resolveRelation, resolveRelationDef, sendCancelRequest, sqlToPreparedName, unknownFieldMessage, warnRedundantSortTerm, } from '../query-utils.js';
22
23
  import { normalizeKeyColumns, snakeToCamel } from '../schema.js';
23
24
  import { transactionClientFor } from '../transaction-client-slot.js';
24
- import { transactionStateOf, withSavepoint } from '../transaction-state.js';
25
+ import { completeTransaction } from '../transaction-outcome.js';
26
+ import { sendControl, TransactionState, transactionStateOf, withSavepoint, writeDeadline, } from '../transaction-state.js';
25
27
  import * as aggMod from './aggregates.js';
26
28
  import { assertProjectionShape, defaultProjectionFields, includeKeysForBatching, loadRelationsBatched, neededParentKeyFields, rejectNestedPickOrder, resolveCountRelations, stripFields, } from './batched-loader.js';
27
29
  import { assertMutationWhereIdentifiesOneRow, assertWhereIdentifiesOneRow, expandCompoundUniqueWhere, uniqueKeyNames, whereIdentifiesOneRow, } from './compound-unique.js';
30
+ import { assertTupleCursorMetadata, refuseTupleCursor, tupleCursorFingerprint } from './cursor-tuple.js';
28
31
  import { resolveExcludedFromCreate } from './expr.js';
29
- import { cursorFieldValue, dedupeColumnList, dedupeOrderEntries, isEmptyOrderBy, isJsonPathOrderBy, isRelationPickOrderBy, isVectorOrderBy, normalizeOrderBy, operandColumnKind, orderByEntries, sortedEntries, } from './filters.js';
32
+ import { columnOperandKind, cursorFieldValue, dedupeColumnList, dedupeOrderEntries, isEmptyOrderBy, isJsonPathOrderBy, isVectorOrderBy, normalizeOrderBy, orderByEntries, sortedEntries, } from './filters.js';
30
33
  import { assertCursorNotEmptied, assertCursorWritten, assertWhereNotEmptiedByPruning, hasCursor, isCursorInclusive, pruneUndefinedArgs, } from './normalize-args.js';
31
34
  import { warnUnknownQueryOptions } from './option-surface.js';
32
- import { applyStableRelationOrderTo, normalizeWithClause, normalizeWithPagination } from './relation-names.js';
35
+ import { applyStableRelationOrderTo, normalizeWithClause, normalizeWithPagination, primaryKeyOrderBy, } from './relation-names.js';
33
36
  import * as relationsMod from './relations.js';
34
37
  import { lockOnStreamMessage, lockOutsideTransactionMessage, lockWithDistinctMessage, resolveRowLock, } from './row-lock.js';
35
38
  import { resolveSqlComment } from './sql-comment.js';
36
- import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, newStreamIdleState, resolveStreamIdleTimeout, StreamIdleGuard, streamBackstopStatement, streamIdleExpiredError, watchStreamConnection, } from './stream-idle.js';
39
+ import { assertStreamActive, DEFAULT_STREAM_IDLE_TIMEOUT_MS, newStreamIdleState, resolveStreamIdleTimeout, StreamIdleGuard, streamBackstopStatement, streamIdleExpiredError, watchStreamConnection, } from './stream-idle.js';
40
+ import { acquireStreamConnection, CANCEL_GRACE_MS, cancellableStreamConnection, resolveStreamSignal, settleBackendCancel, TIMED_OUT, } from './stream-signal.js';
37
41
  import { resolveSkipGlobalFilters, resolveUnsafeFlag, UNSAFE } from './types.js';
38
- import { assertMiddlewareArgsKept, availableClause, boundedPreparedName, CELL_DIALECT, CELL_FLOAT, CELL_FLOAT_ARRAY, CELL_PLAIN, CELL_TEMPORAL, CELL_TEXT_ARRAY, canCancelBackend, isNodePostgresPool, isTemporalInfinity, LRUCache, normalizePagination, ownLookup, parseDbDate, readJsonFloat, readJsonFloatArray, readOnlyMiddlewareParams, readTextArray, resolveColumnName, resolveRelation, resolveRelationDef, sendCancelRequest, sqlToPreparedName, unknownFieldMessage, warnRedundantSortTerm, } from './utils.js';
39
42
  import { resetWarnOnce, shouldWarnOnce, WARN_NS } from './warn-registry.js';
40
43
  import * as whereMod from './where.js';
41
44
  import * as writesMod from './writes.js';
@@ -104,8 +107,8 @@ const CACHE_MISMATCH_WARN_NS = 'cacheMismatch';
104
107
  * loopback TCP 0.118ms 0.000711ms ~166-236 between 200 and 400
105
108
  * +1ms/direction 2.683ms 0.000717ms ~3744-3993 between 3000 and 5000
106
109
  *
107
- * The two things that matters most in that table: the per-row penalty is
108
- * essentially IDENTICAL across the two links (it is a property of the plan, not
110
+ * Two measurements matter in that table: the per-row penalty is nearly
111
+ * identical across the two links (it is a property of the plan, not
109
112
  * the wire), while the break-even moved by 17x. So the break-even is a function
110
113
  * of the deployment's round-trip time and NOTHING ELSE that is knowable at plan
111
114
  * time. That is why this is expressed as a per-row cost and a round-trip time
@@ -240,6 +243,8 @@ const ROW_PLAN_CACHE_SIZE = 128;
240
243
  * probe's own limit.
241
244
  */
242
245
  const STREAM_SPECULATION_MAX_BATCH = 1000;
246
+ /** The context-free cell readers, indexed by the shared decode kind. */
247
+ const CELL_READERS = [undefined, undefined, readJsonFloat, readJsonFloatArray, readTextArray];
243
248
  const FLOAT_TYPES = new Set(['float4', 'float8', 'real', 'double precision']);
244
249
  const FLOAT_ARRAY_TYPES = new Set(['_float4', '_float8', 'float4[]', 'float8[]', 'real[]', 'double precision[]']);
245
250
  /**
@@ -247,12 +252,18 @@ const FLOAT_ARRAY_TYPES = new Set(['_float4', '_float8', 'float4[]', 'float8[]',
247
252
  * temporal: a float can arrive from JSON as "NaN" / "Infinity", and an enum
248
253
  * array, which the driver has no parser for, as array text.
249
254
  */
250
- function cellKindOf(pgType, enums) {
255
+ function cellKindOf(pgType, enums, array) {
251
256
  if (FLOAT_TYPES.has(pgType))
252
257
  return CELL_FLOAT;
253
258
  if (FLOAT_ARRAY_TYPES.has(pgType))
254
259
  return CELL_FLOAT_ARRAY;
255
- const element = pgType.startsWith('_') ? pgType.slice(1) : pgType.endsWith('[]') ? pgType.slice(0, -2) : undefined;
260
+ const element = !array
261
+ ? undefined
262
+ : pgType.startsWith('_')
263
+ ? pgType.slice(1)
264
+ : pgType.endsWith('[]')
265
+ ? pgType.slice(0, -2)
266
+ : undefined;
256
267
  return element !== undefined && enums !== undefined && Object.hasOwn(enums, element) ? CELL_TEXT_ARRAY : CELL_PLAIN;
257
268
  }
258
269
  /**
@@ -296,17 +307,7 @@ function cacheParamValueEqual(a, b) {
296
307
  const aArr = Array.isArray(a);
297
308
  const bArr = Array.isArray(b);
298
309
  if (aArr || bArr) {
299
- if (!aArr || !bArr)
300
- return false;
301
- const arrA = a;
302
- const arrB = b;
303
- if (arrA.length !== arrB.length)
304
- return false;
305
- for (let i = 0; i < arrA.length; i++) {
306
- if (!cacheParamValueEqual(arrA[i], arrB[i]))
307
- return false;
308
- }
309
- return true;
310
+ return aArr && bArr && cacheParamsEqual(a, b);
310
311
  }
311
312
  const objA = a;
312
313
  const objB = b;
@@ -326,8 +327,10 @@ function cacheParamValueEqual(a, b) {
326
327
  function cacheParamsEqual(a, b) {
327
328
  if (a.length !== b.length)
328
329
  return false;
329
- for (let i = 0; i < a.length; i++) {
330
- if (!cacheParamValueEqual(a[i], b[i]))
330
+ for (let i = 0; i < a.length;) {
331
+ const av = a[i];
332
+ const bv = b[i++];
333
+ if (av !== bv && !cacheParamValueEqual(av, bv))
331
334
  return false;
332
335
  }
333
336
  return true;
@@ -353,7 +356,7 @@ function maybeExpandCompoundUnique(meta, args) {
353
356
  * fully-derived predicate (the parent's own FK match, guarded there against a
354
357
  * null reference key), not caller input, and the flag is what lets that
355
358
  * unconditional-looking statement through the empty-`where` guard. Since
356
- * `allowFullTableScan` now only accepts {@link UNSAFE}, that literal `true`
359
+ * `allowFullTableScan` only accepts {@link UNSAFE}, that literal `true`
357
360
  * would throw and every nested `set` would fail.
358
361
  *
359
362
  * Rather than hand the nested-write engine the sentinel (which would put the
@@ -363,9 +366,13 @@ function maybeExpandCompoundUnique(meta, args) {
363
366
  * exactly `true`, so nothing else about the call is touched and no other
364
367
  * operation gains an escape hatch.
365
368
  *
369
+ * `timeout` bounds the nested write as one call: every statement it sends
370
+ * gets what is left of it (see `writeDeadline`).
371
+ *
366
372
  * @internal Exported for its unit test; not part of the public surface.
367
373
  */
368
- export function unlockNestedWriteTx(tx) {
374
+ export function unlockNestedWriteTx(tx, timeout) {
375
+ const deadline = timeout ? writeDeadline(timeout) : undefined;
369
376
  const wrapped = {
370
377
  table(name) {
371
378
  const handle = tx.table(name);
@@ -379,9 +386,15 @@ export function unlockNestedWriteTx(tx) {
379
386
  if (typeof value !== 'function')
380
387
  return value;
381
388
  const method = value;
382
- if (prop !== 'updateMany')
389
+ if (prop !== 'updateMany' && !deadline)
383
390
  return method.bind(target);
384
- return (args) => method.call(target, args?.allowFullTableScan === true ? { ...args, allowFullTableScan: UNSAFE } : args);
391
+ return (args) => {
392
+ const unlocked = prop === 'updateMany' && args?.allowFullTableScan === true
393
+ ? { ...args, allowFullTableScan: UNSAFE }
394
+ : args;
395
+ // Every statement of a nested write gets what is left of the call's `timeout`.
396
+ return method.call(target, deadline ? { ...unlocked, timeout: deadline() } : unlocked);
397
+ };
385
398
  },
386
399
  });
387
400
  },
@@ -438,36 +451,14 @@ function relationLoadStrategyMessage(value) {
438
451
  return (`\`relationLoadStrategy\` must be one of ${RELATION_LOAD_STRATEGIES.map((v) => `'${v}'`).join(', ')} ` +
439
452
  `(received ${describeOptionValue(value)}).`);
440
453
  }
441
- /** A value the findUnique simple path may bind as it is: a primitive, Date or Buffer. */
442
- function isFastPathScalar(value) {
443
- switch (typeof value) {
444
- case 'string':
445
- case 'number':
446
- case 'bigint':
447
- case 'boolean':
448
- return true;
449
- case 'object':
450
- return value instanceof Date || (value !== null && ArrayBuffer.isView(value));
451
- default:
452
- return false;
453
- }
454
- }
455
- /** Resolves a race when a deadline passes first. */
456
- const TIMED_OUT = Symbol('timedOut');
457
- /**
458
- * How long a statement that outlived its `timeout` gets, after the cancel
459
- * request is sent, to answer before its connection is destroyed instead of
460
- * reused. A cancel normally lands within a round trip or two.
461
- */
462
- const CANCEL_GRACE_MS = 2000;
463
454
  /** Whether `err` is PostgreSQL's query_canceled (57014), as the driver raised it or as Turbine wrapped it. */
464
455
  function isQueryCanceled(err) {
465
456
  const e = err;
466
457
  return e?.code === '57014' || e?.cause?.code === '57014';
467
458
  }
468
- /** The {@link DeferredQuery.rowLock} marker for a locking read, or nothing. */
459
+ /** A marker only for locking reads; unlocked reads allocate no marker object. */
469
460
  function rowLockMarker(rowLock) {
470
- return rowLock ? { rowLock: true } : {};
461
+ return rowLock ? { rowLock: true } : null;
471
462
  }
472
463
  /** The two accepted {@link JsonEncoding} values, frozen so the check is total. */
473
464
  const JSON_ENCODINGS = Object.freeze(['object', 'positional']);
@@ -499,9 +490,9 @@ function defaultJsonEncoding(dialect) {
499
490
  * SQL template caches shared by every QueryInterface built from ONE options
500
491
  * object, for one schema and one table.
501
492
  *
502
- * A transaction builds its own QueryInterface per table, so before this each
493
+ * A transaction builds its own QueryInterface per table, so previously each
503
494
  * `$transaction` started with an empty cache and rebuilt the SQL of every
504
- * statement it sent. TransactionClient now hands every transaction of a client
495
+ * statement it sent. TransactionClient hands every transaction of a client
505
496
  * the same options object (`txQueryOptions` in client.ts), so they share one
506
497
  * cache per table and a statement is built once per process, as it is outside
507
498
  * a transaction.
@@ -690,13 +681,15 @@ export class QueryInterface {
690
681
  * source but can be assembled per request from user input, so the key space
691
682
  * is not provably finite. Eviction only ever costs a rebuild.
692
683
  */
684
+ /** Only the last executed native projection; descriptors are snapshotted, never retained. */
685
+ arrayReadPlan;
693
686
  rowPlanCache = new LRUCache(ROW_PLAN_CACHE_SIZE);
694
687
  /**
695
- * The most recent plan per table, which is the entry `parseRow` actually
696
- * probes. One result set is one shape, so this hits for every row after the
697
- * first without hashing a cache key per row.
688
+ * Each table's row parser holds its most recent shape locally. Flat reads
689
+ * capture the parser once, so neither the table nor parser cache is looked
690
+ * up again for every row. Every row still verifies its exact own key order.
698
691
  */
699
- rowPlanLast = new Map();
692
+ rowParsers = new Map();
700
693
  /**
701
694
  * Client-level automatic WHERE filters keyed by table accessor (soft-delete /
702
695
  * multi-tenancy). AND-merged into every query on the keyed table and every
@@ -732,10 +725,8 @@ export class QueryInterface {
732
725
  * to Date as well (otherwise nested dates leak through as strings).
733
726
  */
734
727
  camelDateFieldCache = new Map();
735
- /** Per-table memo of {@link cellKindOf}, keyed by column name and field name. */
728
+ /** Per-table cell kinds and optional dialect readers, keyed by column and field name. */
736
729
  cellKindCache = new Map();
737
- /** The dialect decode of each {@link CELL_DIALECT} column, by table, then by column and field name. */
738
- dialectDecodeCache = new Map();
739
730
  /**
740
731
  * Per-table memo of `Object.entries(meta.relations)`, consumed by the nested
741
732
  * row parser (see `getRelationEntries` in relations.ts). Same rationale and
@@ -881,7 +872,7 @@ export class QueryInterface {
881
872
  options?.globalFilters && Object.keys(options.globalFilters).length > 0 ? options.globalFilters : undefined;
882
873
  this.txScoped = options?._txScoped ?? false;
883
874
  this.options = options;
884
- // Pre-compute column type lookup maps (TASK-26)
875
+ // Pre-compute column type lookup maps
885
876
  //
886
877
  // Metadata can carry a column's database type in EITHER of two places: on
887
878
  // the column entry (`dialectType` / `pgType`, what introspection and
@@ -922,9 +913,10 @@ export class QueryInterface {
922
913
  // the walk needs no public accessors on the class.
923
914
  this.whereHost = {
924
915
  tableMeta: this.tableMeta,
925
- normalizeRelationFilter: (relDef, filterObj) => this.normalizeRelationFilter(relDef, filterObj),
926
- getColumnPgType: (column) => this.getColumnPgType(column),
927
- isJsonColumnType: (colType) => this.isJsonColumnType(colType),
916
+ normalizeRelationFilter: (relDef, filterObj) => whereMod.normalizeRelationFilter(this.ctx, relDef, filterObj),
917
+ getColumnPgType: (column) => whereMod.getColumnPgType(this.ctx, column),
918
+ getColumnKind: whereMod.memoizedKinds(this.tableMeta),
919
+ isJsonColumnType: (colType) => whereMod.isJsonColumnType(this.ctx, colType),
928
920
  };
929
921
  // Bind the privacy-preserving view handed to the extracted WHERE module.
930
922
  // Data fields are immutable after this point; `currentSkip` is reassigned
@@ -980,15 +972,15 @@ export class QueryInterface {
980
972
  return meta ? this.rowDecodePlanFor(table, meta, keys) : undefined;
981
973
  },
982
974
  decodeCell: (kind, value, table, field) => this.decodeCell(kind, value, table, field),
983
- nullsSuffix: (nulls) => this.nullsSuffix(nulls),
984
- isRelationOrderByValue: (value) => this.isRelationOrderByValue(value),
985
- resolveOrderByColumn: (table, meta, key) => this.resolveOrderByColumn(table, meta, key),
986
- buildJsonPathOrderEntry: (table, meta, field, spec, prefix, params) => this.buildJsonPathOrderEntry(table, meta, field, spec, prefix, params),
975
+ nullsSuffix: (nulls) => relationsMod.nullsSuffix(this.ctx, nulls),
976
+ isRelationOrderByValue: (value) => relationsMod.isRelationOrderByValue(this.ctx, value),
977
+ resolveOrderByColumn: (table, meta, key) => relationsMod.resolveOrderByColumn(this.ctx, table, meta, key),
978
+ buildJsonPathOrderEntry: (table, meta, field, spec, prefix, params) => relationsMod.buildJsonPathOrderEntry(this.ctx, table, meta, field, spec, prefix, params),
987
979
  toSqlColumn: (field) => this.toSqlColumn(field),
988
980
  mutationInsertId: (result) => this.mutationInsertId(result),
989
981
  acquireSql: (cacheKey, build) => this.acquireSql(cacheKey, build),
990
982
  crossCheckCache: (op, cacheKey, entry, build, collectedParams) => this.crossCheckCache(op, cacheKey, entry, build, collectedParams),
991
- // LIVE getter, not a copied value: `jsonEncoding` is now a per-query
983
+ // LIVE getter, not a copied value: `jsonEncoding` is a per-query
992
984
  // option, so the module-facing view must see the encoding of the query
993
985
  // being built rather than the one the client was constructed with. Same
994
986
  // shape and same reason as `currentSkip` above.
@@ -1114,10 +1106,7 @@ export class QueryInterface {
1114
1106
  * ROWS ONLY`. No params are pushed, so the collect path is unaffected.
1115
1107
  */
1116
1108
  limitOneClause() {
1117
- if (this.dialect.buildLimitOffset) {
1118
- return this.dialect.buildLimitOffset({ limitPlaceholder: '1', offsetPlaceholder: undefined, hasOrderBy: false });
1119
- }
1120
- return ' LIMIT 1';
1109
+ return this.buildPagination('1', undefined, false);
1121
1110
  }
1122
1111
  /**
1123
1112
  * Coerce a LIMIT/OFFSET argument and validate it as a non-negative safe
@@ -1269,7 +1258,7 @@ export class QueryInterface {
1269
1258
  * `findFirstOrThrow`) that refuses a `where` whose every key was `undefined`.
1270
1259
  */
1271
1260
  normalizeArgs(args, refuseEmptiedWhere) {
1272
- const pruned = pruneUndefinedArgs(this.schema, this.table, args);
1261
+ const pruned = pruneUndefinedArgs(this.schema, this.table, args, this.dialect.capabilities.tupleCursorPredicate === true);
1273
1262
  if (pruned !== args) {
1274
1263
  if (refuseEmptiedWhere)
1275
1264
  assertWhereNotEmptiedByPruning(this.table, refuseEmptiedWhere, args, pruned);
@@ -1294,14 +1283,6 @@ export class QueryInterface {
1294
1283
  throw new ValidationError(relationLoadStrategyMessage(relationLoadStrategy));
1295
1284
  }
1296
1285
  }
1297
- /**
1298
- * Refuse a `findUnique` whose `where` names no unique key. The rule and the
1299
- * message live in query/compound-unique.ts, beside the definition of what
1300
- * counts as unique and shared with the PowDB engine.
1301
- */
1302
- assertFindUniqueKey(where) {
1303
- assertWhereIdentifiesOneRow(this.tableMeta, this.table, where);
1304
- }
1305
1286
  /**
1306
1287
  * Refuse a locking read that is not inside a transaction, at the execute
1307
1288
  * entry of each find method and before any strategy runs. The `build*`
@@ -1326,38 +1307,9 @@ export class QueryInterface {
1326
1307
  throw new ValidationError(lockOnStreamMessage(this.table, operation));
1327
1308
  }
1328
1309
  }
1329
- /**
1330
- * Fill a PK-ascending `orderBy` into every to-many `with` relation that has no
1331
- * explicit one, recursing into nested `with`. Returns a CLONED clause (user
1332
- * args are never mutated); when nothing needs filling it returns the input
1333
- * object unchanged, so the byte-identical fast path stays free. Only called
1334
- * when {@link resolveStableOrder} is true; runs BEFORE `withFingerprint`, so
1335
- * the two orderings get distinct SQL-cache entries automatically. To-one
1336
- * relations are single rows (no array to order) and PK-less targets have
1337
- * nothing stable to order by, so both are left untouched.
1338
- */
1339
- applyStableRelationOrder(withClause, table, depth = 0) {
1340
- // The transform itself lives in ./relation-names.ts as of 0.74.0, so PowDB
1341
- // runs the SAME rule instead of a second copy that accepted the option and
1342
- // did nothing.
1343
- return applyStableRelationOrderTo(this.schema, withClause, table, depth);
1344
- }
1345
1310
  // -------------------------------------------------------------------------
1346
1311
  // Deterministic pagination (unordered LIMIT/OFFSET)
1347
1312
  // -------------------------------------------------------------------------
1348
- /**
1349
- * The primary key of this table as an ascending `orderBy`, in DECLARATION
1350
- * order (a composite PK orders on every column), or `undefined` for a PK-less
1351
- * table. Field names are the camelCase accessor names, so the emitted SQL goes
1352
- * through the normal column mapping.
1353
- */
1354
- pkOrderBy() {
1355
- const pk = this.tableMeta.primaryKey ?? [];
1356
- if (pk.length === 0)
1357
- return undefined;
1358
- const fields = pk.map((c) => this.tableMeta.reverseColumnMap[c] ?? c);
1359
- return fields.length === 1 ? { [fields[0]]: 'asc' } : fields.map((f) => ({ [f]: 'asc' }));
1360
- }
1361
1313
  /** Memo for {@link totalOrderKeys}; table metadata is immutable. */
1362
1314
  totalOrderKeysMemo;
1363
1315
  /**
@@ -1415,7 +1367,7 @@ export class QueryInterface {
1415
1367
  let lastDesc = false;
1416
1368
  for (const [key, dir] of entries) {
1417
1369
  lastDesc = false;
1418
- if (isVectorOrderBy(dir) || isJsonPathOrderBy(dir) || this.isRelationOrderByValue(dir))
1370
+ if (isVectorOrderBy(dir) || isJsonPathOrderBy(dir) || relationsMod.isRelationOrderByValue(this.ctx, dir))
1419
1371
  continue;
1420
1372
  const column = resolveColumnName(this.tableMeta, key);
1421
1373
  if (column === undefined)
@@ -1463,6 +1415,9 @@ export class QueryInterface {
1463
1415
  */
1464
1416
  planCursor(args) {
1465
1417
  const raw = args.cursor;
1418
+ const tuple = args.cursorPredicate === 'tuple';
1419
+ if (tuple)
1420
+ assertTupleCursorMetadata(this.tableMeta);
1466
1421
  if (!hasCursor(raw))
1467
1422
  return { args, plan: undefined };
1468
1423
  const meta = this.tableMeta;
@@ -1480,7 +1435,7 @@ export class QueryInterface {
1480
1435
  const value = cursorFieldValue(key, written, {
1481
1436
  column,
1482
1437
  table: this.table,
1483
- kind: operandColumnKind(this.getColumnPgType(column)),
1438
+ kind: this.whereHost.getColumnKind(column),
1484
1439
  nullable: nullableColumn(column),
1485
1440
  });
1486
1441
  cursorValues.set(column, value);
@@ -1492,7 +1447,7 @@ export class QueryInterface {
1492
1447
  const terms = [];
1493
1448
  const orderEntries = orderByEntries(args.orderBy).filter(([, d]) => d !== undefined);
1494
1449
  for (const [key, dir] of orderEntries) {
1495
- if (isVectorOrderBy(dir) || isJsonPathOrderBy(dir) || this.isRelationOrderByValue(dir)) {
1450
+ if (isVectorOrderBy(dir) || isJsonPathOrderBy(dir) || relationsMod.isRelationOrderByValue(this.ctx, dir)) {
1496
1451
  throw new ValidationError(`findMany on "${this.table}" refused: \`cursor\` cannot page past the orderBy entry "${key}", which ` +
1497
1452
  'orders by a relation, a JSON path or a vector distance rather than a column. Order the cursor ' +
1498
1453
  'query by columns only, or page it with `offset`.');
@@ -1506,6 +1461,8 @@ export class QueryInterface {
1506
1461
  // Tiebreaker, the same one a first page gets (see tiebreakColumns).
1507
1462
  const tiebreak = this.tiebreakColumns(new Set(terms.map((t) => t.column)));
1508
1463
  if (!tiebreak) {
1464
+ if (tuple)
1465
+ refuseTupleCursor('Need a non-null unique key.');
1509
1466
  throw new ValidationError(`findMany on "${this.table}" refused: a \`cursor\` page needs an order with no ties, and "${this.table}" ` +
1510
1467
  'has no primary key or unique key on NOT NULL columns to break them. Add a primary key, or page ' +
1511
1468
  'this table with `offset`.');
@@ -1527,8 +1484,8 @@ export class QueryInterface {
1527
1484
  t.pin = true;
1528
1485
  pinned = true;
1529
1486
  }
1487
+ t.nullsFirst = t.nulls !== undefined ? t.nulls === 'first' : nullsSortHigh ? t.desc : !t.desc;
1530
1488
  }
1531
- const nullsFirst = (t) => t.nulls !== undefined ? t.nulls === 'first' : nullsSortHigh ? t.desc : !t.desc;
1532
1489
  let nextArgs = args;
1533
1490
  if (appended || pinned) {
1534
1491
  const orderBy = terms.map((t) => {
@@ -1540,26 +1497,27 @@ export class QueryInterface {
1540
1497
  }
1541
1498
  const inclusive = isCursorInclusive(args);
1542
1499
  const coerce = (column, value) => whereMod.coerceWhereOperand(this.ctx, meta, column, value);
1543
- const keysetTerms = terms.map((t) => ({
1544
- column: t.column,
1545
- desc: t.desc,
1546
- nullsFirst: nullsFirst(t),
1547
- nullable: t.nullable,
1548
- }));
1500
+ // The placement loop has filled every term before the plan can escape.
1501
+ const keysetTerms = terms;
1502
+ const orderFp = (values) => keysetTerms
1503
+ .map((t, i) => `${t.column}:${t.desc ? 'd' : 'a'}${t.nullable ? (t.nullsFirst ? 'f' : 'l') : ''}${values?.[i] === null ? '0' : ''}`)
1504
+ .join(',');
1505
+ // IndexMetadata.columns can omit expressions and does not prove that an
1506
+ // index uses the column's own equality/collation. Trust constraints only.
1507
+ const tupleFp = tuple ? tupleCursorFingerprint(meta, terms, cursorValues, args, inclusive, this.schema.enums) : '';
1549
1508
  // An inclusive cursor (prisma-compat) names a ROW, as Prisma's does, so it
1550
1509
  // always reads that row: a deleted cursor row gives an empty page, never a
1551
1510
  // page placed where the row used to be.
1552
- const namesRow = inclusive && whereIdentifiesOneRow(meta, flat);
1553
- if (!namesRow && terms.every((t) => cursorValues.has(t.column))) {
1511
+ const namesRow = !tuple && inclusive && whereIdentifiesOneRow(meta, flat);
1512
+ if (tuple || (!namesRow && terms.every((t) => cursorValues.has(t.column)))) {
1554
1513
  const values = terms.map((t) => {
1555
1514
  const v = cursorValues.get(t.column);
1556
1515
  return v === null ? null : coerce(t.column, v);
1557
1516
  });
1558
- const fp = `v:${keysetTerms.map((t, i) => `${t.column}:${t.desc ? 'd' : 'a'}${t.nullable ? (t.nullsFirst ? 'f' : 'l') : ''}${values[i] === null ? '0' : ''}`).join(',')}` +
1559
- (inclusive ? ':i' : '');
1517
+ const fp = tupleFp || `v:${orderFp(values)}${inclusive ? ':i' : ''}`;
1560
1518
  return {
1561
1519
  args: nextArgs,
1562
- plan: { mode: 'values', terms: keysetTerms, values, lookup: [], inclusive, fingerprint: fp },
1520
+ plan: { mode: tuple ? 'tuple' : 'values', terms: keysetTerms, values, inclusive, fingerprint: fp },
1563
1521
  };
1564
1522
  }
1565
1523
  if (!whereIdentifiesOneRow(meta, flat)) {
@@ -1571,12 +1529,12 @@ export class QueryInterface {
1571
1529
  `for every ordered field, or name the cursor row by ${keys.length > 0 ? keys.join(' or ') : 'a unique key'}.`);
1572
1530
  }
1573
1531
  const lookup = [...cursorValues].map(([column, v]) => ({ column, value: v === null ? null : coerce(column, v) }));
1574
- const fp = `r:${keysetTerms.map((t) => `${t.column}:${t.desc ? 'd' : 'a'}${t.nullable ? (t.nullsFirst ? 'f' : 'l') : ''}`).join(',')}` +
1532
+ const fp = `r:${orderFp()}` +
1575
1533
  `|k=${lookup.map((l) => `${l.column}${l.value === null ? '0' : ''}`).join(',')}` +
1576
1534
  (inclusive ? ':i' : '');
1577
1535
  return {
1578
1536
  args: nextArgs,
1579
- plan: { mode: 'row', terms: keysetTerms, values: [], lookup, inclusive, fingerprint: fp },
1537
+ plan: { mode: 'row', terms: keysetTerms, lookup, inclusive, fingerprint: fp },
1580
1538
  };
1581
1539
  }
1582
1540
  /**
@@ -1595,13 +1553,16 @@ export class QueryInterface {
1595
1553
  const col = (t) => `${qt}.${this.q(t.column)}`;
1596
1554
  let ref;
1597
1555
  let guard = '';
1598
- if (plan.mode === 'values') {
1556
+ if (plan.mode !== 'row') {
1599
1557
  const refs = plan.values.map((v) => {
1600
1558
  if (v === null)
1601
1559
  return null;
1602
1560
  params.push(v);
1603
1561
  return this.p(params.length);
1604
1562
  });
1563
+ if (plan.mode === 'tuple') {
1564
+ return `(${plan.terms.map(col).join(', ')}) ${plan.terms[0].desc ? '<' : '>'} (${refs.join(', ')})`;
1565
+ }
1605
1566
  ref = (i) => refs[i] ?? null;
1606
1567
  }
1607
1568
  else {
@@ -1714,7 +1675,7 @@ export class QueryInterface {
1714
1675
  return undefined;
1715
1676
  if (!this.isUnorderedPage(args))
1716
1677
  return undefined;
1717
- return this.pkOrderBy();
1678
+ return primaryKeyOrderBy(this.tableMeta);
1718
1679
  }
1719
1680
  /**
1720
1681
  * Advice (`diagnostics.advice`), once per query shape: an unordered paginating findMany returns a
@@ -1975,7 +1936,7 @@ export class QueryInterface {
1975
1936
  if (!schemaHasIndexInfo(this.schema) && !parentSetLarge)
1976
1937
  return null;
1977
1938
  const withClause = this.resolveStableOrder(stableFlag)
1978
- ? this.applyStableRelationOrder(withArg, this.table)
1939
+ ? applyStableRelationOrderTo(this.schema, withArg, this.table)
1979
1940
  : withArg;
1980
1941
  const split = this.partitionWithForAuto(withClause, parentSetLarge, parentBound);
1981
1942
  if (Object.keys(split.batchedWith).length === 0)
@@ -2143,7 +2104,7 @@ export class QueryInterface {
2143
2104
  // relation fetch was never affected, because that one goes through the
2144
2105
  // child's own buildFindMany and merges the filter unqualified.
2145
2106
  tableGlobalFilter: (table, ref, precedingParams) => {
2146
- const gf = this.resolveGlobalFilter(table, resolvedSkip);
2107
+ const gf = whereMod.resolveGlobalFilter(this.ctx, table, resolvedSkip);
2147
2108
  if (!gf)
2148
2109
  return null;
2149
2110
  const meta = this.schema.tables[table];
@@ -2205,7 +2166,7 @@ export class QueryInterface {
2205
2166
  // orderBy into its follow-up query, so filling the synthesized PK order here
2206
2167
  // makes the batched output deterministic exactly like the join path.
2207
2168
  const withClause = this.resolveStableOrder(args.stableRelationOrder)
2208
- ? this.applyStableRelationOrder(args.with, this.table)
2169
+ ? applyStableRelationOrderTo(this.schema, args.with, this.table)
2209
2170
  : args.with;
2210
2171
  // Scope-rule parity with the join strategy (which throws at SQL build):
2211
2172
  // reject nested pick-row ordering BEFORE the base query so acceptance
@@ -2563,6 +2524,65 @@ export class QueryInterface {
2563
2524
  readWithTimeout(sql, params, timeout, preparedName) {
2564
2525
  return this.queryWithTimeout(sql, params, timeout, preparedName, true);
2565
2526
  }
2527
+ /** One executor for compiled reads; all paths retain timeout, naming and decoding. */
2528
+ async executeRead(deferred, args) {
2529
+ const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
2530
+ return deferred.transform(result);
2531
+ }
2532
+ /** Native flat reads skip the driver's intermediate object materialization. */
2533
+ async executeFlatRead(deferred, args) {
2534
+ // Only native pg's standard text-row lifecycle is positional. Custom
2535
+ // clients, binary pools, transactions and timed reads keep object rows.
2536
+ const arrayRows = !args?.timeout &&
2537
+ !this.txScoped &&
2538
+ this.dialect.capabilities.connectionDriver === 'pg-compatible' &&
2539
+ canReadArrayRows(this.pool);
2540
+ if (!arrayRows)
2541
+ return this.executeRead(deferred, args);
2542
+ const result = await this.queryWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName), true, this.pool, true);
2543
+ if (result.fields && Array.isArray(result.rows[0])) {
2544
+ let plan = this.arrayReadPlan;
2545
+ const columns = result.fields;
2546
+ let same = plan !== undefined && plan.names.length === columns.length;
2547
+ if (same) {
2548
+ for (let i = 0; i < columns.length; i++) {
2549
+ if (plan.names[i] !== columns[i].name) {
2550
+ same = false;
2551
+ break;
2552
+ }
2553
+ }
2554
+ }
2555
+ if (!same) {
2556
+ // Object.keys reproduces pg's object enumeration: integer keys sort,
2557
+ // duplicate names retain their first position and their LAST value.
2558
+ const positions = Object.create(null);
2559
+ for (let i = 0; i < columns.length; i++)
2560
+ positions[columns[i].name] = i;
2561
+ this.arrayReadPlan = plan = {
2562
+ names: columns.map((column) => column.name),
2563
+ indices: Object.values(positions),
2564
+ decode: this.rowDecodePlanFor(this.table, this.tableMeta, Object.keys(positions)),
2565
+ };
2566
+ }
2567
+ const { fields, kinds } = plan.decode;
2568
+ const { indices } = plan;
2569
+ return result.rows.map((row) => {
2570
+ const parsed = {};
2571
+ for (let i = 0; i < fields.length; i++) {
2572
+ const field = fields[i];
2573
+ const kind = kinds[i];
2574
+ let value = row[indices[i]];
2575
+ if (field === '__proto__')
2576
+ Object.defineProperty(parsed, field, { writable: true, enumerable: true, configurable: true });
2577
+ if (kind !== CELL_PLAIN && (kind !== CELL_FLOAT || typeof value === 'string'))
2578
+ value = this.decodeCell(kind, value, this.table, field);
2579
+ parsed[field] = value;
2580
+ }
2581
+ return parsed;
2582
+ });
2583
+ }
2584
+ return deferred.transform(result);
2585
+ }
2566
2586
  /**
2567
2587
  * Execute a pool.query with an optional timeout.
2568
2588
  *
@@ -2575,7 +2595,7 @@ export class QueryInterface {
2575
2595
  * pg driver errors are translated to typed Turbine errors via wrapPgError.
2576
2596
  * `retryIfStale` is {@link readWithTimeout}'s; nothing else sets it.
2577
2597
  */
2578
- async queryWithTimeout(sql, params, requestedTimeout, preparedName, retryIfStale = false, pool = this.pool) {
2598
+ async queryWithTimeout(sql, params, requestedTimeout, preparedName, retryIfStale = false, pool = this.pool, arrayRows = false) {
2579
2599
  const action = this.currentAction;
2580
2600
  const out = this.outgoing(sql, preparedName, action);
2581
2601
  // 0 is no timeout, as it is for `$transaction`'s option and the server's statement_timeout.
@@ -2583,10 +2603,11 @@ export class QueryInterface {
2583
2603
  if (timeout !== undefined && pool === this.pool && this.cancelsOnTimeout()) {
2584
2604
  return this.queryCancellable(out, params, timeout, retryIfStale, action);
2585
2605
  }
2586
- if (timeout !== undefined && pool === this.pool && this.txScoped && this.dialect.capabilities.backendCancel) {
2587
- const state = transactionStateOf(this.pool);
2588
- if (state !== undefined && canCancelBackend(state.client)) {
2589
- return this.queryCancellableInTransaction(out, params, timeout, state, action);
2606
+ // The caller's transaction, for a timed statement that runs in one.
2607
+ const state = timeout !== undefined && pool === this.pool && this.txScoped ? transactionStateOf(pool) : undefined;
2608
+ if (timeout !== undefined && state !== undefined && this.dialect.capabilities.backendCancel) {
2609
+ if (canCancelBackend(state.client)) {
2610
+ return this.queryCancellable(out, params, timeout, false, action, state);
2590
2611
  }
2591
2612
  }
2592
2613
  let trace = startQueryTrace(this.table, action, out.sql, params.length);
@@ -2599,13 +2620,18 @@ export class QueryInterface {
2599
2620
  // cast. Guarded at runtime by `preparedStatementsEnabled`, which only the
2600
2621
  // drivers that accept it turn on.
2601
2622
  const usePrepared = out.name && this.preparedStatementsEnabled;
2602
- const send = () => usePrepared
2603
- ? pool.query({
2604
- name: out.name,
2623
+ const send = () => {
2624
+ if (!arrayRows && !usePrepared)
2625
+ return pool.query(out.text, params);
2626
+ const config = {
2627
+ name: usePrepared ? out.name : undefined,
2605
2628
  text: out.text,
2606
2629
  values: params,
2607
- })
2608
- : pool.query(out.text, params);
2630
+ };
2631
+ if (arrayRows)
2632
+ config.rowMode = 'array';
2633
+ return pool.query(config);
2634
+ };
2609
2635
  let exec = send();
2610
2636
  // Set when the caller's timeout has already answered, so a first attempt
2611
2637
  // that fails AFTER that does not send a retry nobody is waiting for.
@@ -2627,31 +2653,26 @@ export class QueryInterface {
2627
2653
  return send();
2628
2654
  });
2629
2655
  }
2630
- if (!timeout) {
2631
- try {
2632
- const result = await exec;
2633
- this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0, undefined, undefined, trace);
2634
- return result;
2635
- }
2636
- catch (err) {
2637
- const wrapped = wrapPgError(err);
2638
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, wrapped instanceof Error ? wrapped : undefined, undefined, trace);
2639
- throw wrapped;
2640
- }
2641
- }
2642
2656
  let timer;
2643
- const timeoutPromise = new Promise((_, reject) => {
2644
- timer = setTimeout(() => {
2645
- abandoned = true;
2646
- reject(new TimeoutError(timeout, 'Query', {
2647
- outcome: 'unknown',
2648
- message: `Query timed out after ${timeout}ms. It could not be cancelled on the server and may still ` +
2649
- 'complete, so a write may have been applied: check before retrying it.',
2650
- }));
2651
- }, timeout);
2652
- });
2657
+ const timeoutPromise = timeout
2658
+ ? new Promise((_, reject) => {
2659
+ timer = setTimeout(() => {
2660
+ abandoned = true;
2661
+ const lead = `Query timed out after ${timeout}ms. It could not be cancelled on the server`;
2662
+ reject(new TimeoutError(timeout, 'Query', {
2663
+ outcome: 'unknown',
2664
+ // In a write's own savepoint, the rollback to it waits for the statement
2665
+ // to end, so the statement cannot complete after the error is settled
2666
+ // (see settledTimeout in transaction-state.ts).
2667
+ message: state?.inWriteSavepoint
2668
+ ? `${lead}.`
2669
+ : `${lead} and may still complete: check before retrying a write.`,
2670
+ }));
2671
+ }, timeout);
2672
+ })
2673
+ : undefined;
2653
2674
  try {
2654
- const result = await Promise.race([exec, timeoutPromise]);
2675
+ const result = await (timeoutPromise ? Promise.race([exec, timeoutPromise]) : exec);
2655
2676
  this.emitQueryEvent(out, params, performance.now() - start, action, result.rowCount ?? 0, undefined, undefined, trace);
2656
2677
  return result;
2657
2678
  }
@@ -2689,8 +2710,12 @@ export class QueryInterface {
2689
2710
  * A deadline that passes while still waiting for a connection sends nothing
2690
2711
  * (`'not-executed'`). Either way the connection goes back to the pool only
2691
2712
  * once its backend is idle, so timed-out statements cannot hold the pool.
2713
+ *
2714
+ * With `state`, the transaction owns the connection: skip checkout/release
2715
+ * and retry, and cancel through its existing rollback-only settlement path.
2716
+ * The shared runner keeps statement naming, timing and query events identical.
2692
2717
  */
2693
- async queryCancellable(out, params, timeout, retryIfStale, action) {
2718
+ async queryCancellable(out, params, timeout, retryIfStale, action, state) {
2694
2719
  let trace = startQueryTrace(this.table, action, out.sql, params.length);
2695
2720
  let start = performance.now();
2696
2721
  const config = out.name && this.preparedStatementsEnabled ? { name: out.name, text: out.text, values: params } : null;
@@ -2715,27 +2740,37 @@ export class QueryInterface {
2715
2740
  });
2716
2741
  try {
2717
2742
  for (let attempt = 0;; attempt++) {
2718
- const checkingOut = acquireConnection(this.pool);
2743
+ // Ambient transactions own their checkout. Only a standalone statement
2744
+ // races pool admission against the deadline and returns late checkouts.
2719
2745
  let held;
2720
- try {
2721
- held = await Promise.race([checkingOut, deadline]);
2722
- }
2723
- catch (err) {
2724
- throw report(err);
2725
- }
2726
- if (held === TIMED_OUT) {
2727
- checkingOut.then((late) => late.checkout.release(), () => { });
2728
- throw report(neverSent());
2746
+ if (!state) {
2747
+ const checkingOut = acquireConnection(this.pool);
2748
+ let admission;
2749
+ try {
2750
+ admission = await Promise.race([checkingOut, deadline]);
2751
+ }
2752
+ catch (err) {
2753
+ throw report(err);
2754
+ }
2755
+ if (admission === TIMED_OUT) {
2756
+ checkingOut.then((late) => late.checkout.release(), () => { });
2757
+ throw report(neverSent());
2758
+ }
2759
+ held = admission;
2729
2760
  }
2730
- const { client, checkout } = held;
2761
+ const client = held?.client ?? this.pool;
2731
2762
  const running = (config
2732
2763
  ? client.query(config)
2733
2764
  : client.query(out.text, params)).then((result) => ({ result }), (error) => ({ error }));
2734
2765
  const first = await Promise.race([running, deadline]);
2735
- const settled = first === TIMED_OUT ? await this.cancelTimedOut(held, running, timeout) : first;
2766
+ const settled = first === TIMED_OUT
2767
+ ? state
2768
+ ? await this.cancelInTransaction(state, running, timeout)
2769
+ : await this.cancelTimedOut(held, running, timeout)
2770
+ : first;
2736
2771
  if ('result' in settled) {
2737
2772
  if (first !== TIMED_OUT)
2738
- checkout.release();
2773
+ held?.checkout.release();
2739
2774
  const rows = settled.result.rowCount ?? 0;
2740
2775
  this.emitQueryEvent(out, params, performance.now() - start, action, rows, undefined, undefined, trace);
2741
2776
  return settled.result;
@@ -2745,8 +2780,8 @@ export class QueryInterface {
2745
2780
  const err = settled.error;
2746
2781
  if (first === TIMED_OUT)
2747
2782
  throw report(err);
2748
- checkout.release(err instanceof Error ? err : true);
2749
- if (!(retryIfStale && attempt === 0 && isStaleConnectionError(err)))
2783
+ held?.checkout.release(err instanceof Error ? err : true);
2784
+ if (!(retryIfStale && !state && attempt === 0 && isStaleConnectionError(err)))
2750
2785
  throw report(err);
2751
2786
  report(err, true);
2752
2787
  await settleEventLoop();
@@ -2760,128 +2795,68 @@ export class QueryInterface {
2760
2795
  clearTimeout(timer);
2761
2796
  }
2762
2797
  }
2763
- /**
2764
- * A timed statement inside a transaction, cancelled on the server when the
2765
- * deadline passes, on the transaction's own connection.
2766
- *
2767
- * A cancelled statement made no change, but PostgreSQL aborts the
2768
- * transaction it ran in, so the timeout ends the transaction too: it is
2769
- * marked to roll back ({@link TransactionState.abort}), which also covers a
2770
- * cancel that arrived after the statement finished. The error is
2771
- * `outcome: 'not-executed'` either way, because nothing it did can commit.
2772
- * A statement that finishes before the deadline is returned as usual.
2773
- */
2774
- async queryCancellableInTransaction(out, params, timeout, state, action) {
2775
- const trace = startQueryTrace(this.table, action, out.sql, params.length);
2776
- const start = performance.now();
2777
- const running = (out.name && this.preparedStatementsEnabled
2778
- ? this.pool.query({
2779
- name: out.name,
2780
- text: out.text,
2781
- values: params,
2782
- })
2783
- : this.pool.query(out.text, params)).then((result) => ({ result }), (error) => ({ error }));
2784
- let timer;
2785
- const deadline = new Promise((resolve) => {
2786
- timer = setTimeout(() => resolve(TIMED_OUT), timeout);
2787
- });
2788
- let settled;
2789
- try {
2790
- const first = await Promise.race([running, deadline]);
2791
- settled = first === TIMED_OUT ? await this.cancelInTransaction(state, running, timeout) : first;
2792
- }
2793
- finally {
2794
- clearTimeout(timer);
2795
- }
2796
- if ('result' in settled) {
2797
- const rows = settled.result.rowCount ?? 0;
2798
- this.emitQueryEvent(out, params, performance.now() - start, action, rows, undefined, undefined, trace);
2799
- return settled.result;
2800
- }
2801
- const err = 'timeout' in settled ? settled.timeout : wrapPgError(settled.error);
2802
- const error = err instanceof Error ? err : undefined;
2803
- this.emitQueryEvent(out, params, performance.now() - start, action, 0, error, undefined, trace);
2804
- throw err;
2805
- }
2806
- /** Cancel a timed-out statement in a transaction and end the transaction. See {@link queryCancellableInTransaction}. */
2798
+ /** Cancel a timed-out statement in a transaction and end the transaction. See {@link queryCancellable}. */
2807
2799
  async cancelInTransaction(state, running, timeout) {
2808
- let graceTimer;
2809
- const graceOver = new Promise((resolve) => {
2810
- graceTimer = setTimeout(() => resolve(TIMED_OUT), CANCEL_GRACE_MS);
2800
+ const { answer } = await settleBackendCancel(sendCancelRequest(state.client, CANCEL_GRACE_MS), running);
2801
+ if (answer !== TIMED_OUT && 'result' in answer)
2802
+ return answer;
2803
+ const cancelled = answer !== TIMED_OUT && isQueryCanceled(answer.error);
2804
+ if (answer !== TIMED_OUT && !cancelled)
2805
+ return answer;
2806
+ const lead = cancelled
2807
+ ? `Query timed out after ${timeout}ms and was cancelled on the server`
2808
+ : `Query timed out after ${timeout}ms, and the server did not confirm its cancellation within ${CANCEL_GRACE_MS}ms`;
2809
+ // In a write's own savepoint the write's other statements are still in the
2810
+ // transaction until the rollback to that savepoint answers, which then
2811
+ // decides what the error says (see settledTimeout in transaction-state.ts).
2812
+ const inWrite = state.inWriteSavepoint;
2813
+ const error = new TimeoutError(timeout, 'Query', {
2814
+ outcome: inWrite ? 'unknown' : 'not-executed',
2815
+ ...(cancelled ? { cause: answer.error } : {}),
2816
+ message: inWrite
2817
+ ? `${lead}.`
2818
+ : `${lead}${cancelled ? ', so it made no change' : ''}. The transaction it ran in rolls back instead of committing.`,
2811
2819
  });
2812
- try {
2813
- await Promise.race([sendCancelRequest(state.client, CANCEL_GRACE_MS), graceOver]);
2814
- const answer = await Promise.race([running, graceOver]);
2815
- if (answer !== TIMED_OUT && 'result' in answer)
2816
- return answer;
2817
- const cancelled = answer !== TIMED_OUT && isQueryCanceled(answer.error);
2818
- if (answer !== TIMED_OUT && !cancelled)
2819
- return answer;
2820
- const error = new TimeoutError(timeout, 'Query', {
2821
- outcome: 'not-executed',
2822
- ...(cancelled ? { cause: answer.error } : {}),
2823
- message: (cancelled
2824
- ? `Query timed out after ${timeout}ms and was cancelled on the server, so it made no change. `
2825
- : `Query timed out after ${timeout}ms, and the server did not confirm its cancellation within ` +
2826
- `${CANCEL_GRACE_MS}ms. `) +
2827
- 'The transaction it ran in is over: it rolls back instead of committing, and no statement in it is ' +
2828
- 'kept. Let this error leave the transaction callback and retry the whole transaction, or run a ' +
2829
- 'statement that may time out in a nested `tx.$transaction(...)`, which rolls back only that block.',
2830
- });
2831
- state.abort(error);
2832
- return { timeout: error };
2833
- }
2834
- finally {
2835
- clearTimeout(graceTimer);
2836
- }
2820
+ state.abort(error);
2821
+ return { timeout: error };
2837
2822
  }
2838
2823
  /**
2839
2824
  * Cancel a statement that outlived its timeout, wait for it to answer, and
2840
2825
  * release its connection accordingly. See {@link queryCancellable}.
2841
2826
  */
2842
2827
  async cancelTimedOut(held, running, timeout) {
2843
- let graceTimer;
2844
- const graceOver = new Promise((resolve) => {
2845
- graceTimer = setTimeout(() => resolve(TIMED_OUT), CANCEL_GRACE_MS);
2846
- });
2847
- try {
2848
- const delivered = await Promise.race([sendCancelRequest(held.client, CANCEL_GRACE_MS), graceOver]);
2849
- const answer = await Promise.race([running, graceOver]);
2850
- if (answer === TIMED_OUT) {
2851
- held.checkout.release(new Error('the statement did not stop after a cancel request'));
2852
- return {
2853
- timeout: new TimeoutError(timeout, 'Query', {
2854
- outcome: 'unknown',
2855
- message: `Query timed out after ${timeout}ms and the server did not confirm its cancellation within ` +
2856
- `${CANCEL_GRACE_MS}ms, so it may still complete and a write may have been applied: check before ` +
2857
- 'retrying it. The connection was closed.',
2858
- }),
2859
- };
2860
- }
2861
- // A cancel that was sent but not confirmed could still land on the NEXT
2862
- // statement this connection runs, so such a connection is not reused.
2863
- const reusable = delivered === true;
2864
- if ('result' in answer) {
2865
- held.checkout.release(reusable ? undefined : true);
2866
- return answer;
2867
- }
2868
- const err = answer.error;
2869
- if (reusable && err?.code === '57014') {
2870
- held.checkout.release();
2871
- return {
2872
- timeout: new TimeoutError(timeout, 'Query', {
2873
- outcome: 'not-executed',
2874
- cause: err,
2875
- message: `Query timed out after ${timeout}ms and was cancelled on the server. It made no change.`,
2876
- }),
2877
- };
2878
- }
2879
- held.checkout.release(err instanceof Error ? err : true);
2828
+ const { delivered, answer } = await settleBackendCancel(sendCancelRequest(held.client, CANCEL_GRACE_MS), running);
2829
+ if (answer === TIMED_OUT) {
2830
+ held.checkout.release(new Error('the statement did not stop after a cancel request'));
2831
+ return {
2832
+ timeout: new TimeoutError(timeout, 'Query', {
2833
+ outcome: 'unknown',
2834
+ message: `Query timed out after ${timeout}ms and the server did not confirm its cancellation within ` +
2835
+ `${CANCEL_GRACE_MS}ms, so it may still complete and a write may have been applied: check before ` +
2836
+ 'retrying it. The connection was closed.',
2837
+ }),
2838
+ };
2839
+ }
2840
+ // A cancel that was sent but not confirmed could still land on the NEXT
2841
+ // statement this connection runs, so such a connection is not reused.
2842
+ const reusable = delivered === true;
2843
+ if ('result' in answer) {
2844
+ held.checkout.release(reusable ? undefined : true);
2880
2845
  return answer;
2881
2846
  }
2882
- finally {
2883
- clearTimeout(graceTimer);
2847
+ const err = answer.error;
2848
+ if (reusable && err?.code === '57014') {
2849
+ held.checkout.release();
2850
+ return {
2851
+ timeout: new TimeoutError(timeout, 'Query', {
2852
+ outcome: 'not-executed',
2853
+ cause: err,
2854
+ message: `Query timed out after ${timeout}ms and was cancelled on the server. It made no change.`,
2855
+ }),
2856
+ };
2884
2857
  }
2858
+ held.checkout.release(err instanceof Error ? err : true);
2859
+ return answer;
2885
2860
  }
2886
2861
  /**
2887
2862
  * Execute a write `DeferredQuery` (create/update/delete/upsert) according to
@@ -2913,82 +2888,46 @@ export class QueryInterface {
2913
2888
  * deadline is not sent. `onClient` routes them to a held connection.
2914
2889
  */
2915
2890
  deadlineExec(timeout, onClient) {
2916
- const deadline = timeout ? performance.now() + timeout : undefined;
2891
+ const left = timeout ? writeDeadline(timeout) : undefined;
2917
2892
  return async (sql, params, preparedName) => {
2918
- let left = timeout;
2919
- if (deadline !== undefined) {
2920
- left = Math.ceil(deadline - performance.now());
2921
- if (left <= 0) {
2922
- throw new TimeoutError(timeout, 'Query', {
2923
- outcome: 'not-executed',
2924
- message: `Query timed out after ${timeout}ms: the write's statements share one deadline, and it passed ` +
2925
- 'before the next one was sent. Its earlier statements are rolled back, so it makes no change.',
2926
- });
2927
- }
2928
- }
2893
+ const ms = left?.();
2929
2894
  return onClient
2930
- ? this.queryWithTimeout(sql, params, left, preparedName, false, onClient)
2931
- : this.queryWithTimeout(sql, params, left, preparedName);
2895
+ ? this.queryWithTimeout(sql, params, ms, preparedName, false, onClient)
2896
+ : this.queryWithTimeout(sql, params, ms, preparedName);
2932
2897
  };
2933
2898
  }
2934
2899
  /**
2935
2900
  * Run a write that takes several statements as one transaction on one
2936
2901
  * connection: the caller's transaction when there is one, else one opened
2937
- * here. A statement that times out is cancelled where the engine allows it,
2938
- * and its connection is closed rather than rolled back (a ROLLBACK would wait
2939
- * behind it); the transaction never commits, so the write made no change.
2940
- * `timeout` is one deadline for every statement (see {@link deadlineExec}).
2902
+ * here and settled by {@link completeTransaction}. A statement that times
2903
+ * out ends that transaction: its running statement is cancelled where the
2904
+ * engine allows it and ROLLBACK sent, and the error says whether the server
2905
+ * confirmed the rollback. `timeout` is one deadline for every statement (see
2906
+ * {@link deadlineExec}).
2941
2907
  */
2942
2908
  async inOneTransaction(work, timeout, operation, alternative) {
2943
2909
  if (this.txScoped) {
2944
2910
  // In the caller's transaction, a savepoint keeps the write whole: a later
2945
2911
  // statement that fails and is caught cannot leave the earlier ones behind.
2912
+ // A deadline between statements made no change only once the rollback
2913
+ // to that savepoint is acknowledged (see writeDeadline).
2946
2914
  return withSavepoint(this.pool, () => work(this.deadlineExec(timeout)));
2947
2915
  }
2948
2916
  if (typeof this.pool.connect !== 'function') {
2949
2917
  throw new 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 ` +
2950
2918
  `this pool cannot check one out (a stateless HTTP driver). ${alternative}`);
2951
2919
  }
2952
- const { client, checkout } = await openCheckout(this.pool, (c) => c.query(this.dialect.beginStatement()));
2920
+ const held = await openCheckout(this.pool, (c) => sendControl(c, this.dialect.beginStatement()));
2921
+ const { client } = held;
2922
+ const state = new TransactionState(client, this.dialect);
2923
+ // Statements go through the state, so the settlement knows one is still
2924
+ // running when a timeout cuts the write short.
2953
2925
  const onClient = {
2954
- query: (text, values) => typeof text === 'string'
2926
+ query: (text, values) => state.run(() => typeof text === 'string'
2955
2927
  ? client.query(text, values)
2956
- : client.query(text),
2928
+ : client.query(text)),
2957
2929
  };
2958
- try {
2959
- const value = await work(this.deadlineExec(timeout, onClient));
2960
- await client.query(this.dialect.commitStatement());
2961
- checkout.release();
2962
- return value;
2963
- }
2964
- catch (err) {
2965
- if (err instanceof TimeoutError) {
2966
- if (await sendCancelRequest(client, CANCEL_GRACE_MS)) {
2967
- checkout.release(err);
2968
- }
2969
- else {
2970
- // No cancel reached the server (or the engine has none), so the
2971
- // statement may still be running. The ROLLBACK queues behind it on
2972
- // this connection, and the connection goes back to the pool only
2973
- // after it: never with the transaction still open.
2974
- client.query(this.dialect.rollbackStatement()).then(() => checkout.release(), (e) => checkout.release(e instanceof Error ? e : true));
2975
- }
2976
- throw new TimeoutError(err.timeoutMs, 'Query', {
2977
- outcome: 'not-executed',
2978
- cause: err,
2979
- message: `Query timed out after ${err.timeoutMs}ms. Its transaction is rolled back rather than committed, ` +
2980
- 'so it makes no change.',
2981
- });
2982
- }
2983
- try {
2984
- await client.query(this.dialect.rollbackStatement());
2985
- }
2986
- catch {
2987
- // Best effort: the connection may be gone.
2988
- }
2989
- checkout.release();
2990
- throw explainConnectionLoss(wrapPgError(err), checkout.lostWith);
2991
- }
2930
+ return completeTransaction(held, state, this.dialect, undefined, () => work(this.deadlineExec(timeout, onClient)));
2992
2931
  }
2993
2932
  // ---------------------------------------------------------------------------
2994
2933
  // Write compilation (extracted to writes.ts).
@@ -3114,7 +3053,7 @@ export class QueryInterface {
3114
3053
  // depending on every consumer to re-establish it.
3115
3054
  args = this.normalizeArgs(args);
3116
3055
  this.assertLockInTransaction(args, 'findUnique');
3117
- return this.executeWithMiddleware('findUnique', args, async () => {
3056
+ return this.executeWithMiddleware('findUnique', args, () => {
3118
3057
  if (args.with) {
3119
3058
  const strategy = this.resolveLoadStrategy(args.relationLoadStrategy);
3120
3059
  if (strategy === 'batched')
@@ -3130,8 +3069,7 @@ export class QueryInterface {
3130
3069
  }
3131
3070
  }
3132
3071
  const deferred = this.buildFindUnique(args);
3133
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args.timeout, this.preparedNameFor(args, deferred.preparedName));
3134
- return deferred.transform(result);
3072
+ return this.executeRead(deferred, args);
3135
3073
  });
3136
3074
  }
3137
3075
  /**
@@ -3145,7 +3083,7 @@ export class QueryInterface {
3145
3083
  args = this.normalizeArgs(args);
3146
3084
  // Stable relation order (opt-in), see runFindManyBatched.
3147
3085
  const withClause = this.resolveStableOrder(args.stableRelationOrder)
3148
- ? this.applyStableRelationOrder(args.with, this.table)
3086
+ ? applyStableRelationOrderTo(this.schema, args.with, this.table)
3149
3087
  : args.with;
3150
3088
  // Same scope-rule parity as runFindManyBatched: reject before querying.
3151
3089
  rejectNestedPickOrder(withClause);
@@ -3175,6 +3113,7 @@ export class QueryInterface {
3175
3113
  // Prisma compound-unique selector expansion (before global-filter merge and
3176
3114
  // fingerprinting, so the cache only ever sees the canonical expanded where).
3177
3115
  args = maybeExpandCompoundUnique(this.tableMeta, args);
3116
+ const userWhere = (args.where ?? {});
3178
3117
  // A findUnique whose `where` carries NO predicate must not run.
3179
3118
  //
3180
3119
  // `{ id: undefined }` is what `{ id: req.params.id }` becomes on a request
@@ -3194,7 +3133,7 @@ export class QueryInterface {
3194
3133
  // filter" is its contract, and `where: {}` or no `where` asks for any row.
3195
3134
  // It refuses only a `where` that was emptied by `undefined` values (see
3196
3135
  // normalizeArgs), which never meant "any row".
3197
- if (whereMod.userPredicateIsEmpty(this.ctx, (args.where ?? {}))) {
3136
+ if (whereMod.userPredicateIsEmpty(this.ctx, userWhere)) {
3198
3137
  throw new ValidationError(`findUnique on "${this.table}" refused: the \`where\` clause has no predicate, ` +
3199
3138
  'so this would return an arbitrary row rather than a specific one. ' +
3200
3139
  'A key whose value is `undefined` does not count, check that the value you are looking up is defined. ' +
@@ -3212,14 +3151,14 @@ export class QueryInterface {
3212
3151
  // Checked against the USER's where for the same reason as the guard above:
3213
3152
  // a global filter is not an identity, and letting one satisfy this would
3214
3153
  // hand back an arbitrary row from inside the tenant.
3215
- this.assertFindUniqueKey(args.where);
3154
+ assertWhereIdentifiesOneRow(this.tableMeta, this.table, userWhere);
3216
3155
  // The locking clause, read by the cache key and all three SQL paths below.
3217
3156
  const rowLock = resolveRowLock(args.lock, this.dialect, this.table);
3218
3157
  const lockSql = rowLock?.sql ?? '';
3219
3158
  // Stable relation order (opt-in): fill PK-asc orderBy into unordered to-many
3220
3159
  // relations before fingerprinting (see buildFindMany).
3221
3160
  if (args.with && this.resolveStableOrder(args.stableRelationOrder)) {
3222
- const normalized = this.applyStableRelationOrder(args.with, this.table);
3161
+ const normalized = applyStableRelationOrderTo(this.schema, args.with, this.table);
3223
3162
  if (normalized !== args.with)
3224
3163
  args = { ...args, with: normalized };
3225
3164
  }
@@ -3231,11 +3170,9 @@ export class QueryInterface {
3231
3170
  if (args.with && this.resolveLoadStrategy(args.relationLoadStrategy) === 'flatten') {
3232
3171
  this.warnFlattenBlocked('findUnique reads a single parent row, where the correlated subquery already runs once');
3233
3172
  }
3234
- const columnsList = this.resolveColumns(args.select, args.omit, includePii);
3235
- // A global filter turns the where into `{ AND: [...] }`, which the
3236
- // `isSimpleWhere` test below rejects → the general (buildWhereClause) path
3237
- // handles the merge and its params uniformly.
3238
- const whereObj = (this.mergeGlobalFilter(args.where) ?? {});
3173
+ const columnsList = relationsMod.resolveColumns(this.ctx, args.select, args.omit, includePii);
3174
+ // A global filter wraps the user where in an AND before compilation.
3175
+ const whereObj = (whereMod.mergeGlobalFilter(this.ctx, userWhere) ?? {});
3239
3176
  const colKey = columnsList ? columnsList.join(',') : '*';
3240
3177
  const whereFingerprint = this.fingerprintWhere(whereObj);
3241
3178
  const withFp = args.with ? this.withFingerprint(args.with) : '';
@@ -3247,115 +3184,33 @@ export class QueryInterface {
3247
3184
  const encodingFp = `|je=${jsonEncoding === 'positional' ? 'p' : 'o'}`;
3248
3185
  // Empty without a lock, so every unlocked key is unchanged.
3249
3186
  const lockFp = rowLock ? `|lk=${rowLock.fp}` : '';
3250
- const ck = `fu:${whereFingerprint}|c=${colKey}|w=${withFp}|pii=${includePii ? 1 : 0}${encodingFp}${lockFp}${this.globalFilterCacheSegment()}`;
3187
+ const ck = `fu:${whereFingerprint}|c=${colKey}|w=${withFp}|pii=${includePii ? 1 : 0}${encodingFp}${lockFp}${whereMod.globalFilterCacheSegment(this.ctx)}`;
3251
3188
  const params = [];
3252
- // Check if all where values are simple (plain equality, no operators/null/OR).
3253
- // Keys are sorted to match fingerprintWhere, insertion order here would let
3254
- // permuted where literals share a cache entry with misaligned params.
3255
- const whereKeys = Object.keys(whereObj)
3256
- .filter((k) => whereObj[k] !== undefined)
3257
- .sort();
3258
- // Only a scalar the general path would accept as it is (a primitive, Date
3259
- // or Buffer) on a non-JSON column takes the simple path, so no operand
3260
- // reaches SQL without the general path's validation. Resolved, not looked
3261
- // up: a relation filter spelled the snake_case way must not read as a
3262
- // plain equality.
3263
- const isSimpleWhere = !whereObj.OR &&
3264
- !whereObj.AND &&
3265
- !whereObj.NOT &&
3266
- whereKeys.every((k) => {
3267
- if (!isFastPathScalar(whereObj[k]) || resolveRelationDef(this.tableMeta.relations, k))
3268
- return false;
3269
- const column = resolveColumnName(this.tableMeta, k);
3270
- return column !== undefined && !this.isJsonColumnType(this.getColumnPgType(column));
3271
- });
3272
- // Simple path: plain equality, no operators/null/OR.
3273
- //
3274
- // This path pushes its own params instead of going through
3275
- // `buildWhereClause`, so every VALUE transform the general walker applies
3276
- // has to be mirrored here or the two paths disagree on the same predicate.
3277
- // `coerceWhereOperand` is the one that matters: without it a `Date` keyed on
3278
- // a zone-less `date`/`timestamp`/`time` column binds raw, and a row that
3279
- // `findFirst` matches, `findUnique` silently misses. It is a value-only
3280
- // transform, so the emitted SQL and the cache key are untouched.
3281
- if (!args.with && isSimpleWhere) {
3282
- const coerce = (k, v) => whereMod.coerceWhereOperand(this.ctx, this.tableMeta, this.toColumn(k), v);
3283
- const buildSql = (freshParams) => {
3284
- const qt = this.q(this.table);
3285
- const whereClauses = whereKeys.map((k, i) => {
3286
- freshParams.push(coerce(k, whereObj[k]));
3287
- return `${this.toSqlColumn(k)} = ${this.p(i + 1)}`;
3288
- });
3289
- const whereSql = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
3290
- const selectExpr = columnsList ? columnsList.map((c) => `${qt}.${this.q(c)}`).join(', ') : `${qt}.*`;
3291
- return `SELECT ${selectExpr} FROM ${qt}${whereSql}${this.limitOneClause()}${lockSql}`;
3292
- };
3293
- const entry = this.acquireSql(ck, buildSql);
3294
- // Collect params (same order and same coercion as build)
3295
- for (const k of whereKeys) {
3296
- params.push(coerce(k, whereObj[k]));
3297
- }
3298
- this.crossCheckCache('findUnique', ck, entry, buildSql, params);
3299
- return {
3300
- sql: entry.sql,
3301
- params,
3302
- transform: (result) => {
3303
- const row = result.rows[0];
3304
- return row ? this.parseRow(row, this.table) : null;
3305
- },
3306
- tag: `${this.table}.findUnique`,
3307
- preparedName: entry.name,
3308
- ...rowLockMarker(rowLock),
3309
- };
3310
- }
3311
- // General path (with operators, null, OR, with clause)
3312
- if (!args.with) {
3313
- const buildSql = (freshParams) => {
3314
- const clause = this.buildWhereClause(whereObj, freshParams);
3315
- const whereSql = clause ? ` WHERE ${clause}` : '';
3316
- const qt = this.q(this.table);
3317
- const selectExpr = columnsList ? columnsList.map((c) => `${qt}.${this.q(c)}`).join(', ') : `${qt}.*`;
3318
- return `SELECT ${selectExpr} FROM ${qt}${whereSql}${this.limitOneClause()}${lockSql}`;
3319
- };
3320
- const entry = this.acquireSql(ck, buildSql);
3321
- // Collect params
3322
- this.collectWhereParams(whereObj, params);
3323
- this.crossCheckCache('findUnique', ck, entry, buildSql, params);
3324
- return {
3325
- sql: entry.sql,
3326
- params,
3327
- transform: (result) => {
3328
- const row = result.rows[0];
3329
- return row ? this.parseRow(row, this.table) : null;
3330
- },
3331
- tag: `${this.table}.findUnique`,
3332
- preparedName: entry.name,
3333
- ...rowLockMarker(rowLock),
3334
- };
3335
- }
3336
- // Nested queries with `with` clause.
3337
- // The param order in the original code is:
3338
- // 1. buildWhere pushes where params
3339
- // 2. buildSelectWithRelations pushes relation params to same array
3340
- // We must preserve this exact order.
3189
+ // Scalar equalities share the general compiler's validation and bind order.
3341
3190
  const buildSql = (freshParams) => {
3342
- const clause = this.buildWhereClause(whereObj, freshParams);
3343
- const whereSql = clause ? ` WHERE ${clause}` : '';
3344
- const selectClause = this.buildSelectWithRelations(this.table, args.with, freshParams, columnsList, undefined, undefined, includePii);
3345
- return `SELECT ${selectClause} FROM ${this.q(this.table)}${whereSql}${this.limitOneClause()}${lockSql}`;
3191
+ const clause = whereMod.buildWhereClause(this.ctx, whereObj, freshParams);
3192
+ const qt = this.q(this.table);
3193
+ const selectClause = args.with
3194
+ ? relationsMod.buildSelectWithRelations(this.ctx, this.table, args.with, freshParams, columnsList, undefined, undefined, includePii, undefined)
3195
+ : columnsList
3196
+ ? relationsMod.qualifiedColumns(this.ctx, columnsList, qt)
3197
+ : `${qt}.*`;
3198
+ return `SELECT ${selectClause} FROM ${qt}${clause ? ` WHERE ${clause}` : ''}${this.limitOneClause()}${lockSql}`;
3346
3199
  };
3347
3200
  const entry = this.acquireSql(ck, buildSql);
3348
- // Collect params in exact build order: where first, then with-clause relations
3349
3201
  this.collectWhereParams(whereObj, params);
3350
- this.collectWithParams(args.with, params);
3202
+ if (args.with)
3203
+ relationsMod.collectWithParams(this.ctx, args.with, params, undefined, undefined);
3351
3204
  this.crossCheckCache('findUnique', ck, entry, buildSql, params);
3352
- const parseWith = this.makeNestedParser(args.with, includePii);
3205
+ const parse = args.with
3206
+ ? relationsMod.makeNestedParser(this.ctx, args.with, includePii, undefined)
3207
+ : this.makeRowParser(this.table);
3353
3208
  return {
3354
3209
  sql: entry.sql,
3355
3210
  params,
3356
3211
  transform: (result) => {
3357
3212
  const row = result.rows[0];
3358
- return row ? parseWith(row) : null;
3213
+ return row ? parse(row) : null;
3359
3214
  },
3360
3215
  tag: `${this.table}.findUnique`,
3361
3216
  preparedName: entry.name,
@@ -3391,7 +3246,7 @@ export class QueryInterface {
3391
3246
  'is by default in production.', { code: 'deep-with', table: this.table, operation: 'findMany', depth });
3392
3247
  }
3393
3248
  }
3394
- return this.executeWithMiddleware('findMany', (args ?? {}), async () => {
3249
+ return this.executeWithMiddleware('findMany', (args ?? {}), () => {
3395
3250
  if (args?.with) {
3396
3251
  const strategy = this.resolveLoadStrategy(args.relationLoadStrategy);
3397
3252
  if (strategy === 'batched')
@@ -3403,8 +3258,7 @@ export class QueryInterface {
3403
3258
  }
3404
3259
  }
3405
3260
  const deferred = this.buildFindMany(args);
3406
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
3407
- return deferred.transform(result);
3261
+ return args?.with ? this.executeRead(deferred, args) : this.executeFlatRead(deferred, args);
3408
3262
  });
3409
3263
  }
3410
3264
  /**
@@ -3568,7 +3422,7 @@ export class QueryInterface {
3568
3422
  // relations BEFORE fingerprinting, so the two orderings get distinct cache
3569
3423
  // entries and every downstream path (SQL build, collect, parser) inherits it.
3570
3424
  if (args?.with && this.resolveStableOrder(args.stableRelationOrder)) {
3571
- const normalized = this.applyStableRelationOrder(args.with, this.table);
3425
+ const normalized = applyStableRelationOrderTo(this.schema, args.with, this.table);
3572
3426
  if (normalized !== args.with)
3573
3427
  args = { ...args, with: normalized };
3574
3428
  }
@@ -3658,7 +3512,7 @@ export class QueryInterface {
3658
3512
  // identically (same rule as the vector guard inside the distinct branch).
3659
3513
  if (args?.distinct && args.distinct.length > 0 && args.orderBy) {
3660
3514
  for (const [, d] of orderByEntries(args.orderBy)) {
3661
- if (this.isRelationOrderByValue(d)) {
3515
+ if (relationsMod.isRelationOrderByValue(this.ctx, d)) {
3662
3516
  throw new ValidationError('`distinct` cannot be combined with relation orderBy (pick-row, `_count`, or ' +
3663
3517
  'to-one relation ordering): the outer re-order cannot reference the parent table.');
3664
3518
  }
@@ -3668,12 +3522,12 @@ export class QueryInterface {
3668
3522
  // the UNSAFE sentinel or nothing: a literal `true` (what a spread request
3669
3523
  // body carries) throws here rather than unlocking the projection.
3670
3524
  const includePii = resolveUnsafeFlag(args?.includePii, 'includePii');
3671
- const columnsList = this.resolveColumns(args?.select, args?.omit, includePii);
3525
+ const columnsList = relationsMod.resolveColumns(this.ctx, args?.select, args?.omit, includePii);
3672
3526
  const colKey = columnsList ? columnsList.join(',') : '*';
3673
3527
  // AND-merge this table's global filter into the user where; `hasWhere` gates
3674
3528
  // the build/collect just like `args?.where` did (a merged filter can make
3675
3529
  // an otherwise-absent where present).
3676
- const effWhere = this.mergeGlobalFilter(args?.where);
3530
+ const effWhere = whereMod.mergeGlobalFilter(this.ctx, args?.where);
3677
3531
  const hasWhere = effWhere !== undefined;
3678
3532
  const whereObj = (effWhere ?? {});
3679
3533
  // Build fingerprint for cache lookup
@@ -3691,7 +3545,7 @@ export class QueryInterface {
3691
3545
  // cache entry instead of minting two templates for one query.
3692
3546
  .map(([k, d]) => {
3693
3547
  const rel = resolveRelation(this.tableMeta.relations, k);
3694
- return `${rel?.name ?? k}:${this.orderByEntryFingerprint(d, rel?.def.to)}`;
3548
+ return `${rel?.name ?? k}:${relationsMod.orderByEntryFingerprint(this.ctx, d, rel?.def.to)}`;
3695
3549
  })
3696
3550
  .join(',')
3697
3551
  : '';
@@ -3740,16 +3594,11 @@ export class QueryInterface {
3740
3594
  const encodingFp = `|je=${jsonEncoding === 'positional' ? 'p' : 'o'}`;
3741
3595
  // Empty without a lock, so every unlocked key is unchanged.
3742
3596
  const lockFp = rowLock ? `|lk=${rowLock.fp}` : '';
3743
- 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()}`;
3597
+ 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)}`;
3744
3598
  const params = [];
3745
3599
  const buildSql = (freshParams) => {
3746
3600
  // Fresh build: generates SQL and populates freshParams
3747
- const { sql: freshWhereSql } = hasWhere
3748
- ? (() => {
3749
- const clause = this.buildWhereClause(whereObj, freshParams);
3750
- return { sql: clause ? ` WHERE ${clause}` : '' };
3751
- })()
3752
- : { sql: '' };
3601
+ const freshWhereSql = hasWhere ? whereMod.buildWhereSql(this.ctx, whereObj, freshParams) : '';
3753
3602
  const qt = this.q(this.table);
3754
3603
  let distinctPrefix = '';
3755
3604
  let distinctCols = [];
@@ -3789,10 +3638,10 @@ export class QueryInterface {
3789
3638
  const relationJoins = [];
3790
3639
  let selectClause;
3791
3640
  if (args?.with) {
3792
- selectClause = this.buildSelectWithRelations(this.table, args.with, freshParams, columnsList, undefined, undefined, includePii, flattenPlan ? { plan: flattenPlan, joinSink: relationJoins } : undefined);
3641
+ selectClause = relationsMod.buildSelectWithRelations(this.ctx, this.table, args.with, freshParams, columnsList, undefined, undefined, includePii, flattenPlan ? { plan: flattenPlan, joinSink: relationJoins } : undefined);
3793
3642
  }
3794
3643
  else if (columnsList) {
3795
- selectClause = columnsList.map((c) => `${qt}.${this.q(c)}`).join(', ');
3644
+ selectClause = relationsMod.qualifiedColumns(this.ctx, columnsList, qt);
3796
3645
  }
3797
3646
  else {
3798
3647
  selectClause = `${qt}.*`;
@@ -3825,7 +3674,7 @@ export class QueryInterface {
3825
3674
  if (orderByEntries(args.orderBy).some(([, d]) => isVectorOrderBy(d))) {
3826
3675
  throw new ValidationError('`distinct` cannot be combined with vector distance ordering.');
3827
3676
  }
3828
- const userOrder = this.buildOrderBy(args.orderBy, freshParams);
3677
+ const userOrder = relationsMod.buildOrderBy(this.ctx, args.orderBy, freshParams, undefined);
3829
3678
  // The outer level re-orders by the user's columns, which must therefore
3830
3679
  // exist in the derived table. A NARROWED projection (`select`, `omit`,
3831
3680
  // or the PII rule, which narrows with no user projection at all) left
@@ -3852,7 +3701,7 @@ export class QueryInterface {
3852
3701
  extras.push(col);
3853
3702
  }
3854
3703
  if (extras.length > 0) {
3855
- innerSelect = `${selectClause}, ${extras.map((c) => `${qt}.${this.q(c)}`).join(', ')}`;
3704
+ innerSelect = `${selectClause}, ${relationsMod.qualifiedColumns(this.ctx, extras, qt)}`;
3856
3705
  outerSelect = this.distinctOuterSelectList(columnsList, args.with).join(', ');
3857
3706
  }
3858
3707
  }
@@ -3866,7 +3715,7 @@ export class QueryInterface {
3866
3715
  // vector at the correct position (after cursor params, before LIMIT), and
3867
3716
  // lateralJoins so a lateral pick splices its join into the FROM clause.
3868
3717
  const orderBySql = args?.orderBy
3869
- ? ` ORDER BY ${this.buildOrderBy(args.orderBy, freshParams, lateralJoins)}`
3718
+ ? ` ORDER BY ${relationsMod.buildOrderBy(this.ctx, args.orderBy, freshParams, lateralJoins)}`
3870
3719
  : '';
3871
3720
  sql = `SELECT ${distinctPrefix}${selectClause} FROM ${qt}${relationJoins.join('')}${lateralJoins.join('')}${tail}${orderBySql}`;
3872
3721
  }
@@ -3895,7 +3744,7 @@ export class QueryInterface {
3895
3744
  }
3896
3745
  // 2. WITH relation params
3897
3746
  if (args?.with) {
3898
- this.collectWithParams(args.with, params, undefined, flattenPlan);
3747
+ relationsMod.collectWithParams(this.ctx, args.with, params, undefined, flattenPlan);
3899
3748
  }
3900
3749
  // 3. Cursor params: the build's own renderer, SQL discarded.
3901
3750
  if (cursorPlan)
@@ -3919,11 +3768,13 @@ export class QueryInterface {
3919
3768
  }
3920
3769
  this.crossCheckCache('findMany', ck, entry, buildSql, params);
3921
3770
  // Build the row parser once (positional shapes are computed here, not per row).
3922
- const parseWith = args?.with ? this.makeNestedParser(args.with, includePii, flattenPlan) : null;
3771
+ const parse = args?.with
3772
+ ? relationsMod.makeNestedParser(this.ctx, args.with, includePii, flattenPlan)
3773
+ : this.makeRowParser(this.table);
3923
3774
  return {
3924
3775
  sql: entry.sql,
3925
3776
  params,
3926
- transform: (result) => result.rows.map((row) => (parseWith ? parseWith(row) : this.parseRow(row, this.table))),
3777
+ transform: (result) => result.rows.map(parse),
3927
3778
  tag: `${this.table}.findMany`,
3928
3779
  preparedName: entry.name,
3929
3780
  ...rowLockMarker(rowLock),
@@ -3959,11 +3810,10 @@ export class QueryInterface {
3959
3810
  // throw also lands here first, before a connection is taken.
3960
3811
  this.resolveJsonEncoding(args?.jsonEncoding);
3961
3812
  if (!args?.with) {
3962
- const table = this.table;
3963
- return (row) => this.parseRow(row, table);
3813
+ return this.makeRowParser(this.table);
3964
3814
  }
3965
3815
  const streamFlattenPlan = this.planFlatten(args, streamPii);
3966
- return this.makeNestedParser(args.with, streamPii, streamFlattenPlan);
3816
+ return relationsMod.makeNestedParser(this.ctx, args.with, streamPii, streamFlattenPlan);
3967
3817
  }
3968
3818
  /**
3969
3819
  * Everything a stream does to the DATABASE, and nothing it does to a row.
@@ -3991,7 +3841,16 @@ export class QueryInterface {
3991
3841
  // Canonical args BEFORE the speculative build below, which spreads `args`
3992
3842
  // and sets its own `limit`: a surviving `take` would reach that spread
3993
3843
  // beside it and be read as a second value for one bound.
3844
+ const signal = args?.signal;
3994
3845
  args = this.normalizeArgs(args);
3846
+ const state = this.txScoped ? transactionStateOf(this.pool) : undefined;
3847
+ if (signal &&
3848
+ this.dialect.capabilities.backendCancel &&
3849
+ (this.txScoped
3850
+ ? !state || !this.pool.runStreamQuery || !canCancelBackend(state.client)
3851
+ : !isNodePostgresPool(this.pool))) {
3852
+ throw new UnsupportedFeatureError('Stream cancellation', this.dialect.name, 'A native pg pool, or a scoped transaction with a protocol-cancel target, is required.');
3853
+ }
3995
3854
  const batchSize = Math.max(1, Math.floor(Number(args?.batchSize ?? 1000)));
3996
3855
  // Validated on every path, so a bad value is refused whether or not this
3997
3856
  // stream turns out to need a cursor.
@@ -4031,13 +3890,13 @@ export class QueryInterface {
4031
3890
  // most expensive exactly where it was least likely to pay off: raising
4032
3891
  // `batchSize` for throughput made every large drain slower, and the stream
4033
3892
  // was the only thing here that got slower as `batchSize` went up. So the
4034
- // speculation is now bounded BY `batchSize` rather than scaled by it. At or
3893
+ // speculation is bounded BY `batchSize` rather than scaled by it. At or
4035
3894
  // below the default it is unchanged; above it, a caller asking for large
4036
- // batches has told us not to expect a one-batch result, and we go straight
3895
+ // batches has indicated a one-batch result is unlikely, so go straight
4037
3896
  // to the cursor and waste nothing. The cost of being wrong about that is
4038
3897
  // four round trips on a drain that would have fit, never any transferred
4039
3898
  // rows.
4040
- if (batchSize <= STREAM_SPECULATION_MAX_BATCH) {
3899
+ if (!signal && batchSize <= STREAM_SPECULATION_MAX_BATCH) {
4041
3900
  // The caller's bound (or the client's `defaultLimit`, exactly as findMany
4042
3901
  // applies it) caps the speculative fetch. When the bound fits in a batch
4043
3902
  // the speculative fetch IS the whole answer; otherwise `rows <= batchSize`
@@ -4063,19 +3922,38 @@ export class QueryInterface {
4063
3922
  const deferred = this.buildFindMany(args);
4064
3923
  // Acquire a dedicated connection: cursors require a single connection in a
4065
3924
  // transaction. The dialect owns the streaming SQL (Postgres: BEGIN → DECLARE
4066
- // … NO SCROLL CURSOR FOR → FETCH n → CLOSE → COMMIT, ROLLBACK on error); we
4067
- // just yield the row batches it produces.
3925
+ // … NO SCROLL CURSOR FOR → FETCH n → CLOSE → COMMIT, ROLLBACK on error);
3926
+ // yield the row batches it produces.
4068
3927
  //
4069
3928
  // Inside a caller-owned transaction there is nothing to check out: the
4070
3929
  // transaction-scoped pool pins every query to the transaction's own
4071
3930
  // connection, so `pool.query` already IS that connection. The stream rides
4072
3931
  // on it, is never released here, and the dialect is told to emit no
4073
3932
  // transaction control of its own (`ambientTransaction`).
4074
- const held = this.txScoped ? null : await this.acquireConnection();
3933
+ const held = this.txScoped ? null : await this.acquireConnection(signal);
4075
3934
  const client = held?.client ?? null;
4076
- const base = client ?? {
4077
- query: async (text, values) => (await this.pool.query(text, values)),
4078
- };
3935
+ let discard = false;
3936
+ let base = client ?? this.pool;
3937
+ try {
3938
+ signal?.throwIfAborted();
3939
+ if (signal && !this.dialect.capabilities.backendCancel && !base.streamBatches)
3940
+ throw new UnsupportedFeatureError('Stream cancellation', this.dialect.name, 'A native streaming handle is required.');
3941
+ if (signal && this.dialect.capabilities.backendCancel) {
3942
+ const target = state?.client ?? client;
3943
+ if (!canCancelBackend(target))
3944
+ throw new UnsupportedFeatureError('Stream cancellation', this.dialect.name, 'The acquired connection has no native protocol-cancel target.');
3945
+ base = cancellableStreamConnection(base, target, signal, (error) => {
3946
+ discard = true;
3947
+ state?.abort(error);
3948
+ if (error instanceof ConnectionError)
3949
+ held?.checkout.release(error);
3950
+ }, state ? (send, settled) => this.pool.runStreamQuery(send, settled) : undefined);
3951
+ }
3952
+ }
3953
+ catch (error) {
3954
+ held?.checkout.release();
3955
+ throw error;
3956
+ }
4079
3957
  // The idle guard watches only a stream that holds a connection of its own
4080
3958
  // between pulls. Inside a caller's transaction the connection is theirs and
4081
3959
  // their transaction's timeout bounds it. On PostgreSQL the stream's BEGIN
@@ -4095,53 +3973,62 @@ export class QueryInterface {
4095
3973
  const streamSql = this.outgoing(deferred.sql, undefined, action).text;
4096
3974
  const stream = this.dialect.openStream(conn, streamSql, deferred.params, batchSize, {
4097
3975
  ambientTransaction: this.txScoped,
3976
+ ...(signal ? { signal } : {}),
4098
3977
  });
3978
+ let closing;
3979
+ const close = () => (closing ??= (async () => {
3980
+ guard?.stop();
3981
+ signal?.removeEventListener('abort', onAbort);
3982
+ let failure;
3983
+ try {
3984
+ await stream.return(undefined);
3985
+ }
3986
+ catch (error) {
3987
+ failure = error;
3988
+ throw explainConnectionLoss(wrapPgError(error), held?.checkout.lostWith);
3989
+ }
3990
+ finally {
3991
+ held?.checkout.release(discard || failure !== undefined ? (failure instanceof Error ? failure : true) : undefined);
3992
+ }
3993
+ })());
3994
+ const onAbort = () => {
3995
+ if (closing || idle.expired)
3996
+ return;
3997
+ idle.cancelled = { reason: signal.reason };
3998
+ // return() queues behind an active pull; the transport listener wakes it.
3999
+ // Observe a suspended consumer's cleanup failure again in finally below.
4000
+ void close().catch(() => { });
4001
+ };
4099
4002
  if (watched) {
4100
- guard = new StreamIdleGuard(idle, idleTimeoutMs, () => streamIdleExpiredError(action, this.table, idleTimeoutMs, unit), () => this.expireIdleStream(stream, held, action, idleTimeoutMs, idle, unit), backstop ? () => base.query('SELECT 1') : undefined);
4003
+ guard = new StreamIdleGuard(idle, idleTimeoutMs, () => streamIdleExpiredError(action, this.table, idleTimeoutMs, unit), () => this.expireIdleStream(close, action, idleTimeoutMs, idle, unit), backstop ? () => base.query('SELECT 1') : undefined);
4101
4004
  }
4005
+ signal?.addEventListener('abort', onAbort, { once: true });
4006
+ if (signal?.aborted)
4007
+ onAbort();
4102
4008
  try {
4103
4009
  // Driven by hand rather than `yield*`, so an expired stream's cleanup can
4104
4010
  // run from the timer while this generator is suspended.
4105
4011
  while (true) {
4012
+ assertStreamActive(idle);
4106
4013
  const step = await stream.next();
4014
+ assertStreamActive(idle);
4107
4015
  if (step.done)
4108
4016
  break;
4109
4017
  yield step.value;
4110
- if (idle.expired)
4111
- throw idle.expired;
4018
+ assertStreamActive(idle);
4112
4019
  }
4113
4020
  }
4114
4021
  catch (err) {
4115
- if (err === idle.expired)
4022
+ if (err === idle.expired || (idle.cancelled && err === idle.cancelled.reason))
4116
4023
  throw err;
4117
4024
  // Wrap pg constraint errors so streaming surfaces typed errors like the rest of the API
4118
4025
  throw explainConnectionLoss(wrapPgError(err), held?.checkout.lostWith);
4119
4026
  }
4120
4027
  finally {
4121
- guard?.stop();
4122
- if (guard?.expiry) {
4123
- // The timer already closed the stream and released the connection;
4124
- // wait for that so the connection is never handed back mid-cleanup.
4028
+ if (guard?.expiry)
4125
4029
  await guard.expiry;
4126
- }
4127
- else {
4128
- try {
4129
- // An early exit (`break`) closes the cursor here; after a full drain
4130
- // or an error the dialect's generator has finished and this is a no-op.
4131
- await stream.return(undefined);
4132
- }
4133
- catch (err) {
4134
- // Only an early exit can reach this throw: after an error or a full
4135
- // drain the dialect's generator has finished and return() resolves.
4136
- // A failed CLOSE / COMMIT on an early exit must reach the caller, as
4137
- // it did when this loop was a `yield*`.
4138
- // biome-ignore lint/correctness/noUnsafeFinally: it replaces only an early-exit return, see above
4139
- throw explainConnectionLoss(wrapPgError(err), held?.checkout.lostWith);
4140
- }
4141
- finally {
4142
- held?.checkout.release();
4143
- }
4144
- }
4030
+ else
4031
+ await close();
4145
4032
  }
4146
4033
  }
4147
4034
  /**
@@ -4151,16 +4038,12 @@ export class QueryInterface {
4151
4038
  * log `stream-idle-timeout`. The log line matters: an abandoned consumer
4152
4039
  * never pulls again, so it never sees the E002 waiting for it.
4153
4040
  */
4154
- async expireIdleStream(stream, held, action, timeoutMs, idle, unit) {
4155
- let failure;
4041
+ async expireIdleStream(close, action, timeoutMs, idle, unit) {
4156
4042
  try {
4157
- await stream.return(undefined);
4158
- }
4159
- catch (err) {
4160
- failure = err;
4043
+ await close();
4161
4044
  }
4162
- finally {
4163
- held.checkout.release(failure === undefined ? undefined : failure instanceof Error ? failure : true);
4045
+ catch {
4046
+ // The idle timeout already owns the terminal error; close discarded the checkout.
4164
4047
  }
4165
4048
  logTo(this.logger, 'warn', `${action} on "${this.table}" had no ${unit} requested for ${timeoutMs} ms, so Turbine closed its cursor ` +
4166
4049
  `and released its connection (${idle.rows} ${idle.rows === 1 ? 'row' : 'rows'} handed out before that). ` +
@@ -4203,10 +4086,14 @@ export class QueryInterface {
4203
4086
  */
4204
4087
  async *findManyStreamBatches(args) {
4205
4088
  args = this.normalizeArgs(args);
4089
+ resolveStreamSignal(args?.signal);
4206
4090
  this.assertNoStreamLock(args, 'findManyStreamBatches');
4207
4091
  const parse = this.makeStreamRowParser(args);
4208
4092
  const idle = newStreamIdleState();
4093
+ const assertStreamOpen = this.pool.assertStreamOpen;
4209
4094
  for await (const batch of this.streamRaw(args, 'findManyStreamBatches', idle, 'batch')) {
4095
+ assertStreamActive(idle);
4096
+ assertStreamOpen?.();
4210
4097
  const parsed = new Array(batch.length);
4211
4098
  for (let i = 0; i < batch.length; i++) {
4212
4099
  parsed[i] = parse(batch[i]);
@@ -4218,8 +4105,8 @@ export class QueryInterface {
4218
4105
  yield parsed;
4219
4106
  idle.suspended = false;
4220
4107
  idle.pulls++;
4221
- if (idle.expired)
4222
- throw idle.expired;
4108
+ assertStreamActive(idle);
4109
+ assertStreamOpen?.();
4223
4110
  }
4224
4111
  }
4225
4112
  /**
@@ -4259,6 +4146,7 @@ export class QueryInterface {
4259
4146
  */
4260
4147
  async *findManyStream(args) {
4261
4148
  args = this.normalizeArgs(args);
4149
+ resolveStreamSignal(args?.signal);
4262
4150
  this.assertNoStreamLock(args, 'findManyStream');
4263
4151
  const parse = this.makeStreamRowParser(args);
4264
4152
  // Parsed one row at a time, INSIDE the yield loop rather than a batch ahead
@@ -4266,8 +4154,11 @@ export class QueryInterface {
4266
4154
  // took. That laziness is the reason this loop is not written over
4267
4155
  // `findManyStreamBatches`.
4268
4156
  const idle = newStreamIdleState();
4157
+ const assertStreamOpen = this.pool.assertStreamOpen;
4269
4158
  for await (const batch of this.streamRaw(args, 'findManyStream', idle, 'row')) {
4270
4159
  for (let i = 0; i < batch.length; i++) {
4160
+ assertStreamActive(idle);
4161
+ assertStreamOpen?.();
4271
4162
  const row = parse(batch[i]);
4272
4163
  idle.rows++;
4273
4164
  // See findManyStreamBatches: the idle guard's view of the consumer.
@@ -4275,8 +4166,8 @@ export class QueryInterface {
4275
4166
  yield row;
4276
4167
  idle.suspended = false;
4277
4168
  idle.pulls++;
4278
- if (idle.expired)
4279
- throw idle.expired;
4169
+ assertStreamActive(idle);
4170
+ assertStreamOpen?.();
4280
4171
  }
4281
4172
  }
4282
4173
  }
@@ -4311,8 +4202,7 @@ export class QueryInterface {
4311
4202
  }
4312
4203
  }
4313
4204
  const deferred = this.buildFindFirst(args);
4314
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
4315
- return deferred.transform(result);
4205
+ return this.executeRead(deferred, args);
4316
4206
  });
4317
4207
  }
4318
4208
  buildFindFirst(args) {
@@ -4346,33 +4236,14 @@ export class QueryInterface {
4346
4236
  async findFirstOrThrow(args) {
4347
4237
  args = this.normalizeArgs(args, 'findFirstOrThrow');
4348
4238
  this.assertLockInTransaction(args, 'findFirstOrThrow');
4349
- return this.executeWithMiddleware('findFirstOrThrow', (args ?? {}), async () => {
4239
+ return this.executeWithMiddleware('findFirstOrThrow', (args ?? {}), () => {
4350
4240
  const deferred = this.buildFindFirstOrThrow(args);
4351
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
4352
- return deferred.transform(result);
4241
+ return this.executeRead(deferred, args);
4353
4242
  });
4354
4243
  }
4355
4244
  buildFindFirstOrThrow(args) {
4356
4245
  args = this.normalizeArgs(args, 'findFirstOrThrow');
4357
- const inner = this.buildFindFirstAs(args, 'findFirstOrThrow');
4358
- return {
4359
- sql: inner.sql,
4360
- params: inner.params,
4361
- transform: (result) => {
4362
- const row = inner.transform(result);
4363
- if (row === null) {
4364
- throw new NotFoundError({
4365
- table: this.table,
4366
- where: args?.where,
4367
- operation: 'findFirstOrThrow',
4368
- });
4369
- }
4370
- return row;
4371
- },
4372
- tag: `${this.table}.findFirstOrThrow`,
4373
- ...(inner.preparedName !== undefined ? { preparedName: inner.preparedName } : {}),
4374
- ...(inner.rowLock ? { rowLock: true } : {}),
4375
- };
4246
+ return this.requireFound(this.buildFindFirstAs(args, 'findFirstOrThrow'), args?.where, 'findFirstOrThrow');
4376
4247
  }
4377
4248
  // -------------------------------------------------------------------------
4378
4249
  // findUniqueOrThrow, like findUnique but throws if no record found
@@ -4380,30 +4251,27 @@ export class QueryInterface {
4380
4251
  async findUniqueOrThrow(args) {
4381
4252
  args = this.normalizeArgs(args);
4382
4253
  this.assertLockInTransaction(args, 'findUniqueOrThrow');
4383
- return this.executeWithMiddleware('findUniqueOrThrow', args, async () => {
4254
+ return this.executeWithMiddleware('findUniqueOrThrow', args, () => {
4384
4255
  const deferred = this.buildFindUniqueOrThrow(args);
4385
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args.timeout, this.preparedNameFor(args, deferred.preparedName));
4386
- return deferred.transform(result);
4256
+ return this.executeRead(deferred, args);
4387
4257
  });
4388
4258
  }
4389
4259
  buildFindUniqueOrThrow(args) {
4390
4260
  args = this.normalizeArgs(args);
4391
- const inner = this.buildFindUnique(args);
4261
+ return this.requireFound(this.buildFindUnique(args), args.where, 'findUniqueOrThrow');
4262
+ }
4263
+ /** The throwing read wrappers retain the inner statement and its markers. */
4264
+ requireFound(inner, where, operation) {
4392
4265
  return {
4393
4266
  sql: inner.sql,
4394
4267
  params: inner.params,
4395
4268
  transform: (result) => {
4396
4269
  const row = inner.transform(result);
4397
- if (row === null) {
4398
- throw new NotFoundError({
4399
- table: this.table,
4400
- where: args.where,
4401
- operation: 'findUniqueOrThrow',
4402
- });
4403
- }
4270
+ if (row === null)
4271
+ throw new NotFoundError({ table: this.table, where, operation });
4404
4272
  return row;
4405
4273
  },
4406
- tag: `${this.table}.findUniqueOrThrow`,
4274
+ tag: `${this.table}.${operation}`,
4407
4275
  ...(inner.preparedName !== undefined ? { preparedName: inner.preparedName } : {}),
4408
4276
  ...(inner.rowLock ? { rowLock: true } : {}),
4409
4277
  };
@@ -4495,33 +4363,44 @@ export class QueryInterface {
4495
4363
  // Nested write helpers (shared by create + update)
4496
4364
  // -------------------------------------------------------------------------
4497
4365
  async nestedCreate(args) {
4366
+ // Refuse before a belongsTo write or transaction can produce effects.
4367
+ writesMod.assertWritable(this.ctx, 'create');
4498
4368
  const data = args.data;
4369
+ assertNestedArrayWrites(this.schema, this.table, data);
4499
4370
  // Validated up front, before any row is written, and then applied by the
4500
4371
  // nested engine's final read-back, which already speaks select/omit.
4501
4372
  this.resolveWriteProjection(args);
4502
4373
  const shape = { select: args.select, omit: args.omit };
4503
4374
  if (this.txScoped) {
4504
- const ctx = this.buildNestedCtx();
4375
+ const ctx = this.buildNestedCtx(args.timeout);
4505
4376
  return executeNestedCreate(ctx, this.table, data, 0, [], shape);
4506
4377
  }
4507
4378
  return this.runInImplicitTx(async (ctx) => {
4508
4379
  const result = await executeNestedCreate(ctx, this.table, data, 0, [], shape);
4509
4380
  return result;
4510
- });
4381
+ }, args.timeout);
4511
4382
  }
4512
4383
  async nestedUpdate(args) {
4384
+ writesMod.assertWritable(this.ctx, 'update');
4513
4385
  const data = args.data;
4514
4386
  const where = args.where;
4387
+ // The lock goes to the parent's own UPDATE, which the nested engine runs
4388
+ // before any relation write; its version column is refused in `data`
4389
+ // here, before a transaction opens, as on the flat path.
4390
+ const lock = args.optimisticLock;
4391
+ if (lock)
4392
+ writesMod.assertLockColumnNotWritten(this.tableMeta, this.table, data, lock.field);
4393
+ assertNestedArrayWrites(this.schema, this.table, data);
4515
4394
  this.resolveWriteProjection(args);
4516
4395
  const shape = { select: args.select, omit: args.omit };
4517
4396
  if (this.txScoped) {
4518
- const ctx = this.buildNestedCtx();
4519
- return executeNestedUpdate(ctx, this.table, where, data, 0, [], shape);
4397
+ const ctx = this.buildNestedCtx(args.timeout);
4398
+ return executeNestedUpdate(ctx, this.table, where, data, 0, [], shape, lock);
4520
4399
  }
4521
4400
  return this.runInImplicitTx(async (ctx) => {
4522
- const result = await executeNestedUpdate(ctx, this.table, where, data, 0, [], shape);
4401
+ const result = await executeNestedUpdate(ctx, this.table, where, data, 0, [], shape, lock);
4523
4402
  return result;
4524
- });
4403
+ }, args.timeout);
4525
4404
  }
4526
4405
  /**
4527
4406
  * Check out a guarded pooled connection, as a typed error when that fails.
@@ -4529,10 +4408,10 @@ export class QueryInterface {
4529
4408
  * matters); the cursor stream holds it, and a nested write opens its
4530
4409
  * implicit transaction on one through `openCheckout`.
4531
4410
  */
4532
- acquireConnection() {
4533
- return acquireConnection(this.pool);
4411
+ acquireConnection(signal) {
4412
+ return signal ? acquireStreamConnection(this.pool, signal) : acquireConnection(this.pool);
4534
4413
  }
4535
- async runInImplicitTx(fn) {
4414
+ async runInImplicitTx(fn, timeout) {
4536
4415
  // client.ts registers TransactionClient when it is evaluated (it cannot be
4537
4416
  // imported from here, see transaction-client-slot.ts). Read before the
4538
4417
  // checkout, so a program that never loaded client.ts gets a typed error
@@ -4540,14 +4419,15 @@ export class QueryInterface {
4540
4419
  const TransactionClient = transactionClientFor(`A nested write or lookup-first upsert on "${this.table}"`);
4541
4420
  // BEGIN runs inside openCheckout, which sends it once more on a fresh
4542
4421
  // connection when the first one turns out to be dead and releases the
4543
- // connection itself when BEGIN fails for good. The catch below therefore
4422
+ // connection itself when BEGIN fails for good. The settlement therefore
4544
4423
  // only sees a transaction that began, and never emits a stray ROLLBACK on
4545
4424
  // a connection that opened none.
4546
- const { client, checkout } = await openCheckout(this.pool, (c) => c.query(this.dialect.beginStatement()));
4547
- try {
4425
+ const held = await openCheckout(this.pool, (c) => sendControl(c, this.dialect.beginStatement()));
4426
+ const state = new TransactionState(held.client, this.dialect);
4427
+ return completeTransaction(held, state, this.dialect, undefined, async () => {
4548
4428
  const tx = new TransactionClient(
4549
4429
  // biome-ignore lint/suspicious/noExplicitAny: MiddlewareFn and Middleware are structurally identical
4550
- client, this.schema,
4430
+ held.client, this.schema,
4551
4431
  // biome-ignore lint/suspicious/noExplicitAny: MiddlewareFn and Middleware are structurally identical
4552
4432
  this.middlewares, this.options,
4553
4433
  // Pass the source pool so its read-only guard + capabilities carry into
@@ -4555,31 +4435,16 @@ export class QueryInterface {
4555
4435
  // read-only client's nested writes bypass the E018 guard and an
4556
4436
  // older-engine client falls back to the full capability set inside the
4557
4437
  // implicit transaction.
4558
- this.pool);
4559
- const ctx = {
4438
+ this.pool, state);
4439
+ return fn({
4560
4440
  schema: this.schema,
4561
4441
  // biome-ignore lint/suspicious/noExplicitAny: TransactionClient satisfies NestedWriteContext['tx'] at runtime
4562
- tx: unlockNestedWriteTx(tx),
4442
+ tx: unlockNestedWriteTx(tx, timeout),
4563
4443
  scopedConnect: this.scopedConnect,
4564
- };
4565
- const result = await fn(ctx);
4566
- await client.query(this.dialect.commitStatement());
4567
- return result;
4568
- }
4569
- catch (err) {
4570
- try {
4571
- await client.query(this.dialect.rollbackStatement());
4572
- }
4573
- catch {
4574
- // Best-effort rollback: connection may have died.
4575
- }
4576
- throw explainConnectionLoss(err, checkout.lostWith);
4577
- }
4578
- finally {
4579
- checkout.release();
4580
- }
4444
+ });
4445
+ });
4581
4446
  }
4582
- buildNestedCtx() {
4447
+ buildNestedCtx(timeout) {
4583
4448
  const pool = this.pool;
4584
4449
  const schema = this.schema;
4585
4450
  const middlewares = this.middlewares;
@@ -4589,7 +4454,7 @@ export class QueryInterface {
4589
4454
  const opts = txQueryOptions(this.options);
4590
4455
  return {
4591
4456
  schema,
4592
- tx: unlockNestedWriteTx(this.makeTxProxy(pool, schema, middlewares, opts)),
4457
+ tx: unlockNestedWriteTx(this.makeTxProxy(pool, schema, middlewares, opts), timeout),
4593
4458
  };
4594
4459
  }
4595
4460
  // biome-ignore lint/suspicious/noExplicitAny: bridges MiddlewareFn[] ↔ Middleware[] and QI ↔ NestedWriteContext type gap
@@ -4617,6 +4482,7 @@ export class QueryInterface {
4617
4482
  // First: the nested-write branch below decides before upsertLookupReason
4618
4483
  // would have refused it.
4619
4484
  writesMod.assertNoOptimisticLock(this.ctx, args, 'upsert');
4485
+ writesMod.assertWritable(this.ctx, 'upsert');
4620
4486
  if (this.upsertNeedsLookup(args)) {
4621
4487
  return this.upsertLookupFirst(args);
4622
4488
  }
@@ -4640,10 +4506,10 @@ export class QueryInterface {
4640
4506
  * `upsert` as Prisma defines it: find the row `where` names, update it if it
4641
4507
  * exists, else insert `create`, in one transaction (the caller's, when there
4642
4508
  * is one). Taken whenever the single conflict statement would mean something
4643
- * else (`upsertLookupReason`: `where` not pinned to `create`'s values, an
4644
- * empty `update`, a global filter the engine's statement cannot carry) and
4645
- * whenever `create` or `update` holds nested relation writes, which only the
4646
- * nested-write engine can run.
4509
+ * else (`upsertLookupReason`: `where` not pinned to `create`'s values or not
4510
+ * exactly one unique key, an empty `update`, a global filter the engine's
4511
+ * statement cannot carry) and whenever `create` or `update` holds nested
4512
+ * relation writes, which only the nested-write engine can run.
4647
4513
  *
4648
4514
  * Validation is DATA-INDEPENDENT, as it is for the batched relation loader:
4649
4515
  * both halves are compiled before the lookup runs, so an unknown field in
@@ -4672,6 +4538,7 @@ export class QueryInterface {
4672
4538
  const shape = { select: args.select, omit: args.omit, timeout: args.timeout };
4673
4539
  const scalarCreate = extractRelationFields(create, this.tableMeta).scalars;
4674
4540
  const scalarUpdate = extractRelationFields(update, this.tableMeta).scalars;
4541
+ assertNestedArrayWrites(this.schema, this.table, [create, update]);
4675
4542
  const updateIsEmpty = Object.values(update).every((v) => v === undefined);
4676
4543
  if (Object.keys(scalarCreate).length > 0)
4677
4544
  this.buildCreate({ data: scalarCreate });
@@ -4721,24 +4588,22 @@ export class QueryInterface {
4721
4588
  // -------------------------------------------------------------------------
4722
4589
  async count(args) {
4723
4590
  args = this.normalizeArgs(args);
4724
- return this.executeWithMiddleware('count', (args ?? {}), async () => {
4591
+ return this.executeWithMiddleware('count', (args ?? {}), () => {
4725
4592
  const deferred = this.buildCount(args);
4726
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args?.timeout, this.preparedNameFor(args, deferred.preparedName));
4727
- return deferred.transform(result);
4593
+ return this.executeRead(deferred, args);
4728
4594
  });
4729
4595
  }
4730
4596
  buildCount(args) {
4731
4597
  args = this.normalizeArgs(args);
4732
4598
  this.currentSkip = resolveSkipGlobalFilters(args?.skipGlobalFilters);
4733
- const effWhere = this.mergeGlobalFilter(args?.where);
4599
+ const effWhere = whereMod.mergeGlobalFilter(this.ctx, args?.where);
4734
4600
  const hasWhere = effWhere !== undefined;
4735
4601
  const whereObj = (effWhere ?? {});
4736
4602
  const whereFp = hasWhere ? this.fingerprintWhere(whereObj) : '';
4737
- const ck = `cnt:${whereFp}${this.globalFilterCacheSegment()}`;
4603
+ const ck = `cnt:${whereFp}${whereMod.globalFilterCacheSegment(this.ctx)}`;
4738
4604
  const params = [];
4739
4605
  const buildSql = (freshParams) => {
4740
- const clause = hasWhere ? this.buildWhereClause(whereObj, freshParams) : null;
4741
- const whereSql = clause ? ` WHERE ${clause}` : '';
4606
+ const whereSql = hasWhere ? whereMod.buildWhereSql(this.ctx, whereObj, freshParams) : '';
4742
4607
  return `SELECT ${this.castAgg('COUNT(*)', 'int')} AS count FROM ${this.q(this.table)}${whereSql}`;
4743
4608
  };
4744
4609
  const entry = this.acquireSql(ck, buildSql);
@@ -4756,10 +4621,9 @@ export class QueryInterface {
4756
4621
  }
4757
4622
  async groupBy(args) {
4758
4623
  args = this.normalizeArgs(args);
4759
- return this.executeWithMiddleware('groupBy', args, async () => {
4624
+ return this.executeWithMiddleware('groupBy', args, () => {
4760
4625
  const deferred = this.buildGroupBy(args);
4761
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args.timeout, this.preparedNameFor(args, deferred.preparedName));
4762
- return deferred.transform(result);
4626
+ return this.executeRead(deferred, args);
4763
4627
  });
4764
4628
  }
4765
4629
  buildGroupBy(args) {
@@ -4772,63 +4636,14 @@ export class QueryInterface {
4772
4636
  }
4773
4637
  async aggregate(args) {
4774
4638
  args = this.normalizeArgs(args);
4775
- return this.executeWithMiddleware('aggregate', args, async () => {
4639
+ return this.executeWithMiddleware('aggregate', args, () => {
4776
4640
  const deferred = this.buildAggregate(args);
4777
- const result = await this.readWithTimeout(deferred.sql, deferred.params, args.timeout, this.preparedNameFor(args, deferred.preparedName));
4778
- return deferred.transform(result);
4641
+ return this.executeRead(deferred, args);
4779
4642
  });
4780
4643
  }
4781
- // =========================================================================
4782
- // Internal helpers
4783
- // =========================================================================
4784
- // ---------------------------------------------------------------------------
4785
- // Relation + orderBy compilation (extracted to relations.ts).
4786
- // ---------------------------------------------------------------------------
4787
- resolveColumns(select, omit, includePii) {
4788
- return relationsMod.resolveColumns(this.ctx, select, omit, includePii);
4789
- }
4790
4644
  withFingerprint(withClause, table, depth = 0) {
4791
4645
  return relationsMod.withFingerprint(this.ctx, withClause, table, depth);
4792
4646
  }
4793
- collectWithParams(withClause, params, table, flattenPlan) {
4794
- relationsMod.collectWithParams(this.ctx, withClause, params, table, flattenPlan);
4795
- }
4796
- orderByEntryFingerprint(d, targetTable) {
4797
- return relationsMod.orderByEntryFingerprint(this.ctx, d, targetTable);
4798
- }
4799
- buildOrderBy(orderBy, params, lateralSink) {
4800
- return relationsMod.buildOrderBy(this.ctx, orderBy, params, lateralSink);
4801
- }
4802
- isRelationOrderByValue(value) {
4803
- return relationsMod.isRelationOrderByValue(this.ctx, value);
4804
- }
4805
- nullsSuffix(nulls) {
4806
- return relationsMod.nullsSuffix(this.ctx, nulls);
4807
- }
4808
- resolveOrderByColumn(table, meta, key) {
4809
- return relationsMod.resolveOrderByColumn(this.ctx, table, meta, key);
4810
- }
4811
- validateJsonPathOrderBy(table, meta, field, spec) {
4812
- return relationsMod.validateJsonPathOrderBy(this.ctx, table, meta, field, spec);
4813
- }
4814
- buildJsonPathOrderEntry(table, meta, field, spec, prefix, params) {
4815
- return relationsMod.buildJsonPathOrderEntry(this.ctx, table, meta, field, spec, prefix, params);
4816
- }
4817
- collectRelationPickOrderParams(relName, relDef, spec, params) {
4818
- relationsMod.collectRelationPickOrderParams(this.ctx, relName, relDef, spec, params);
4819
- }
4820
- collectRelationCountParams(relDef, params) {
4821
- relationsMod.collectRelationCountParams(this.ctx, relDef, params);
4822
- }
4823
- getCamelDateFields(table, meta) {
4824
- return relationsMod.getCamelDateFields(this.ctx, table, meta);
4825
- }
4826
- makeNestedParser(withClause, includePii, flattenPlan) {
4827
- return relationsMod.makeNestedParser(this.ctx, withClause, includePii, flattenPlan);
4828
- }
4829
- buildSelectWithRelations(table, withClause, params, columnsList, depth, path, includePii, flatten) {
4830
- return relationsMod.buildSelectWithRelations(this.ctx, table, withClause, params, columnsList, depth, path, includePii, flatten);
4831
- }
4832
4647
  /**
4833
4648
  * Compile the `relationLoadStrategy: 'flatten'` plan for a findMany-shaped
4834
4649
  * query, or `null` to emit exactly the SQL (and cache key) the default
@@ -4846,7 +4661,7 @@ export class QueryInterface {
4846
4661
  * strategy, silently and byte-identically):
4847
4662
  * - the resolved strategy is not `'flatten'`;
4848
4663
  * - `jsonEncoding: 'positional'` (a flattened relation emits no JSON at all,
4849
- * so the two are not composed in this version). NOTE that this is the
4664
+ * so the two are not composed in this version). This is the
4850
4665
  * PostgreSQL DEFAULT, so on Postgres `'flatten'` engages only when the
4851
4666
  * caller ALSO passes `jsonEncoding: 'object'`. The fallback is silent and
4852
4667
  * byte-identical, and `warnFlattenBlocked` names the encoding and the
@@ -4959,10 +4774,8 @@ export class QueryInterface {
4959
4774
  // ---------------------------------------------------------------------------
4960
4775
  // WHERE-clause compilation (extracted to where.ts).
4961
4776
  //
4962
- // These thin delegators forward to the free functions in where.ts, passing
4963
- // this.ctx (the BuilderCtx view built in the constructor). Methods called
4964
- // only from within where.ts itself were moved out entirely; only the
4965
- // cross-module + public + @internal entry points keep a delegator here.
4777
+ // Public fingerprint/collect entry points retain their delegators. Private
4778
+ // compiler calls use the module functions directly with the same ctx.
4966
4779
  // ---------------------------------------------------------------------------
4967
4780
  fingerprintWhere(where) {
4968
4781
  return whereMod.fingerprintWhere(this.ctx, where);
@@ -4970,42 +4783,6 @@ export class QueryInterface {
4970
4783
  collectWhereParams(where, params) {
4971
4784
  whereMod.collectWhereParams(this.ctx, where, params);
4972
4785
  }
4973
- resolveGlobalFilter(table, skip = this.currentSkip) {
4974
- return whereMod.resolveGlobalFilter(this.ctx, table, skip);
4975
- }
4976
- mergeGlobalFilter(userWhere) {
4977
- return whereMod.mergeGlobalFilter(this.ctx, userWhere);
4978
- }
4979
- collectTargetGlobalFilterAlias(targetTable, params) {
4980
- whereMod.collectTargetGlobalFilterAlias(this.ctx, targetTable, params);
4981
- }
4982
- globalFilterCacheSegment() {
4983
- return whereMod.globalFilterCacheSegment(this.ctx);
4984
- }
4985
- buildWhereClause(where, params) {
4986
- return whereMod.buildWhereClause(this.ctx, where, params);
4987
- }
4988
- buildAliasWhere(targetTable, targetMeta, alias, where, params) {
4989
- return whereMod.buildAliasWhere(this.ctx, targetTable, targetMeta, alias, where, params);
4990
- }
4991
- vectorOperator(field, rawColumn, metric) {
4992
- return whereMod.vectorOperator(this.ctx, field, rawColumn, metric);
4993
- }
4994
- pushVectorParam(field, _rawColumn, to, params) {
4995
- return whereMod.pushVectorParam(this.ctx, field, _rawColumn, to, params);
4996
- }
4997
- normalizeRelationFilter(relDef, filterObj) {
4998
- return whereMod.normalizeRelationFilter(this.ctx, relDef, filterObj);
4999
- }
5000
- isJsonColumnType(colType) {
5001
- return whereMod.isJsonColumnType(this.ctx, colType);
5002
- }
5003
- getColumnPgType(column) {
5004
- return whereMod.getColumnPgType(this.ctx, column);
5005
- }
5006
- jsonPathParam(path, nativeForm) {
5007
- return whereMod.jsonPathParam(this.ctx, path, nativeForm);
5008
- }
5009
4786
  /**
5010
4787
  * Collect params for an orderBy clause. Vector KNN ordering pushes the
5011
4788
  * `$n::vector` query vector and JSON-path ordering pushes its text[] path;
@@ -5013,43 +4790,7 @@ export class QueryInterface {
5013
4790
  * order exactly so the cached-SQL param re-collection stays in lockstep.
5014
4791
  */
5015
4792
  collectOrderByParams(orderBy, params) {
5016
- for (const [key, dir] of orderByEntries(orderBy)) {
5017
- if (isVectorOrderBy(dir)) {
5018
- const rawColumn = this.toColumn(key);
5019
- // Re-run the same validation as buildOrderBy so the collect path can
5020
- // never push a param that the build path rejected (or vice versa).
5021
- this.vectorOperator(key, rawColumn, dir.distance.metric);
5022
- this.pushVectorParam(key, rawColumn, dir.distance.to, params);
5023
- continue;
5024
- }
5025
- // JSON-path ordering: mirrors buildJsonPathOrderEntry: same validation,
5026
- // then the path bound as one text[] param.
5027
- if (isJsonPathOrderBy(dir)) {
5028
- this.validateJsonPathOrderBy(this.table, this.tableMeta, key, dir);
5029
- params.push(this.jsonPathParam(dir.path));
5030
- continue;
5031
- }
5032
- // To-many relation orderBy (`{ posts: { _count } }`) uses the same count
5033
- // subquery as `_count`: mirror its global-filter params. Pick-row
5034
- // ordering mirrors its full param chain (by-path / global filter /
5035
- // pick.where / pick.orderBy paths). To-one relation orderBy is mirrored
5036
- // by running its build (see collectToOneRelationOrderParams).
5037
- if (this.isRelationOrderByValue(dir)) {
5038
- // Mirrors the build path's resolution, so a cache HIT binds params for
5039
- // the same relation the cached SQL was built from.
5040
- const resolvedRel = resolveRelation(this.tableMeta.relations, key);
5041
- const relDef = resolvedRel?.def;
5042
- if (relDef && isRelationPickOrderBy(dir)) {
5043
- this.collectRelationPickOrderParams(resolvedRel.name, relDef, dir, params);
5044
- }
5045
- else if (relDef && (relDef.type === 'hasMany' || relDef.type === 'manyToMany')) {
5046
- this.collectRelationCountParams(relDef, params);
5047
- }
5048
- else if (relDef) {
5049
- relationsMod.collectToOneRelationOrderParams(this.ctx, key, dir, params);
5050
- }
5051
- }
5052
- }
4793
+ relationsMod.collectOrderParams(this.ctx, orderByEntries(orderBy), params);
5053
4794
  }
5054
4795
  // -------------------------------------------------------------------------
5055
4796
  // Global filters (soft-delete / multi-tenancy, WS-G)
@@ -5224,89 +4965,51 @@ export class QueryInterface {
5224
4965
  // UTC so results don't depend on the server's time zone.
5225
4966
  return this.utcTimestamps ? parseDbDate(String(value)) : new Date(value);
5226
4967
  }
5227
- /** The non-temporal decode kinds of `table`'s columns, by column and by field name. */
4968
+ /** The non-temporal decode kinds and dialect readers of one immutable table. */
5228
4969
  getCellKinds(table, meta) {
5229
- let kinds = this.cellKindCache.get(table);
5230
- if (!kinds) {
5231
- kinds = new Map();
4970
+ let cached = this.cellKindCache.get(table);
4971
+ if (!cached) {
4972
+ cached = { kinds: new Map() };
5232
4973
  for (const column of meta.columns) {
5233
4974
  // Metadata may carry the type on the column or only in the table map.
5234
4975
  const pgType = column.pgType ?? meta.pgTypes?.[column.name];
5235
4976
  if (typeof pgType !== 'string')
5236
4977
  continue;
5237
- let kind = cellKindOf(pgType, this.schema.enums);
4978
+ let kind = cellKindOf(pgType, this.schema.enums, columnOperandKind(meta, column.name) === 'array');
5238
4979
  const decode = kind === CELL_PLAIN ? this.dialect.decodeColumnValue?.(pgType) : undefined;
5239
4980
  if (decode !== undefined) {
5240
4981
  kind = CELL_DIALECT;
5241
- let decoders = this.dialectDecodeCache.get(table);
5242
- if (!decoders) {
5243
- decoders = new Map();
5244
- this.dialectDecodeCache.set(table, decoders);
5245
- }
5246
- decoders.set(column.name, decode);
5247
- decoders.set(column.field, decode);
4982
+ cached.decoders ??= new Map();
4983
+ cached.decoders.set(column.name, decode);
4984
+ cached.decoders.set(column.field, decode);
5248
4985
  }
5249
4986
  if (kind === CELL_PLAIN)
5250
4987
  continue;
5251
- kinds.set(column.name, kind);
5252
- kinds.set(column.field, kind);
4988
+ cached.kinds.set(column.name, kind);
4989
+ cached.kinds.set(column.field, kind);
5253
4990
  }
5254
- this.cellKindCache.set(table, kinds);
4991
+ this.cellKindCache.set(table, cached);
5255
4992
  }
5256
- return kinds;
4993
+ return cached;
5257
4994
  }
5258
4995
  /** One cell's decode, for every kind but {@link CELL_PLAIN}. */
5259
4996
  decodeCell(kind, value, table, field) {
5260
- switch (kind) {
5261
- case CELL_TEMPORAL:
5262
- return this.decodeTemporalCell(value, table, field);
5263
- case CELL_FLOAT:
5264
- return readJsonFloat(value);
5265
- case CELL_FLOAT_ARRAY:
5266
- return readJsonFloatArray(value);
5267
- case CELL_TEXT_ARRAY:
5268
- return readTextArray(value);
5269
- case CELL_DIALECT:
5270
- return this.decodeDialectCell(value, table, field);
5271
- default:
4997
+ if (kind === CELL_TEMPORAL)
4998
+ return this.decodeTemporalCell(value, table, field);
4999
+ if (kind === CELL_DIALECT) {
5000
+ if (value === null || value === undefined)
5272
5001
  return value;
5002
+ const decode = this.cellKindCache.get(table)?.decoders?.get(field);
5003
+ return decode ? decode(value) : value;
5273
5004
  }
5005
+ const read = CELL_READERS[kind];
5006
+ return read === undefined ? value : read(value);
5274
5007
  }
5275
5008
  /**
5276
- * A {@link CELL_DIALECT} cell: the dialect's decode for the column's declared
5277
- * type, recorded by {@link getCellKinds} when it classified the column.
5278
- */
5279
- decodeDialectCell(value, table, field) {
5280
- if (value === null || value === undefined)
5281
- return value;
5282
- const decode = this.dialectDecodeCache.get(table)?.get(field);
5283
- return decode ? decode(value) : value;
5284
- }
5285
- /**
5286
- * Build the decode plan for one exact column list, and remember it as this
5287
- * table's most recent shape so the next row of the same result set hits the
5288
- * fast path in {@link parseRow}.
5289
- *
5290
- * The shape key's delimiter is NUL because it is the one byte a Postgres
5291
- * identifier cannot contain, even quoted, so no table or column name can
5292
- * forge a collision. It MUST be written as the six-character escape, never
5293
- * as a literal NUL byte: a raw NUL makes byte-oriented tools classify this
5294
- * file as binary, and `grep` then reports ZERO matches for a term that is
5295
- * present rather than saying it declined to look. This is the largest file
5296
- * in the repo, and that silent empty result has already sent more than one
5297
- * search down the wrong path.
5298
- */
5299
- buildRowDecodePlan(table, meta, keys) {
5300
- const plan = this.rowDecodePlanFor(table, meta, keys);
5301
- this.rowPlanLast.set(table, plan);
5302
- return plan;
5303
- }
5304
- /**
5305
- * The cached decode plan for one exact column list, without touching the
5306
- * per-table most-recent slot. {@link buildRowDecodePlan} is the per-row entry;
5307
- * this is also what the positional nested-row plan in relations.ts reads
5308
- * (through the ctx) when it is built, so a nested row decodes by exactly the
5309
- * field names and cell kinds {@link parseRow} would give the same keys.
5009
+ * The bounded decode plan for one exact column list. Both the object parser
5010
+ * and positional relation parser use these same names and cell kinds.
5011
+ * NUL separates identifiers because it cannot occur in a SQL identifier;
5012
+ * keep it escaped in source so text tools never classify this file as binary.
5310
5013
  */
5311
5014
  rowDecodePlanFor(table, meta, keys) {
5312
5015
  const shapeKey = `${table}\u0000${keys.join('\u0000')}`;
@@ -5316,8 +5019,8 @@ export class QueryInterface {
5316
5019
  const dateCols = meta.dateColumns;
5317
5020
  // camelCase-keyed date fields, so nested json_build_object rows (whose
5318
5021
  // keys are already camelCase) get the same Date coercion as top-level rows.
5319
- const camelDateFields = this.getCamelDateFields(table, meta);
5320
- const cellKinds = this.getCellKinds(table, meta);
5022
+ const camelDateFields = relationsMod.getCamelDateFields(this.ctx, table, meta);
5023
+ const { kinds: cellKinds } = this.getCellKinds(table, meta);
5321
5024
  const cols = keys.slice();
5322
5025
  const fields = [];
5323
5026
  const kinds = [];
@@ -5334,62 +5037,58 @@ export class QueryInterface {
5334
5037
  }
5335
5038
  return plan;
5336
5039
  }
5337
- /**
5338
- * Whether a cached plan describes exactly this row's column list, in order.
5339
- * A pointer compare per column: both sides are the driver's own interned
5340
- * column-name strings, so this is far cheaper than the reverse-map lookup and
5341
- * two Set probes per column that it replaces, and unlike a length check or a
5342
- * fingerprint it CANNOT accept a different projection that happens to look
5343
- * similar. That matters more than the speed: a positional plan applied to the
5344
- * wrong column list would silently write each value under a neighbouring
5345
- * field's name, which is the one failure mode worth paying a full comparison
5346
- * to make impossible.
5347
- */
5348
- static rowPlanMatches(plan, keys) {
5349
- const cols = plan.cols;
5350
- if (cols.length !== keys.length)
5351
- return false;
5352
- for (let i = 0; i < keys.length; i++) {
5353
- if (cols[i] !== keys[i])
5354
- return false;
5355
- }
5356
- return true;
5357
- }
5358
5040
  parseRow(row, table) {
5359
- const parsed = {};
5041
+ return this.makeRowParser(table)(row);
5042
+ }
5043
+ makeRowParser(table) {
5044
+ const cached = this.rowParsers.get(table);
5045
+ if (cached)
5046
+ return cached;
5360
5047
  const meta = this.schema.tables[table];
5361
- if (meta) {
5362
- // Every row of one result set has the same columns in the same order (a
5363
- // SQL result set has fixed field descriptors, and a nested row decoded
5364
- // from `json_build_object` has a fixed key list), so the per-column
5365
- // name resolution and date-column membership tests are the same answer
5366
- // recomputed for every row. Resolve them ONCE per column shape and keep
5367
- // the plan; the shape is verified against each row rather than assumed,
5368
- // so a caller that does hand this function heterogeneous rows gets a
5369
- // rebuilt plan instead of a mis-mapped one.
5370
- const keys = Object.keys(row);
5371
- const last = this.rowPlanLast.get(table);
5372
- const plan = last !== undefined && QueryInterface.rowPlanMatches(last, keys)
5373
- ? last
5374
- : this.buildRowDecodePlan(table, meta, keys);
5375
- const { cols, fields, kinds } = plan;
5376
- for (let i = 0; i < cols.length; i++) {
5377
- const field = fields[i];
5378
- const value = row[cols[i]];
5379
- const kind = kinds[i];
5380
- // A float from the driver is already a number; only JSON's strings need reading.
5381
- parsed[field] =
5382
- kind === CELL_PLAIN || (kind === CELL_FLOAT && typeof value !== 'string')
5383
- ? value
5384
- : this.decodeCell(kind, value, table, field);
5048
+ let last;
5049
+ let plain;
5050
+ const parse = (row) => {
5051
+ const parsed = {};
5052
+ if (meta) {
5053
+ // Every row of one result set has the same columns in the same order (a
5054
+ // SQL result set has fixed field descriptors, and a nested row decoded
5055
+ // from `json_build_object` has a fixed key list), so the per-column
5056
+ // name resolution and date-column membership tests are the same answer
5057
+ // recomputed for every row. Resolve them ONCE per column shape and keep
5058
+ // the plan; the shape is verified against each row rather than assumed,
5059
+ // so a caller that does hand this function heterogeneous rows gets a
5060
+ // rebuilt plan instead of a mis-mapped one.
5061
+ const keys = Object.keys(row);
5062
+ // String keys use the shared comparator's exact, ordered === checks.
5063
+ if (last === undefined || !cacheParamsEqual(last.cols, keys)) {
5064
+ last = this.rowDecodePlanFor(table, meta, keys);
5065
+ plain = last.kinds.map((kind, i) => kind === CELL_PLAIN && last.fields[i] !== '__proto__');
5066
+ }
5067
+ const { cols, fields, kinds } = last;
5068
+ // Keep this row's classification across reentrant reads of another shape.
5069
+ const plainColumns = plain;
5070
+ for (let i = 0; i < cols.length; i++) {
5071
+ const field = fields[i];
5072
+ let value = row[cols[i]];
5073
+ if (!plainColumns[i]) {
5074
+ const kind = kinds[i];
5075
+ if (field === '__proto__')
5076
+ Object.defineProperty(parsed, field, { writable: true, enumerable: true, configurable: true });
5077
+ if (kind !== CELL_PLAIN && (kind !== CELL_FLOAT || typeof value === 'string'))
5078
+ value = this.decodeCell(kind, value, table, field);
5079
+ }
5080
+ parsed[field] = value;
5081
+ }
5385
5082
  }
5386
- }
5387
- else {
5388
- // Fallback: no metadata, use regex conversion
5389
- for (const [col, value] of Object.entries(row)) {
5390
- parsed[snakeToCamel(col)] = value;
5083
+ else {
5084
+ // Fallback: no metadata, use regex conversion
5085
+ for (const [col, value] of Object.entries(row)) {
5086
+ parsed[snakeToCamel(col)] = value;
5087
+ }
5391
5088
  }
5392
- }
5393
- return parsed;
5089
+ return parsed;
5090
+ };
5091
+ this.rowParsers.set(table, parse);
5092
+ return parse;
5394
5093
  }
5395
5094
  }