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
@@ -49,6 +49,7 @@ var __importStar = (this && this.__importStar) || (function () {
49
49
  Object.defineProperty(exports, "__esModule", { value: true });
50
50
  exports.piiSelectRefusedMessage = piiSelectRefusedMessage;
51
51
  exports.resolveProjection = resolveProjection;
52
+ exports.qualifiedColumns = qualifiedColumns;
52
53
  exports.resolveColumns = resolveColumns;
53
54
  exports.relationOptions = relationOptions;
54
55
  exports.relationOffset = relationOffset;
@@ -71,6 +72,7 @@ exports.compilePickPieces = compilePickPieces;
71
72
  exports.collectRelationPickOrderParams = collectRelationPickOrderParams;
72
73
  exports.buildRelationOrderClause = buildRelationOrderClause;
73
74
  exports.collectRelationOrderParams = collectRelationOrderParams;
75
+ exports.collectOrderParams = collectOrderParams;
74
76
  exports.buildRelationCountExpr = buildRelationCountExpr;
75
77
  exports.manyToManyTargetGlobalFilterExists = manyToManyTargetGlobalFilterExists;
76
78
  exports.collectManyToManyTargetGlobalFilter = collectManyToManyTargetGlobalFilter;
@@ -88,6 +90,7 @@ exports.decodePositionalRelations = decodePositionalRelations;
88
90
  exports.decodePositionalValue = decodePositionalValue;
89
91
  exports.decodePositionalObject = decodePositionalObject;
90
92
  exports.makePositionalRowParser = makePositionalRowParser;
93
+ exports.makeObjectRowParser = makeObjectRowParser;
91
94
  exports.provableUniqueTargetKey = provableUniqueTargetKey;
92
95
  exports.planFlattenWith = planFlattenWith;
93
96
  exports.emitFlattenNode = emitFlattenNode;
@@ -100,11 +103,12 @@ exports.buildManyToManySubquery = buildManyToManySubquery;
100
103
  const errors_js_1 = require("../errors.js");
101
104
  const index_advisor_js_1 = require("../index-advisor.js");
102
105
  const logger_js_1 = require("../logger.js");
106
+ const query_utils_js_1 = require("../query-utils.js");
103
107
  const schema_js_1 = require("../schema.js");
104
108
  const batched_loader_js_1 = require("./batched-loader.js");
109
+ const compound_unique_js_1 = require("./compound-unique.js");
105
110
  const filters_js_1 = require("./filters.js");
106
111
  const types_js_1 = require("./types.js");
107
- const utils_js_1 = require("./utils.js");
108
112
  const warn_registry_js_1 = require("./warn-registry.js");
109
113
  const whereMod = __importStar(require("./where.js"));
110
114
  const writesMod = __importStar(require("./writes.js"));
@@ -118,7 +122,7 @@ const writesMod = __importStar(require("./writes.js"));
118
122
  * that no longer reflects what was asked for.
119
123
  */
120
124
  function projectionColumn(table, meta, field, clause) {
121
- const column = (0, utils_js_1.resolveColumnName)(meta, field);
125
+ const column = (0, query_utils_js_1.resolveColumnName)(meta, field);
122
126
  if (column)
123
127
  return column;
124
128
  // A relation named in a projection is a habit, not a typo, so it gets its own
@@ -127,9 +131,9 @@ function projectionColumn(table, meta, field, clause) {
127
131
  // Resolved, so `select: { ripening_checks: true }` gets the "that is a
128
132
  // relation, use `with`" message rather than degrading to an unknown-field
129
133
  // suggestion that names the relation back at the caller.
130
- if ((0, utils_js_1.resolveRelationDef)(meta.relations, field))
131
- throw new errors_js_1.ValidationError((0, utils_js_1.relationInProjectionMessage)(table, field, clause));
132
- throw new errors_js_1.ValidationError((0, utils_js_1.unknownFieldMessage)(table, field, meta));
134
+ if ((0, query_utils_js_1.resolveRelationDef)(meta.relations, field))
135
+ throw new errors_js_1.ValidationError((0, query_utils_js_1.relationInProjectionMessage)(table, field, clause));
136
+ throw new errors_js_1.ValidationError((0, query_utils_js_1.unknownFieldMessage)(table, field, meta));
133
137
  }
134
138
  /**
135
139
  * The E003 text for a PII-tagged column named in `select` without
@@ -194,15 +198,15 @@ function resolveProjection(qi, table, meta, select, omit, includePii) {
194
198
  // Check 1 runs first so both are PRESENCE-decided exactly like the branch
195
199
  // below (`if (select)`): a truthiness-decided refusal here flipped verdicts
196
200
  // between strategies when the batched loader force-added correlation keys
197
- // to an all-falsy select (review-caught in 0.65). The batched loader
201
+ // to an all-falsy select (0.65). The batched loader
198
202
  // asserts the same two rules on the RAW args (`assertProjectionShape`)
199
203
  // before any adjustment, with these same messages.
200
204
  if (select && !Array.isArray(select)) {
201
205
  if (!Object.values(select).some(Boolean)) {
202
- throw new errors_js_1.ValidationError((0, utils_js_1.selectNamesNothingMessage)(table));
206
+ throw new errors_js_1.ValidationError((0, query_utils_js_1.selectNamesNothingMessage)(table));
203
207
  }
204
208
  if (omit && !Array.isArray(omit) && Object.values(omit).some(Boolean)) {
205
- throw new errors_js_1.ValidationError((0, utils_js_1.selectOmitExclusiveMessage)(table));
209
+ throw new errors_js_1.ValidationError((0, query_utils_js_1.selectOmitExclusiveMessage)(table));
206
210
  }
207
211
  }
208
212
  if (select) {
@@ -247,11 +251,11 @@ function resolveProjection(qi, table, meta, select, omit, includePii) {
247
251
  // projection positionally except through THIS list: the SELECT list, the
248
252
  // relation `json_build_object` pairs and the positional `RelationShape`
249
253
  // keys are all derived from it, so they move together. The one observable
250
- // consequence is that a projected row's KEY INSERTION order now follows the
254
+ // consequence is that a projected row's KEY INSERTION order follows the
251
255
  // table rather than the `select` literal.
252
256
  const piiCols = includePii ? undefined : writesMod.piiColumns(qi, meta);
253
257
  const stitchOnly = piiCols && piiCols.size > 0 ? (0, batched_loader_js_1.stitchOnlyFields)(select) : undefined;
254
- return (0, utils_js_1.canonicalColumnOrder)(meta, Object.entries(select)
258
+ return (0, query_utils_js_1.canonicalColumnOrder)(meta, Object.entries(select)
255
259
  .filter(([, v]) => v)
256
260
  .map(([k]) => {
257
261
  const column = projectionColumn(table, meta, k, 'select');
@@ -285,6 +289,10 @@ function resolveProjection(qi, table, meta, select, omit, includePii) {
285
289
  * The query's own table. Thin wrapper over {@link resolveProjection} kept for
286
290
  * the existing call sites in builder.ts.
287
291
  */
292
+ /** A qualified scalar projection, preserving the caller's column order. */
293
+ function qualifiedColumns(qi, columns, qualifier) {
294
+ return columns.map((column) => `${qualifier}.${qi.q(column)}`).join(', ');
295
+ }
288
296
  function resolveColumns(qi, select, omit, includePii) {
289
297
  return resolveProjection(qi, qi.table, qi.tableMeta, select, omit, includePii);
290
298
  }
@@ -363,7 +371,7 @@ function checkWithOptions(qi, table, relName, opts) {
363
371
  const advice = whereMod.adviceLogger(qi);
364
372
  if (!advice || !(0, warn_registry_js_1.shouldWarnOnce)(warn_registry_js_1.WARN_NS.unknownQueryOption, `${table}.with.${relName}.${key}`))
365
373
  continue;
366
- const suggestion = (0, utils_js_1.suggestKey)(key, WITH_OPTION_KEYS);
374
+ const suggestion = (0, query_utils_js_1.suggestKey)(key, WITH_OPTION_KEYS);
367
375
  (0, logger_js_1.logTo)(advice, 'warn', `unknown option "${key}" on relation "${relName}" in \`with\` on ${table}, it is ignored.` +
368
376
  (suggestion ? ` Did you mean "${suggestion}"?` : ''), { code: 'unknown-query-option', table, operation: 'with', key });
369
377
  }
@@ -442,7 +450,7 @@ function withFingerprint(qi, withClause, table, depth = 0) {
442
450
  .join(',')})`);
443
451
  continue;
444
452
  }
445
- const relDef = (0, utils_js_1.ownLookup)(meta.relations, relName);
453
+ const relDef = (0, query_utils_js_1.ownLookup)(meta.relations, relName);
446
454
  if (!relDef) {
447
455
  parts.push(`unknown:${relName}`);
448
456
  continue;
@@ -507,7 +515,7 @@ function collectWithParams(qi, withClause, params, table, flattenPlan) {
507
515
  if (!meta)
508
516
  return;
509
517
  for (const [relName, relSpec] of (0, filters_js_1.sortedEntries)(withClause)) {
510
- const relDef = (0, utils_js_1.ownLookup)(meta.relations, relName);
518
+ const relDef = (0, query_utils_js_1.ownLookup)(meta.relations, relName);
511
519
  if (!relDef)
512
520
  continue;
513
521
  const flatNode = flattenPlan?.nodes[relName];
@@ -545,81 +553,39 @@ function collectRelationSubqueryParams(qi, relDef, spec, params, _parentRef, dep
545
553
  // mirrors below must stay off for it (its documented contract remains
546
554
  // where → limit → nested).
547
555
  const nativeOrderPath = !qi.dialect.buildRelationSubquery;
548
- // manyToMany param order mirrors buildManyToManySubquery:
549
- // orderBy params → where params → limit param → nested-with params
550
- // (always, both paths).
551
- if (relDef.type === 'manyToMany') {
552
- const m2mOrderEntries = opts.orderBy ? (0, filters_js_1.orderByEntries)(opts.orderBy).filter(([, dir]) => dir !== undefined) : [];
553
- if (nativeOrderPath && m2mOrderEntries.length > 0) {
554
- collectRelationOrderParams(qi, targetTable, targetMeta, m2mOrderEntries, params);
555
- }
556
- if (opts.where) {
557
- whereMod.collectAliasWhereParams(qi, targetTable, targetMeta, opts.where, params);
558
- }
559
- whereMod.collectTargetGlobalFilterAlias(qi, targetTable, params);
560
- if (opts.limit !== undefined && !qi.dialect.inlineLimitOffset) {
561
- params.push(qi.paginationValue(opts.limit, 'relation limit'));
562
- }
563
- const m2mOffset = relationOffset(opts);
564
- if (m2mOffset !== undefined && !qi.dialect.inlineLimitOffset) {
565
- params.push(qi.paginationValue(m2mOffset, 'relation offset'));
566
- }
567
- if (opts.with) {
568
- for (const [nestedRelName, nestedSpec] of (0, filters_js_1.sortedEntries)(opts.with)) {
569
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
570
- if (!nestedRelDef)
571
- continue;
572
- collectRelationSubqueryParams(qi, nestedRelDef, nestedSpec, params, 'alias', depth + 1);
573
- }
574
- }
575
- return;
576
- }
577
- // Mirrors buildRelationSubquery's willWrap: `orderBy: {}` is treated as absent.
578
- const relOrderEntries = opts.orderBy ? (0, filters_js_1.orderByEntries)(opts.orderBy).filter(([, dir]) => dir !== undefined) : [];
579
- const hasOrder = relOrderEntries.length > 0;
556
+ const manyToMany = relDef.type === 'manyToMany';
557
+ const many = manyToMany || relDef.type === 'hasMany';
558
+ const entries = opts.orderBy ? (0, filters_js_1.orderByEntries)(opts.orderBy).filter(([, dir]) => dir !== undefined) : [];
580
559
  const offset = relationOffset(opts);
581
- const willWrap = relDef.type === 'hasMany' && (opts.limit !== undefined || offset !== undefined || hasOrder);
582
- // Non-wrapped path: nested relations BEFORE where/limit
583
- if (!willWrap && opts.with) {
584
- for (const [nestedRelName, nestedSpec] of (0, filters_js_1.sortedEntries)(opts.with)) {
585
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
586
- if (!nestedRelDef)
587
- continue;
588
- collectRelationSubqueryParams(qi, nestedRelDef, nestedSpec, params, 'alias', depth + 1);
560
+ const nestedLast = manyToMany || (many && (opts.limit !== undefined || offset !== undefined || entries.length > 0));
561
+ const collectNested = () => {
562
+ if (!opts.with)
563
+ return;
564
+ for (const [name, nestedSpec] of (0, filters_js_1.sortedEntries)(opts.with)) {
565
+ const nested = (0, query_utils_js_1.ownLookup)(targetMeta.relations, name);
566
+ if (nested)
567
+ collectRelationSubqueryParams(qi, nested, nestedSpec, params, 'alias', depth + 1);
589
568
  }
569
+ };
570
+ // Unwrapped to-one/hasMany builds nested SELECTs before its predicates;
571
+ // wrapped hasMany and every m2m build them after paging the inner rows.
572
+ if (!nestedLast)
573
+ collectNested();
574
+ if (nativeOrderPath && entries.length > 0) {
575
+ collectRelationOrderParams(qi, targetTable, targetMeta, entries, params);
590
576
  }
591
- // orderBy params (JSON paths / relation-order global filters): mirrors
592
- // buildRelationSubquery, which builds its ORDER BY terms BEFORE compiling
593
- // spec.where (both wrapped and non-wrapped paths).
594
- if (nativeOrderPath && hasOrder) {
595
- collectRelationOrderParams(qi, targetTable, targetMeta, relOrderEntries, params);
596
- }
597
- // where params, mirrors buildAliasWhere push order
598
577
  if (opts.where) {
599
578
  whereMod.collectAliasWhereParams(qi, targetTable, targetMeta, opts.where, params);
600
579
  }
601
- // Global filter on the target, mirrors targetGlobalFilterAlias in
602
- // buildRelationSubquery (pushed after spec.where, before limit).
603
580
  whereMod.collectTargetGlobalFilterAlias(qi, targetTable, params);
604
- // limit param, only hasMany parameterizes its limit (mirrors
605
- // buildRelationSubquery). belongsTo/hasOne ignore limit (always LIMIT 1), so
606
- // pushing one here would orphan a param and desync the collect path.
607
- // `limit: 0` pushes (LIMIT 0 is honored), so check !== undefined.
608
- if (relDef.type === 'hasMany' && opts.limit !== undefined && !qi.dialect.inlineLimitOffset) {
609
- params.push(qi.paginationValue(opts.limit, 'relation limit'));
610
- }
611
- if (relDef.type === 'hasMany' && offset !== undefined && !qi.dialect.inlineLimitOffset) {
612
- params.push(qi.paginationValue(offset, 'relation offset'));
613
- }
614
- // Wrapped path: nested relations AFTER where/limit (inside inner subquery)
615
- if (willWrap && opts.with) {
616
- for (const [nestedRelName, nestedSpec] of (0, filters_js_1.sortedEntries)(opts.with)) {
617
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
618
- if (!nestedRelDef)
619
- continue;
620
- collectRelationSubqueryParams(qi, nestedRelDef, nestedSpec, params, 'innerAlias', depth + 1);
621
- }
581
+ if (many && !qi.dialect.inlineLimitOffset) {
582
+ if (opts.limit !== undefined)
583
+ params.push(qi.paginationValue(opts.limit, 'relation limit'));
584
+ if (offset !== undefined)
585
+ params.push(qi.paginationValue(offset, 'relation offset'));
622
586
  }
587
+ if (nestedLast)
588
+ collectNested();
623
589
  }
624
590
  /**
625
591
  * Value-shape fingerprint for a single orderBy entry, so two queries whose
@@ -794,7 +760,7 @@ function nullsSuffix(qi, nulls) {
794
760
  * with both.
795
761
  */
796
762
  function resolveOrderByColumn(_qi, table, meta, key) {
797
- const col = (0, utils_js_1.resolveColumnName)(meta, key);
763
+ const col = (0, query_utils_js_1.resolveColumnName)(meta, key);
798
764
  if (col === undefined) {
799
765
  throw new errors_js_1.ValidationError(`Unknown field "${key}" in orderBy on table "${table}". ` +
800
766
  `Known fields: ${Object.keys(meta.columnMap).join(', ') || '(none)'}.`);
@@ -887,7 +853,7 @@ function buildChainedToOneOrderBy(qi, head, nextRelName, nextValue, params) {
887
853
  for (;;) {
888
854
  if (!currentMeta)
889
855
  throw new errors_js_1.RelationError(`Unknown relation target in orderBy chain "${path.join('.')}"`);
890
- const relDef = (0, utils_js_1.ownLookup)(currentMeta.relations, relName);
856
+ const relDef = (0, query_utils_js_1.ownLookup)(currentMeta.relations, relName);
891
857
  if (!relDef) {
892
858
  throw new errors_js_1.ValidationError(`Unknown relation "${relName}" in orderBy on relation "${path.join('.')}" ` +
893
859
  `(table "${currentMeta.name}"). Available: ${Object.keys(currentMeta.relations).join(', ') || '(none)'}.`);
@@ -927,14 +893,14 @@ function buildChainedToOneOrderBy(qi, head, nextRelName, nextValue, params) {
927
893
  // Resolved, so a chained orderBy descends through the snake_case spelling
928
894
  // of a relation exactly as `with` does; `relName` carries the DECLARED
929
895
  // name onward so the path reported in errors is the canonical one.
930
- const chained = (0, utils_js_1.resolveRelation)(currentMeta.relations, key);
896
+ const chained = (0, query_utils_js_1.resolveRelation)(currentMeta.relations, key);
931
897
  if (chained && isRelationOrderByValue(qi, entryValue)) {
932
898
  relName = chained.name;
933
899
  value = entryValue;
934
900
  continue;
935
901
  }
936
902
  // Terminal: a column on the last table in the chain.
937
- const snakeCol = (0, utils_js_1.resolveColumnName)(currentMeta, key);
903
+ const snakeCol = (0, query_utils_js_1.resolveColumnName)(currentMeta, key);
938
904
  if (snakeCol === undefined) {
939
905
  throw new errors_js_1.ValidationError(`Unknown column "${key}" in orderBy on relation "${path.join('.')}" (table "${currentMeta.name}").`);
940
906
  }
@@ -972,7 +938,7 @@ function buildRelationOrderBy(qi, relName, value, alias, params, ctx, lateralSin
972
938
  const parentRef = ctx?.parentRef ?? qi.table;
973
939
  // Resolved, then `relName` is rebound to the declared spelling so the alias
974
940
  // and every message below use one name.
975
- const resolvedOwner = (0, utils_js_1.resolveRelation)(ownerMeta.relations, relName);
941
+ const resolvedOwner = (0, query_utils_js_1.resolveRelation)(ownerMeta.relations, relName);
976
942
  if (resolvedOwner)
977
943
  relName = resolvedOwner.name;
978
944
  const relDef = resolvedOwner?.def;
@@ -982,16 +948,16 @@ function buildRelationOrderBy(qi, relName, value, alias, params, ctx, lateralSin
982
948
  // landing here on such a table is an orderBy VALUE of the wrong shape on a
983
949
  // scalar column, which deserves to be named rather than reported as a
984
950
  // missing relation.
985
- const isColumn = (0, utils_js_1.resolveColumnName)(ownerMeta, relName) !== undefined;
951
+ const isColumn = (0, query_utils_js_1.resolveColumnName)(ownerMeta, relName) !== undefined;
986
952
  throw new errors_js_1.RelationError(isColumn
987
953
  ? `orderBy on "${ownerTable}.${relName}" got a relation-shaped value, but "${relName}" is a ` +
988
954
  `column. Order a column with 'asc' / 'desc' (or { sort, nulls }); the object form is for relations.`
989
955
  : `Unknown relation "${relName}" in orderBy on table "${ownerTable}". ` +
990
- (0, utils_js_1.availableClause)(Object.keys(ownerMeta.relations), `"${ownerTable}" has no relations.`));
956
+ (0, query_utils_js_1.availableClause)(Object.keys(ownerMeta.relations), `"${ownerTable}" has no relations.`));
991
957
  }
992
958
  // Pick-row ordering (`{ pick, by }`): order by a value from ONE related
993
959
  // row: a correlated scalar subquery with its own ORDER BY … LIMIT 1.
994
- // Top-level findMany only (`ctx` present means we are inside a relation
960
+ // Top-level findMany only (`ctx` present means this is inside a relation
995
961
  // subquery's orderBy) and hasMany only: validatePickOrderBy throws the
996
962
  // scope errors, shared with the cache-hit collect mirror.
997
963
  if ((0, filters_js_1.isRelationPickOrderBy)(value)) {
@@ -1029,15 +995,15 @@ function buildRelationOrderBy(qi, relName, value, alias, params, ctx, lateralSin
1029
995
  // Each further to-one hop becomes a JOIN inside the SAME correlated
1030
996
  // subquery rather than another level of nesting, so an N-hop chain still
1031
997
  // costs one subquery.
1032
- const nestedRel = (0, utils_js_1.ownLookup)(targetMeta.relations, col);
998
+ const nestedRel = (0, query_utils_js_1.ownLookup)(targetMeta.relations, col);
1033
999
  if (nestedRel && isRelationOrderByValue(qi, dirValue)) {
1034
1000
  return buildChainedToOneOrderBy(qi, { relName, relDef, alias, correlation }, col, dirValue, params);
1035
1001
  }
1036
1002
  // The ONE key-resolution rule ({@link resolveColumnName}), so a target
1037
1003
  // column resolves here exactly as it does in the top-level orderBy.
1038
- const snakeCol = (0, utils_js_1.resolveColumnName)(targetMeta, col);
1004
+ const snakeCol = (0, query_utils_js_1.resolveColumnName)(targetMeta, col);
1039
1005
  if (snakeCol === undefined) {
1040
- const relationHint = (0, utils_js_1.ownLookup)(targetMeta.relations, col)
1006
+ const relationHint = (0, query_utils_js_1.ownLookup)(targetMeta.relations, col)
1041
1007
  ? ` "${col}" is a relation on "${relDef.to}": order by one of ITS columns, e.g. ` +
1042
1008
  `{ ${relName}: { ${col}: { <column>: 'asc' } } }.`
1043
1009
  : '';
@@ -1317,37 +1283,38 @@ function buildRelationOrderClause(qi, targetTable, targetMeta, alias, orderEntri
1317
1283
  * column validation so a warmed cache can never skip it.
1318
1284
  */
1319
1285
  function collectRelationOrderParams(qi, targetTable, targetMeta, orderEntries, params) {
1320
- for (const [key, dirValue] of orderEntries) {
1321
- if ((0, filters_js_1.isVectorOrderBy)(dirValue)) {
1322
- throw new errors_js_1.ValidationError(`Vector distance ordering on "${key}" is only supported in a top-level findMany orderBy.`);
1286
+ collectOrderParams(qi, orderEntries, params, { meta: targetMeta, table: targetTable });
1287
+ }
1288
+ /** Shared root/relation cache-hit binding; nested-only refusals remain explicit. */
1289
+ function collectOrderParams(qi, entries, params, scope) {
1290
+ const meta = scope?.meta ?? qi.tableMeta;
1291
+ const table = scope?.table ?? qi.table;
1292
+ for (const [key, value] of entries) {
1293
+ if ((0, filters_js_1.isVectorOrderBy)(value)) {
1294
+ if (scope)
1295
+ throw new errors_js_1.ValidationError(`Vector distance ordering on "${key}" is only supported in a top-level findMany orderBy.`);
1296
+ const column = qi.toColumn(key);
1297
+ whereMod.vectorOperator(qi, key, column, value.distance.metric);
1298
+ whereMod.pushVectorParam(qi, key, column, value.distance.to, params);
1323
1299
  }
1324
- if ((0, filters_js_1.isJsonPathOrderBy)(dirValue)) {
1325
- validateJsonPathOrderBy(qi, targetTable, targetMeta, key, dirValue);
1326
- params.push(whereMod.jsonPathParam(qi, dirValue.path));
1327
- continue;
1300
+ else if ((0, filters_js_1.isJsonPathOrderBy)(value)) {
1301
+ validateJsonPathOrderBy(qi, table, meta, key, value);
1302
+ params.push(whereMod.jsonPathParam(qi, value.path));
1328
1303
  }
1329
- if (isRelationOrderByValue(qi, dirValue)) {
1330
- // Pick-row ordering is top-level-only: the build path throws the same
1331
- // E003 (buildRelationOrderBy with ctx set), so the mirror must too.
1332
- if ((0, filters_js_1.isRelationPickOrderBy)(dirValue)) {
1304
+ else if (isRelationOrderByValue(qi, value)) {
1305
+ if (scope && (0, filters_js_1.isRelationPickOrderBy)(value))
1333
1306
  throw pickOrderNestedError(qi, key);
1334
- }
1335
- // resolveRelationDef, as buildRelationOrderBy resolves it, so a relation
1336
- // written in its table spelling binds its params on a cache hit too.
1337
- const relDef = (0, utils_js_1.resolveRelationDef)(targetMeta.relations, key);
1338
- if (relDef && (relDef.type === 'hasMany' || relDef.type === 'manyToMany')) {
1339
- collectRelationCountParams(qi, relDef, params);
1340
- }
1341
- else if (relDef) {
1342
- collectToOneRelationOrderParams(qi, key, dirValue, params, {
1343
- meta: targetMeta,
1344
- table: targetTable,
1345
- parentRef: targetTable,
1346
- });
1347
- }
1348
- continue;
1307
+ const resolved = (0, query_utils_js_1.resolveRelation)(meta.relations, key);
1308
+ const def = resolved?.def;
1309
+ if (def && (0, filters_js_1.isRelationPickOrderBy)(value))
1310
+ collectRelationPickOrderParams(qi, resolved.name, def, value, params);
1311
+ else if (def && (def.type === 'hasMany' || def.type === 'manyToMany'))
1312
+ collectRelationCountParams(qi, def, params);
1313
+ else if (def)
1314
+ collectToOneRelationOrderParams(qi, key, value, params, scope ? { meta, table, parentRef: table } : undefined);
1349
1315
  }
1350
- resolveOrderByColumn(qi, targetTable, targetMeta, key);
1316
+ else if (scope)
1317
+ resolveOrderByColumn(qi, table, meta, key);
1351
1318
  }
1352
1319
  }
1353
1320
  /**
@@ -1528,12 +1495,27 @@ function parseScalarColumns(qi, row, table, meta, fromJson) {
1528
1495
  countObj[key.slice(COUNT_PREFIX.length)] = Number(parsed[key]);
1529
1496
  }
1530
1497
  if (countObj) {
1498
+ // Preserve the row and its descriptors. Copying it would read scalar
1499
+ // getters again, including accessors installed by inherited setters.
1531
1500
  for (const rel of Object.keys(countObj))
1532
1501
  delete parsed[`${COUNT_PREFIX}${rel}`];
1533
1502
  parsed._count = countObj;
1534
1503
  }
1535
1504
  return parsed;
1536
1505
  }
1506
+ /**
1507
+ * The warn-and-throw for a relation payload that could not be parsed as
1508
+ * JSON, shared by {@link parseRelationValue} and the object decode plan so
1509
+ * both report the same relation with the same cause chain.
1510
+ */
1511
+ function throwRelationPayloadError(qi, relName, err) {
1512
+ const log = whereMod.adviceLogger(qi);
1513
+ if (log && (0, warn_registry_js_1.shouldWarnOnce)(warn_registry_js_1.WARN_NS.relationParseFailure, `${qi.table}.${relName}`)) {
1514
+ (0, logger_js_1.logTo)(log, 'warn', `Relation "${relName}" on "${qi.table}" returned a payload that is not valid JSON. ` +
1515
+ `This is a bug; please report it with the emitted SQL.`, { code: 'relation-payload-json', table: qi.table, relation: relName });
1516
+ }
1517
+ throw new errors_js_1.InvariantError('relation-payload-json', `Relation "${relName}" on table "${qi.table}" returned a payload that could not be parsed as JSON.`, { cause: err });
1518
+ }
1537
1519
  /**
1538
1520
  * The relation half of {@link parseNestedRow}: one relation column's value
1539
1521
  * (never `undefined`, which the caller skips) as the parsed relation.
@@ -1550,18 +1532,9 @@ function parseRelationValue(qi, relName, relDef, rawValue) {
1550
1532
  // --- Non-empty values: full parse path ---
1551
1533
  if (typeof rawValue === 'string') {
1552
1534
  try {
1553
- const jsonVal = JSON.parse(rawValue);
1554
1535
  // After parsing, recurse via parseNestedRow so each item gets date
1555
1536
  // coercion AND its own sub-relations parsed at arbitrary depth.
1556
- if (Array.isArray(jsonVal)) {
1557
- return jsonVal.map((item) => typeof item === 'object' && item !== null
1558
- ? parseNestedRow(qi, item, relDef.to, true)
1559
- : item);
1560
- }
1561
- if (typeof jsonVal === 'object' && jsonVal !== null) {
1562
- return parseNestedRow(qi, jsonVal, relDef.to, true);
1563
- }
1564
- return jsonVal;
1537
+ return parseRelationObject(qi, relDef, JSON.parse(rawValue));
1565
1538
  }
1566
1539
  catch (err) {
1567
1540
  // A relation column that does not parse is a bug in the emitted SQL or
@@ -1575,14 +1548,13 @@ function parseRelationValue(qi, relName, relDef, rawValue) {
1575
1548
  // per-relation loop: one 10,000-row page was 10,000 warnings. The
1576
1549
  // parse error stays out of the entry: its message quotes the payload,
1577
1550
  // which is row data.
1578
- const log = whereMod.adviceLogger(qi);
1579
- if (log && (0, warn_registry_js_1.shouldWarnOnce)(warn_registry_js_1.WARN_NS.relationParseFailure, `${qi.table}.${relName}`)) {
1580
- (0, logger_js_1.logTo)(log, 'warn', `Relation "${relName}" on "${qi.table}" returned a payload that is not valid JSON. ` +
1581
- `This is a bug; please report it with the emitted SQL.`, { code: 'relation-payload-json', table: qi.table, relation: relName });
1582
- }
1583
- throw new errors_js_1.InvariantError('relation-payload-json', `Relation "${relName}" on table "${qi.table}" returned a payload that could not be parsed as JSON.`, { cause: err });
1551
+ throwRelationPayloadError(qi, relName, err);
1584
1552
  }
1585
1553
  }
1554
+ return parseRelationObject(qi, relDef, rawValue);
1555
+ }
1556
+ /** The same nested-object walk for driver-decoded JSON and JSON text. */
1557
+ function parseRelationObject(qi, relDef, rawValue) {
1586
1558
  if (Array.isArray(rawValue)) {
1587
1559
  return rawValue.map((item) => typeof item === 'object' && item !== null
1588
1560
  ? parseNestedRow(qi, item, relDef.to, true)
@@ -1741,7 +1713,7 @@ function buildRelationShapes(qi, table, withClause, includePii) {
1741
1713
  return {};
1742
1714
  const shapes = {};
1743
1715
  for (const [relName, relSpec] of (0, filters_js_1.sortedEntries)(withClause)) {
1744
- const relDef = (0, utils_js_1.ownLookup)(meta.relations, relName);
1716
+ const relDef = (0, query_utils_js_1.ownLookup)(meta.relations, relName);
1745
1717
  if (!relDef)
1746
1718
  continue; // buildSelectWithRelations already threw for this
1747
1719
  shapes[relName] = buildRelationShape(qi, relDef, relSpec, meta, includePii);
@@ -1765,7 +1737,7 @@ function buildRelationShape(qi, relDef, spec, parentMeta, includePii) {
1765
1737
  const nestedWith = relationOptions(spec).with;
1766
1738
  if (nestedWith) {
1767
1739
  for (const [nestedRelName, nestedSpec] of (0, filters_js_1.sortedEntries)(nestedWith)) {
1768
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
1740
+ const nestedRelDef = (0, query_utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
1769
1741
  if (!nestedRelDef)
1770
1742
  continue;
1771
1743
  keys.push(nestedRelName);
@@ -1776,13 +1748,13 @@ function buildRelationShape(qi, relDef, spec, parentMeta, includePii) {
1776
1748
  return { keys, nested, cardinality };
1777
1749
  }
1778
1750
  /**
1779
- * Build the row parser for a `with` clause. In object mode this is just
1780
- * {@link parseNestedRow}. In positional mode the relation shapes are built
1781
- * once (not per row) and compiled into a decode plan
1782
- * ({@link makePositionalRowParser}) that turns each positional array straight
1783
- * into its parsed row. A query whose shapes the plan declines takes the
1784
- * reference path instead, which decodes each positional array into the object
1785
- * form and hands it to parseNestedRow.
1751
+ * Build the row parser for a `with` clause. The relation shapes are built
1752
+ * once per query (not per row) and compiled into a decode plan: in positional mode
1753
+ * {@link makePositionalRowParser} turns each positional array straight into
1754
+ * its parsed row, in object mode {@link makeObjectRowParser} does the same
1755
+ * for each keyed JSON object. A query whose shapes the plan declines takes
1756
+ * the reference path instead ({@link parseNestedRow}, in positional mode
1757
+ * after decoding each array into the object form).
1786
1758
  */
1787
1759
  function makeNestedParser(qi, withClause, includePii, flattenPlan) {
1788
1760
  // A flatten plan and the positional encoding are mutually exclusive (the
@@ -1791,7 +1763,34 @@ function makeNestedParser(qi, withClause, includePii, flattenPlan) {
1791
1763
  if (flattenPlan)
1792
1764
  return makeFlattenParser(qi, flattenPlan);
1793
1765
  if (qi.jsonEncoding !== 'positional') {
1794
- return (row) => parseNestedRow(qi, row, qi.table);
1766
+ // The plan reads a row by position, so it is only worth building where
1767
+ // the engine returns a JSON object's keys in the order the statement
1768
+ // wrote them. MySQL sorts them: every row would fall back to the walker,
1769
+ // and the plan would be built for each query and never used.
1770
+ if (!qi.dialect.capabilities.jsonObjectKeysAsWritten)
1771
+ return (row) => parseNestedRow(qi, row, qi.table);
1772
+ // Built lazily, on the first row actually decoded, never here: this
1773
+ // parser can be constructed before its statement exists (the stream
1774
+ // paths build it first), and the statement build owns validation and
1775
+ // diagnostic ordering. Shape building can throw the same validation
1776
+ // errors, so constructing eagerly would surface them ahead of that
1777
+ // ordering and skip its warnings. If construction fails for any
1778
+ // reason the query decodes through the reference; plan
1779
+ // construction surfaces no error and no log line of its own.
1780
+ let parser;
1781
+ return (row) => {
1782
+ if (parser === undefined) {
1783
+ parser = (r) => parseNestedRow(qi, r, qi.table);
1784
+ try {
1785
+ parser =
1786
+ makeObjectRowParser(qi, qi.table, buildRelationShapes(qi, qi.table, withClause, includePii)) ?? parser;
1787
+ }
1788
+ catch {
1789
+ // The reference parser above stays in place for this query.
1790
+ }
1791
+ }
1792
+ return parser(row);
1793
+ };
1795
1794
  }
1796
1795
  const shapes = buildRelationShapes(qi, qi.table, withClause, includePii);
1797
1796
  return makePositionalRowParser(qi, qi.table, shapes) ?? makeReferencePositionalParser(qi, shapes);
@@ -1921,10 +1920,10 @@ function planPositionalRow(qi, table, shape) {
1921
1920
  return undefined;
1922
1921
  const nested = shape.nested[key];
1923
1922
  if (nested) {
1924
- const def = (0, utils_js_1.ownLookup)(meta.relations, key);
1923
+ const def = (0, query_utils_js_1.ownLookup)(meta.relations, key);
1925
1924
  // The reference copies the slot through parseRow before replacing it, so
1926
1925
  // the slot must be a plain cell under its own name, and no wire field.
1927
- if (!def || field !== key || kind !== utils_js_1.CELL_PLAIN || wireFields?.has(key))
1926
+ if (!def || field !== key || kind !== query_utils_js_1.CELL_PLAIN || wireFields?.has(key))
1928
1927
  return undefined;
1929
1928
  const row = planPositionalRow(qi, def.to, nested);
1930
1929
  if (!row)
@@ -1947,7 +1946,7 @@ function planPositionalRow(qi, table, shape) {
1947
1946
  }
1948
1947
  fields.push(field);
1949
1948
  wire.push(rule);
1950
- if (kind !== utils_js_1.CELL_PLAIN) {
1949
+ if (kind !== query_utils_js_1.CELL_PLAIN) {
1951
1950
  cellPositions.push(i);
1952
1951
  cellKinds.push(kind);
1953
1952
  }
@@ -1959,6 +1958,7 @@ function planPositionalRow(qi, table, shape) {
1959
1958
  return undefined;
1960
1959
  return {
1961
1960
  table,
1961
+ keys,
1962
1962
  fields,
1963
1963
  wire,
1964
1964
  cellPositions,
@@ -1974,47 +1974,62 @@ function planPositionalRow(qi, table, shape) {
1974
1974
  * reference's on every shape it does take.
1975
1975
  */
1976
1976
  function makePositionalRowParser(qi, table, shapes) {
1977
+ return makeTopRowParser(qi, table, shapes, false);
1978
+ }
1979
+ /**
1980
+ * The top-level planned parser both encodings share: the row's scalar half
1981
+ * through {@link parseScalarColumns} exactly as the reference runs it, then
1982
+ * each relation column replaced by its planned decode (or the reference's
1983
+ * {@link parseRelationValue} for a relation the `with` clause did not plan).
1984
+ * The encodings differ in three places, all keyed on `objectMode`: the
1985
+ * positional reference reads relation columns off a `{ ...row }` copy (own
1986
+ * enumerable only) with them already decoded, so it needs the plain-name and
1987
+ * column-collision declines below and decodes a present-but-`undefined`
1988
+ * slot, where the object reference reads the row directly and skips
1989
+ * `undefined`. An object
1990
+ * query with no planned relation at all (a bare `_count`) declines, where
1991
+ * the positional one still has decoding of its own to do.
1992
+ */
1993
+ function makeTopRowParser(qi, table, shapes, objectMode) {
1977
1994
  const meta = qi.schema.tables[table];
1978
1995
  if (!meta || !qi.rowDecodePlan || !qi.decodeCell)
1979
1996
  return undefined;
1980
1997
  const entries = getRelationEntries(qi, table, meta);
1981
- if (!entries.every(([name]) => isPlainKey(name)))
1998
+ if (!objectMode && !entries.every(([name]) => isPlainKey(name)))
1982
1999
  return undefined;
1983
2000
  const plans = [];
2001
+ let planned = false;
1984
2002
  for (const [name, def] of entries) {
1985
2003
  const shape = Object.hasOwn(shapes, name) ? shapes[name] : undefined;
1986
2004
  if (!shape) {
1987
2005
  plans.push(null);
1988
2006
  continue;
1989
2007
  }
1990
- // The reference runs the top-level row through parseRow with the relation
1991
- // columns already decoded; the plan runs it with them raw and replaces them
1992
- // after. Those agree only while parseRow copies a relation column through
1993
- // untouched, under its own name, and the `_count` fold never reads it.
1994
- if (name.startsWith(COUNT_PREFIX) || nameTouchesColumns(qi, table, meta, name))
2008
+ if (!objectMode && (name.startsWith(COUNT_PREFIX) || nameTouchesColumns(qi, table, meta, name)))
1995
2009
  return undefined;
1996
2010
  const row = planPositionalRow(qi, def.to, shape);
1997
2011
  if (!row)
1998
2012
  return undefined;
1999
2013
  plans.push({ name, def, many: shape.cardinality === 'many', position: -1, row });
2014
+ planned = true;
2000
2015
  }
2016
+ if (objectMode && !planned)
2017
+ return undefined;
2001
2018
  const isOwnEnumerable = Object.prototype.propertyIsEnumerable;
2002
2019
  return (row) => {
2003
2020
  const parsed = parseScalarColumns(qi, row, table, meta, false);
2004
2021
  for (let i = 0; i < entries.length; i++) {
2005
2022
  const [name, def] = entries[i];
2006
- // The reference reads relation columns off a `{ ...row }` copy, which
2007
- // holds exactly the row's own enumerable properties.
2008
- if (!isOwnEnumerable.call(row, name))
2023
+ if (objectMode ? row[name] === undefined : !isOwnEnumerable.call(row, name))
2009
2024
  continue;
2010
2025
  const plan = plans[i];
2026
+ const raw = row[name];
2011
2027
  if (plan !== null) {
2012
- parsed[name] = decodePlannedRelation(qi, row[name], plan);
2013
- continue;
2028
+ parsed[name] = objectMode ? decodeObjectRelation(qi, raw, plan) : decodePlannedRelation(qi, raw, plan);
2014
2029
  }
2015
- const raw = row[name];
2016
- if (raw !== undefined)
2030
+ else if (raw !== undefined) {
2017
2031
  parsed[name] = parseRelationValue(qi, name, def, raw);
2032
+ }
2018
2033
  }
2019
2034
  return parsed;
2020
2035
  };
@@ -2059,6 +2074,16 @@ function decodePlannedRelation(qi, raw, rel) {
2059
2074
  }
2060
2075
  /** One positional array through its row plan, into the parsed row. */
2061
2076
  function decodePlannedRow(qi, arr, plan) {
2077
+ return decodePlannedRowWith(qi, arr, plan, decodePlannedRelation);
2078
+ }
2079
+ /**
2080
+ * The planned row write both decoders share: scalars and cell decodes from a
2081
+ * values array in shape order (a positional array as it arrived, or
2082
+ * `Object.values` of a keyed row whose keys were verified to be in shape
2083
+ * order), then relation slots through the caller's relation decoder, which
2084
+ * is where the two encodings' value semantics differ.
2085
+ */
2086
+ function decodePlannedRowWith(qi, arr, plan, decodeRelation) {
2062
2087
  const out = {};
2063
2088
  const { fields, wire, cellPositions, cellKinds, relations, table } = plan;
2064
2089
  for (let i = 0; i < fields.length; i++) {
@@ -2076,7 +2101,7 @@ function decodePlannedRow(qi, arr, plan) {
2076
2101
  const kind = cellKinds[c];
2077
2102
  const value = out[field];
2078
2103
  // parseRow's own skip: a float the driver already made a number.
2079
- if (kind === utils_js_1.CELL_FLOAT && typeof value !== 'string')
2104
+ if (kind === query_utils_js_1.CELL_FLOAT && typeof value !== 'string')
2080
2105
  continue;
2081
2106
  out[field] = decodeCell(kind, value, table, field);
2082
2107
  }
@@ -2085,7 +2110,7 @@ function decodePlannedRow(qi, arr, plan) {
2085
2110
  const order = plan.relationOrder;
2086
2111
  if (order === null) {
2087
2112
  for (const rel of relations)
2088
- out[rel.name] = decodePlannedRelation(qi, arr[rel.position], rel);
2113
+ out[rel.name] = decodeRelation(qi, arr[rel.position], rel);
2089
2114
  }
2090
2115
  else {
2091
2116
  // Claim the keys in key order first, then decode in the reference's order.
@@ -2093,13 +2118,110 @@ function decodePlannedRow(qi, arr, plan) {
2093
2118
  out[rel.name] = undefined;
2094
2119
  for (const index of order) {
2095
2120
  const rel = relations[index];
2096
- out[rel.name] = decodePlannedRelation(qi, arr[rel.position], rel);
2121
+ out[rel.name] = decodeRelation(qi, arr[rel.position], rel);
2097
2122
  }
2098
2123
  }
2099
2124
  }
2100
2125
  return out;
2101
2126
  }
2102
2127
  // ---------------------------------------------------------------------------
2128
+ // Object decode plan: one pass from a keyed JSON object to its parsed row
2129
+ //
2130
+ // The same plan the positional decoder runs, read by key instead of by
2131
+ // position. It is held to {@link parseNestedRow} the way the positional plan
2132
+ // is held to its reference: field names, cell kinds and wire rules come from
2133
+ // the shared {@link PositionalRowPlan} (so every decline check in
2134
+ // `planPositionalRow` applies here too), cell decodes go through
2135
+ // `qi.decodeCell`, and the work runs in the reference's order. One thing
2136
+ // differs from the positional decoder: a keyed row's own key order is not
2137
+ // guaranteed to be the shape's (MySQL sorts JSON object keys by length then
2138
+ // bytes, and a caller-supplied JSON type parser can reorder freely), and
2139
+ // the reference decodes cells in the order the row carries them, which is
2140
+ // observable through the logger. The plan therefore decodes only a row
2141
+ // whose keys are exactly the shape's keys in shape order; any other row
2142
+ // (permuted, a missing or extra key, a `_count__` field, a relation the
2143
+ // `with` clause did not ask for) falls back to `parseNestedRow`, decided
2144
+ // before any cell decode runs, so the fallback decodes exactly once. A
2145
+ // permuted row also marks its plan node (see `PositionalRowPlan.unordered`)
2146
+ // so an engine that never emits shape order pays the comparison once per
2147
+ // shape per result, not once per row.
2148
+ // ---------------------------------------------------------------------------
2149
+ /**
2150
+ * Compile a top-level object parser for `shapes` (see `makeTopRowParser`),
2151
+ * or `undefined` when a shape is declined or nothing is planned.
2152
+ */
2153
+ function makeObjectRowParser(qi, table, shapes) {
2154
+ return makeTopRowParser(qi, table, shapes, true);
2155
+ }
2156
+ /**
2157
+ * One relation value through the object plan: exactly what the reference
2158
+ * produces by {@link parseRelationValue}. The shortcuts and the dispatch on
2159
+ * the value's type are the reference's; only the per-row walk is planned.
2160
+ */
2161
+ function decodeObjectRelation(qi, raw, rel) {
2162
+ if (raw === null || raw === 'null')
2163
+ return null;
2164
+ if (raw === '[]')
2165
+ return [];
2166
+ if (Array.isArray(raw) && raw.length === 0)
2167
+ return [];
2168
+ let value = raw;
2169
+ let wrapped = false;
2170
+ if (typeof raw === 'string') {
2171
+ try {
2172
+ value = JSON.parse(raw);
2173
+ }
2174
+ catch (err) {
2175
+ throwRelationPayloadError(qi, rel.name, err);
2176
+ }
2177
+ wrapped = true;
2178
+ }
2179
+ // The reference parses AND decodes a string payload inside one try, so a
2180
+ // failure deep in it is re-reported against THIS relation, with the inner
2181
+ // failure as its cause. The `wrapped` catch mirrors that exactly.
2182
+ try {
2183
+ if (Array.isArray(value)) {
2184
+ const out = [];
2185
+ for (let i = 0; i < value.length; i++) {
2186
+ const item = value[i];
2187
+ out.push(typeof item === 'object' && item !== null
2188
+ ? Array.isArray(item)
2189
+ ? parseNestedRow(qi, item, rel.def.to, true)
2190
+ : decodeObjectRow(qi, item, rel.row)
2191
+ : item);
2192
+ }
2193
+ return out;
2194
+ }
2195
+ if (typeof value === 'object' && value !== null) {
2196
+ return decodeObjectRow(qi, value, rel.row);
2197
+ }
2198
+ return value;
2199
+ }
2200
+ catch (err) {
2201
+ if (wrapped)
2202
+ throwRelationPayloadError(qi, rel.name, err);
2203
+ throw err;
2204
+ }
2205
+ }
2206
+ /** One keyed JSON object through its row plan, into the parsed row. */
2207
+ function decodeObjectRow(qi, row, plan) {
2208
+ const { keys, table } = plan;
2209
+ if (plan.unordered)
2210
+ return parseNestedRow(qi, row, table, true);
2211
+ const rowKeys = Object.keys(row);
2212
+ if (rowKeys.length !== keys.length)
2213
+ return parseNestedRow(qi, row, table, true);
2214
+ for (let i = 0; i < keys.length; i++) {
2215
+ if (rowKeys[i] !== keys[i]) {
2216
+ plan.unordered = true;
2217
+ return parseNestedRow(qi, row, table, true);
2218
+ }
2219
+ }
2220
+ // The compare above is what proves the row is in shape order, so nothing
2221
+ // is assumed; `Object.values` of such a row is its values in that order.
2222
+ return decodePlannedRowWith(qi, Object.values(row), plan, decodeObjectRelation);
2223
+ }
2224
+ // ---------------------------------------------------------------------------
2103
2225
  // relationLoadStrategy: 'flatten', to-one relations compiled as LEFT JOINs
2104
2226
  // ---------------------------------------------------------------------------
2105
2227
  /**
@@ -2198,19 +2320,7 @@ function provableUniqueTargetKey(relDef, targetMeta) {
2198
2320
  return null;
2199
2321
  if (!cols.every((col) => targetMeta.allColumns.includes(col)))
2200
2322
  return null;
2201
- if (sameColumnSet(cols, targetMeta.primaryKey))
2202
- return cols;
2203
- for (const unique of targetMeta.uniqueColumns) {
2204
- if (sameColumnSet(cols, unique))
2205
- return cols;
2206
- }
2207
- for (const idx of targetMeta.indexes) {
2208
- if (!idx.unique || idx.partial || idx.docPath)
2209
- continue;
2210
- if (sameColumnSet(cols, idx.columns))
2211
- return cols;
2212
- }
2213
- return null;
2323
+ return (0, compound_unique_js_1.uniqueKeyNames)(targetMeta).some((key) => sameColumnSet(cols, key)) ? cols : null;
2214
2324
  }
2215
2325
  /**
2216
2326
  * Plan one relation as a flattened LEFT JOIN, or return `null` to leave it on
@@ -2265,7 +2375,7 @@ function planFlattenNode(qi, counter, relName, relDef, spec, depth, path, includ
2265
2375
  for (const [nestedRelName] of nestedEntries) {
2266
2376
  if (nestedRelName === '_count')
2267
2377
  return decline('its nested `with` uses `_count`');
2268
- if (!(0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName)) {
2378
+ if (!(0, query_utils_js_1.ownLookup)(targetMeta.relations, nestedRelName)) {
2269
2379
  return decline(`its nested \`with\` names "${nestedRelName}", which is not a relation of "${relDef.to}"`);
2270
2380
  }
2271
2381
  }
@@ -2303,7 +2413,7 @@ function planFlattenNode(qi, counter, relName, relDef, spec, depth, path, includ
2303
2413
  return decline(`a projected column alias would exceed ${FLATTEN_MAX_ALIAS_LEN} characters`);
2304
2414
  }
2305
2415
  for (const [nestedRelName, nestedSpec] of nestedEntries) {
2306
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
2416
+ const nestedRelDef = (0, query_utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
2307
2417
  const child = planFlattenNode(qi, counter, nestedRelName, nestedRelDef, nestedSpec, depth + 1, [...path, relName], includePii, aliasSink, rejects);
2308
2418
  if (child) {
2309
2419
  node.slots.push({ relName: nestedRelName, kind: 'flat' });
@@ -2336,7 +2446,7 @@ function flattenNodeSignature(node) {
2336
2446
  *
2337
2447
  * Off when `diagnostics` turn advice off, like the other planner notes, and
2338
2448
  * deduped through the shared registry so a hot query logs once rather than per
2339
- * call. Note that a flatten plan is recomputed on the build, param-collect and
2449
+ * call. A flatten plan is recomputed on the build, param-collect and
2340
2450
  * row-assembly paths for the same query; the registry is what keeps that to
2341
2451
  * one line.
2342
2452
  */
@@ -2373,7 +2483,7 @@ function planFlattenWith(qi, table, withClause, includePii) {
2373
2483
  for (const [relName, relSpec] of (0, filters_js_1.sortedEntries)(withClause)) {
2374
2484
  if (relName === '_count')
2375
2485
  continue;
2376
- const relDef = (0, utils_js_1.ownLookup)(meta.relations, relName);
2486
+ const relDef = (0, query_utils_js_1.ownLookup)(meta.relations, relName);
2377
2487
  // An unknown relation stays on the subquery path so it raises E005 there.
2378
2488
  if (!relDef)
2379
2489
  continue;
@@ -2503,7 +2613,7 @@ function emitFlattenInner(qi, node, params, innerSelects, innerJoins, innerWhere
2503
2613
  innerJoins[at] = ` LEFT JOIN ${qi.q(child.targetTable)} ${child.srcAlias} ON ${conds}`;
2504
2614
  continue;
2505
2615
  }
2506
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, slot.relName);
2616
+ const nestedRelDef = (0, query_utils_js_1.ownLookup)(targetMeta.relations, slot.relName);
2507
2617
  const nestedSpec = node.spec.with[slot.relName];
2508
2618
  const sub = buildRelationSubquery(qi, nestedRelDef, nestedSpec, params, srcAlias, aliasCounter, node.depth + 1, [...node.path, node.relName], includePii);
2509
2619
  // Same fallback the subquery path picks for a nested relation slot.
@@ -2542,7 +2652,7 @@ function collectFlattenNodeParams(qi, node, params) {
2542
2652
  collectFlattenNodeParams(qi, node.children[slot.relName], params);
2543
2653
  continue;
2544
2654
  }
2545
- const nestedRelDef = (0, utils_js_1.ownLookup)(node.targetMeta.relations, slot.relName);
2655
+ const nestedRelDef = (0, query_utils_js_1.ownLookup)(node.targetMeta.relations, slot.relName);
2546
2656
  if (!nestedRelDef)
2547
2657
  continue;
2548
2658
  const nestedSpec = node.spec.with[slot.relName];
@@ -2674,17 +2784,17 @@ function buildSelectWithRelations(qi, table, withClause, params, columnsList, de
2674
2784
  }
2675
2785
  const cols = columnsList ?? meta.allColumns;
2676
2786
  const qtbl = qi.q(table);
2677
- const baseCols = cols.map((col) => `${qtbl}.${qi.q(col)}`).join(', ');
2787
+ const baseCols = qualifiedColumns(qi, cols, qtbl);
2678
2788
  const relationSelects = [];
2679
2789
  const aliasCounter = { n: 0 };
2680
2790
  for (const [relName, relSpec] of (0, filters_js_1.sortedEntries)(withClause)) {
2681
2791
  // `_count` is a reserved key handled after the relation subqueries.
2682
2792
  if (relName === '_count')
2683
2793
  continue;
2684
- const relDef = (0, utils_js_1.ownLookup)(meta.relations, relName);
2794
+ const relDef = (0, query_utils_js_1.ownLookup)(meta.relations, relName);
2685
2795
  if (!relDef) {
2686
2796
  throw new errors_js_1.RelationError(`Unknown relation "${relName}" on table "${table}". ` +
2687
- (0, utils_js_1.availableClause)(Object.keys(meta.relations), `"${table}" has no relations.`));
2797
+ (0, query_utils_js_1.availableClause)(Object.keys(meta.relations), `"${table}" has no relations.`));
2688
2798
  }
2689
2799
  // `relationLoadStrategy: 'flatten'`: an eligible to-one relation becomes a
2690
2800
  // LEFT JOIN + prefixed scalar projection instead of a per-parent-row
@@ -2712,6 +2822,21 @@ function buildSelectWithRelations(qi, table, withClause, params, columnsList, de
2712
2822
  }
2713
2823
  return [baseCols, ...relationSelects].join(', ');
2714
2824
  }
2825
+ /** Append nested JSON slots at the caller's existing parameter position. */
2826
+ function appendNestedJson(qi, pairs, relDef, targetMeta, withClause, params, parentAlias, aliasCounter, depth, path, includePii, manyFallback = false) {
2827
+ if (!withClause)
2828
+ return;
2829
+ for (const [name, spec] of (0, filters_js_1.sortedEntries)(withClause)) {
2830
+ const nested = (0, query_utils_js_1.ownLookup)(targetMeta.relations, name);
2831
+ if (!nested)
2832
+ throw new errors_js_1.RelationError(`Unknown relation "${name}" on table "${relDef.to}". ` +
2833
+ (0, query_utils_js_1.availableClause)(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
2834
+ const subquery = buildRelationSubquery(qi, nested, spec, params, parentAlias, aliasCounter, depth + 1, [...path, relDef.name], includePii);
2835
+ const array = manyFallback ? nested.type !== 'belongsTo' && nested.type !== 'hasOne' : nested.type === 'hasMany';
2836
+ const fallback = array ? qi.dialect.emptyJsonArrayLiteral : qi.dialect.nullJsonLiteral;
2837
+ pairs.push([name, qi.dialect.wrapJsonSubresult(subquery, fallback)]);
2838
+ }
2839
+ }
2715
2840
  /**
2716
2841
  * Generate a correlated subquery that returns JSON for a single relation.
2717
2842
  *
@@ -2832,7 +2957,7 @@ function buildRelationSubquery(qi, relDef, spec, params, parentRef, aliasCounter
2832
2957
  if (log) {
2833
2958
  const warnKey = `${relDef.from}.${relDef.name}`;
2834
2959
  // Compute the (potentially costly) probe only for a key not yet warned, and
2835
- // claim the key through the process-wide registry ONLY when we actually warn,
2960
+ // claim the key through the process-wide registry ONLY when emitting a warning,
2836
2961
  // so a dual-package / HMR-reevaluated second module copy cannot re-warn the
2837
2962
  // same relation, and indexed relations never consume the dedupe cap.
2838
2963
  if (!(0, warn_registry_js_1.hasWarnedOnce)(warn_registry_js_1.WARN_NS.unindexedRelation, warnKey)) {
@@ -2912,7 +3037,7 @@ function buildRelationSubquery(qi, relDef, spec, params, parentRef, aliasCounter
2912
3037
  const jsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, alias);
2913
3038
  // Determine if this hasMany will take the wrapped subquery path (LIMIT or ORDER BY).
2914
3039
  // When wrapping, nested relations are built in the wrapped path referencing innerAlias,
2915
- // so we must NOT build them here (they would push orphaned params).
3040
+ // so do NOT build them here (they would push orphaned params).
2916
3041
  // An orderBy with no defined entries (`orderBy: {}`) is treated as absent -
2917
3042
  // it must neither trigger the wrap (dropping nested relations) nor render a
2918
3043
  // dangling `ORDER BY `. `limit: 0` is meaningful (LIMIT 0) and DOES wrap.
@@ -2925,21 +3050,10 @@ function buildRelationSubquery(qi, relDef, spec, params, parentRef, aliasCounter
2925
3050
  if (relDef.type === 'manyToMany') {
2926
3051
  return buildManyToManySubquery(qi, relDef, spec, params, parentRef, aliasCounter, currentDepth, currentPath, alias, targetMeta, targetColumns, includePii);
2927
3052
  }
2928
- // Nested relations, only in the non-wrapped path (wrapped path builds them separately)
2929
- if (!willWrap && opts.with) {
2930
- for (const [nestedRelName, nestedSpec] of (0, filters_js_1.sortedEntries)(opts.with)) {
2931
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
2932
- if (!nestedRelDef) {
2933
- throw new errors_js_1.RelationError(`Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
2934
- (0, utils_js_1.availableClause)(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
2935
- }
2936
- // Recursively build nested subquery, passing THIS alias as the parent reference
2937
- const nestedSubquery = buildRelationSubquery(qi, nestedRelDef, nestedSpec, params, alias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name], includePii);
2938
- // Use '[]'::json for hasMany (empty array), NULL for belongsTo/hasOne (no object)
2939
- const fallback = nestedRelDef.type === 'hasMany' ? qi.dialect.emptyJsonArrayLiteral : qi.dialect.nullJsonLiteral;
2940
- jsonPairs.push([nestedRelName, qi.dialect.wrapJsonSubresult(nestedSubquery, fallback)]);
2941
- }
2942
- }
3053
+ // The two SELECT levels differ only in their row alias. Invoke at the
3054
+ // original bind position so nested WHERE params stay before or after paging.
3055
+ if (!willWrap)
3056
+ appendNestedJson(qi, jsonPairs, relDef, targetMeta, opts.with, params, alias, aliasCounter, currentDepth, currentPath, includePii);
2943
3057
  const jsonObj = buildJsonRow(qi, jsonPairs);
2944
3058
  // Quote parent ref, can be a table name or auto-generated alias
2945
3059
  const qParent = qi.q(parentRef);
@@ -2996,22 +3110,10 @@ function buildRelationSubquery(qi, relDef, spec, params, parentRef, aliasCounter
2996
3110
  const innerAlias = `${alias}i`;
2997
3111
  // Rewrite: SELECT json_agg(json_build_object(...)) FROM (SELECT * FROM table WHERE ... ORDER BY ... LIMIT N) AS alias
2998
3112
  // Inner SELECT always needs all columns for WHERE/ORDER to work; json_build_object filters later
2999
- const innerSql = `SELECT ${targetMeta.allColumns.map((c) => `${alias}.${qi.q(c)}`).join(', ')} FROM ${qTarget} ${alias} WHERE ${whereClause}${orderClause}${limitClause}`;
3113
+ const innerSql = `SELECT ${qualifiedColumns(qi, targetMeta.allColumns, alias)} FROM ${qTarget} ${alias} WHERE ${whereClause}${orderClause}${limitClause}`;
3000
3114
  // For the json_build_object, reference the inner alias, only include resolved columns
3001
3115
  const innerJsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, innerAlias);
3002
- // Build nested relation subqueries referencing innerAlias
3003
- if (opts.with) {
3004
- for (const [nestedRelName, nestedSpec] of (0, filters_js_1.sortedEntries)(opts.with)) {
3005
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
3006
- if (!nestedRelDef) {
3007
- throw new errors_js_1.RelationError(`Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
3008
- (0, utils_js_1.availableClause)(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
3009
- }
3010
- const nestedSub = buildRelationSubquery(qi, nestedRelDef, nestedSpec, params, innerAlias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name], includePii);
3011
- const fallback = nestedRelDef.type === 'hasMany' ? qi.dialect.emptyJsonArrayLiteral : qi.dialect.nullJsonLiteral;
3012
- innerJsonPairs.push([nestedRelName, qi.dialect.wrapJsonSubresult(nestedSub, fallback)]);
3013
- }
3014
- }
3116
+ appendNestedJson(qi, innerJsonPairs, relDef, targetMeta, opts.with, params, innerAlias, aliasCounter, currentDepth, currentPath, includePii);
3015
3117
  const innerJsonObj = buildJsonRow(qi, innerJsonPairs);
3016
3118
  return `SELECT ${qi.dialect.buildJsonArrayAgg(innerJsonObj)} FROM (${innerSql}) ${innerAlias}`;
3017
3119
  }
@@ -3061,7 +3163,7 @@ function buildManyToManySubquery(qi, relDef, spec, params, parentRef, aliasCount
3061
3163
  // JOIN: junction.targetKey = target.<targetPK>. Composite keys pair positionally.
3062
3164
  const targetKeys = (0, schema_js_1.normalizeKeyColumns)(relDef.through.targetKey);
3063
3165
  // The target PK is the column(s) the junction's targetKey references. An empty
3064
- // introspected PK means we cannot know what to JOIN on, fail loudly rather than
3166
+ // introspected PK leaves no known JOIN column: fail loudly rather than
3065
3167
  // silently guessing `id` and generating a wrong JOIN.
3066
3168
  if (targetMeta.primaryKey.length === 0) {
3067
3169
  throw new errors_js_1.ValidationError(`manyToMany relation "${relDef.name}" targets table "${targetTable}" which has no primary key; ` +
@@ -3108,48 +3210,15 @@ function buildManyToManySubquery(qi, relDef, spec, params, parentRef, aliasCount
3108
3210
  // LIMIT / OFFSET, `limit: 0` is honored (LIMIT 0 → empty array)
3109
3211
  const limitClause = relationPagination(qi, opts.limit, relationOffset(opts), params, relOrderEntries.length > 0);
3110
3212
  const fromJoin = `FROM ${qTarget} ${talias} JOIN ${qJunction} ${jalias} ON ${joinOn}`;
3111
- // When LIMIT or ORDER BY is present, wrap the joined rows in an inner subquery
3112
- // so the LIMIT applies to rows BEFORE aggregation (same approach as hasMany).
3113
- if (limitClause || orderClause) {
3114
- const innerAlias = `${talias}i`;
3115
- const innerSql = `SELECT ${targetMeta.allColumns.map((c) => `${talias}.${qi.q(c)}`).join(', ')} ` +
3116
- `${fromJoin} WHERE ${whereClause}${orderClause}${limitClause}`;
3117
- const innerJsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, innerAlias);
3118
- // Nested relations reference the inner alias.
3119
- if (opts.with) {
3120
- for (const [nestedRelName, nestedSpec] of (0, filters_js_1.sortedEntries)(opts.with)) {
3121
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
3122
- if (!nestedRelDef) {
3123
- throw new errors_js_1.RelationError(`Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
3124
- (0, utils_js_1.availableClause)(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
3125
- }
3126
- const nestedSub = buildRelationSubquery(qi, nestedRelDef, nestedSpec, params, innerAlias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name], includePii);
3127
- const fallback = nestedRelDef.type === 'belongsTo' || nestedRelDef.type === 'hasOne'
3128
- ? qi.dialect.nullJsonLiteral
3129
- : qi.dialect.emptyJsonArrayLiteral;
3130
- innerJsonPairs.push([nestedRelName, qi.dialect.wrapJsonSubresult(nestedSub, fallback)]);
3131
- }
3132
- }
3133
- const innerJsonObj = buildJsonRow(qi, innerJsonPairs);
3134
- return `SELECT ${qi.dialect.buildJsonArrayAgg(innerJsonObj)} FROM (${innerSql}) ${innerAlias}`;
3135
- }
3136
- // Simple path: build the json object pairs directly off the target alias,
3137
- // including any nested relations (correlated to the target alias).
3138
- const jsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, talias);
3139
- if (opts.with) {
3140
- for (const [nestedRelName, nestedSpec] of (0, filters_js_1.sortedEntries)(opts.with)) {
3141
- const nestedRelDef = (0, utils_js_1.ownLookup)(targetMeta.relations, nestedRelName);
3142
- if (!nestedRelDef) {
3143
- throw new errors_js_1.RelationError(`Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
3144
- (0, utils_js_1.availableClause)(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
3145
- }
3146
- const nestedSub = buildRelationSubquery(qi, nestedRelDef, nestedSpec, params, talias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name], includePii);
3147
- const fallback = nestedRelDef.type === 'belongsTo' || nestedRelDef.type === 'hasOne'
3148
- ? qi.dialect.nullJsonLiteral
3149
- : qi.dialect.emptyJsonArrayLiteral;
3150
- jsonPairs.push([nestedRelName, qi.dialect.wrapJsonSubresult(nestedSub, fallback)]);
3151
- }
3152
- }
3213
+ // Both shapes project the same row after their filters and paging have
3214
+ // bound. Only its alias and FROM source differ.
3215
+ const wrapped = !!(limitClause || orderClause);
3216
+ const rowAlias = wrapped ? `${talias}i` : talias;
3217
+ const from = wrapped
3218
+ ? `FROM (SELECT ${qualifiedColumns(qi, targetMeta.allColumns, talias)} ${fromJoin} WHERE ${whereClause}${orderClause}${limitClause}) ${rowAlias}`
3219
+ : `${fromJoin} WHERE ${whereClause}`;
3220
+ const jsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, rowAlias);
3221
+ appendNestedJson(qi, jsonPairs, relDef, targetMeta, opts.with, params, rowAlias, aliasCounter, currentDepth, currentPath, includePii, true);
3153
3222
  const jsonObj = buildJsonRow(qi, jsonPairs);
3154
- return `SELECT ${qi.dialect.buildJsonArrayAgg(jsonObj)} ${fromJoin} WHERE ${whereClause}`;
3223
+ return `SELECT ${qi.dialect.buildJsonArrayAgg(jsonObj)} ${from}`;
3155
3224
  }