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
@@ -15,11 +15,12 @@
15
15
  import { CircularRelationError, InvariantError, RelationError, UnsupportedFeatureError, ValidationError, } from '../errors.js';
16
16
  import { missingIndexForRelation } from '../index-advisor.js';
17
17
  import { logTo } from '../logger.js';
18
+ import { availableClause, CELL_FLOAT, CELL_PLAIN, canonicalColumnOrder, ownLookup, relationInProjectionMessage, resolveColumnName, resolveRelation, resolveRelationDef, selectNamesNothingMessage, selectOmitExclusiveMessage, suggestKey, unknownFieldMessage, } from '../query-utils.js';
18
19
  import { normalizeKeyColumns, snakeToCamel } from '../schema.js';
19
20
  import { resolveCountRelations, stitchOnlyFields } from './batched-loader.js';
21
+ import { uniqueKeyNames } from './compound-unique.js';
20
22
  import { describeOperand, isJsonPathOrderBy, isOrderBySpec, isPlainRecord, isRelationPickOrderBy, isVectorOrderBy, MAX_NAMED_ORDER_KEYS, normalizeOrderBy, orderByEntries, sortedEntries, } from './filters.js';
21
23
  import { assertDirectionToken, assertOrderDirection } from './types.js';
22
- import { availableClause, CELL_FLOAT, CELL_PLAIN, canonicalColumnOrder, ownLookup, relationInProjectionMessage, resolveColumnName, resolveRelation, resolveRelationDef, selectNamesNothingMessage, selectOmitExclusiveMessage, suggestKey, unknownFieldMessage, } from './utils.js';
23
24
  import { hasWarnedOnce, shouldWarnOnce, WARN_NS } from './warn-registry.js';
24
25
  import * as whereMod from './where.js';
25
26
  import * as writesMod from './writes.js';
@@ -109,7 +110,7 @@ export function resolveProjection(qi, table, meta, select, omit, includePii) {
109
110
  // Check 1 runs first so both are PRESENCE-decided exactly like the branch
110
111
  // below (`if (select)`): a truthiness-decided refusal here flipped verdicts
111
112
  // between strategies when the batched loader force-added correlation keys
112
- // to an all-falsy select (review-caught in 0.65). The batched loader
113
+ // to an all-falsy select (0.65). The batched loader
113
114
  // asserts the same two rules on the RAW args (`assertProjectionShape`)
114
115
  // before any adjustment, with these same messages.
115
116
  if (select && !Array.isArray(select)) {
@@ -162,7 +163,7 @@ export function resolveProjection(qi, table, meta, select, omit, includePii) {
162
163
  // projection positionally except through THIS list: the SELECT list, the
163
164
  // relation `json_build_object` pairs and the positional `RelationShape`
164
165
  // keys are all derived from it, so they move together. The one observable
165
- // consequence is that a projected row's KEY INSERTION order now follows the
166
+ // consequence is that a projected row's KEY INSERTION order follows the
166
167
  // table rather than the `select` literal.
167
168
  const piiCols = includePii ? undefined : writesMod.piiColumns(qi, meta);
168
169
  const stitchOnly = piiCols && piiCols.size > 0 ? stitchOnlyFields(select) : undefined;
@@ -200,6 +201,10 @@ export function resolveProjection(qi, table, meta, select, omit, includePii) {
200
201
  * The query's own table. Thin wrapper over {@link resolveProjection} kept for
201
202
  * the existing call sites in builder.ts.
202
203
  */
204
+ /** A qualified scalar projection, preserving the caller's column order. */
205
+ export function qualifiedColumns(qi, columns, qualifier) {
206
+ return columns.map((column) => `${qualifier}.${qi.q(column)}`).join(', ');
207
+ }
203
208
  export function resolveColumns(qi, select, omit, includePii) {
204
209
  return resolveProjection(qi, qi.table, qi.tableMeta, select, omit, includePii);
205
210
  }
@@ -460,81 +465,39 @@ export function collectRelationSubqueryParams(qi, relDef, spec, params, _parentR
460
465
  // mirrors below must stay off for it (its documented contract remains
461
466
  // where → limit → nested).
462
467
  const nativeOrderPath = !qi.dialect.buildRelationSubquery;
463
- // manyToMany param order mirrors buildManyToManySubquery:
464
- // orderBy params → where params → limit param → nested-with params
465
- // (always, both paths).
466
- if (relDef.type === 'manyToMany') {
467
- const m2mOrderEntries = opts.orderBy ? orderByEntries(opts.orderBy).filter(([, dir]) => dir !== undefined) : [];
468
- if (nativeOrderPath && m2mOrderEntries.length > 0) {
469
- collectRelationOrderParams(qi, targetTable, targetMeta, m2mOrderEntries, params);
470
- }
471
- if (opts.where) {
472
- whereMod.collectAliasWhereParams(qi, targetTable, targetMeta, opts.where, params);
473
- }
474
- whereMod.collectTargetGlobalFilterAlias(qi, targetTable, params);
475
- if (opts.limit !== undefined && !qi.dialect.inlineLimitOffset) {
476
- params.push(qi.paginationValue(opts.limit, 'relation limit'));
477
- }
478
- const m2mOffset = relationOffset(opts);
479
- if (m2mOffset !== undefined && !qi.dialect.inlineLimitOffset) {
480
- params.push(qi.paginationValue(m2mOffset, 'relation offset'));
481
- }
482
- if (opts.with) {
483
- for (const [nestedRelName, nestedSpec] of sortedEntries(opts.with)) {
484
- const nestedRelDef = ownLookup(targetMeta.relations, nestedRelName);
485
- if (!nestedRelDef)
486
- continue;
487
- collectRelationSubqueryParams(qi, nestedRelDef, nestedSpec, params, 'alias', depth + 1);
488
- }
489
- }
490
- return;
491
- }
492
- // Mirrors buildRelationSubquery's willWrap: `orderBy: {}` is treated as absent.
493
- const relOrderEntries = opts.orderBy ? orderByEntries(opts.orderBy).filter(([, dir]) => dir !== undefined) : [];
494
- const hasOrder = relOrderEntries.length > 0;
468
+ const manyToMany = relDef.type === 'manyToMany';
469
+ const many = manyToMany || relDef.type === 'hasMany';
470
+ const entries = opts.orderBy ? orderByEntries(opts.orderBy).filter(([, dir]) => dir !== undefined) : [];
495
471
  const offset = relationOffset(opts);
496
- const willWrap = relDef.type === 'hasMany' && (opts.limit !== undefined || offset !== undefined || hasOrder);
497
- // Non-wrapped path: nested relations BEFORE where/limit
498
- if (!willWrap && opts.with) {
499
- for (const [nestedRelName, nestedSpec] of sortedEntries(opts.with)) {
500
- const nestedRelDef = ownLookup(targetMeta.relations, nestedRelName);
501
- if (!nestedRelDef)
502
- continue;
503
- collectRelationSubqueryParams(qi, nestedRelDef, nestedSpec, params, 'alias', depth + 1);
472
+ const nestedLast = manyToMany || (many && (opts.limit !== undefined || offset !== undefined || entries.length > 0));
473
+ const collectNested = () => {
474
+ if (!opts.with)
475
+ return;
476
+ for (const [name, nestedSpec] of sortedEntries(opts.with)) {
477
+ const nested = ownLookup(targetMeta.relations, name);
478
+ if (nested)
479
+ collectRelationSubqueryParams(qi, nested, nestedSpec, params, 'alias', depth + 1);
504
480
  }
481
+ };
482
+ // Unwrapped to-one/hasMany builds nested SELECTs before its predicates;
483
+ // wrapped hasMany and every m2m build them after paging the inner rows.
484
+ if (!nestedLast)
485
+ collectNested();
486
+ if (nativeOrderPath && entries.length > 0) {
487
+ collectRelationOrderParams(qi, targetTable, targetMeta, entries, params);
505
488
  }
506
- // orderBy params (JSON paths / relation-order global filters): mirrors
507
- // buildRelationSubquery, which builds its ORDER BY terms BEFORE compiling
508
- // spec.where (both wrapped and non-wrapped paths).
509
- if (nativeOrderPath && hasOrder) {
510
- collectRelationOrderParams(qi, targetTable, targetMeta, relOrderEntries, params);
511
- }
512
- // where params, mirrors buildAliasWhere push order
513
489
  if (opts.where) {
514
490
  whereMod.collectAliasWhereParams(qi, targetTable, targetMeta, opts.where, params);
515
491
  }
516
- // Global filter on the target, mirrors targetGlobalFilterAlias in
517
- // buildRelationSubquery (pushed after spec.where, before limit).
518
492
  whereMod.collectTargetGlobalFilterAlias(qi, targetTable, params);
519
- // limit param, only hasMany parameterizes its limit (mirrors
520
- // buildRelationSubquery). belongsTo/hasOne ignore limit (always LIMIT 1), so
521
- // pushing one here would orphan a param and desync the collect path.
522
- // `limit: 0` pushes (LIMIT 0 is honored), so check !== undefined.
523
- if (relDef.type === 'hasMany' && opts.limit !== undefined && !qi.dialect.inlineLimitOffset) {
524
- params.push(qi.paginationValue(opts.limit, 'relation limit'));
525
- }
526
- if (relDef.type === 'hasMany' && offset !== undefined && !qi.dialect.inlineLimitOffset) {
527
- params.push(qi.paginationValue(offset, 'relation offset'));
528
- }
529
- // Wrapped path: nested relations AFTER where/limit (inside inner subquery)
530
- if (willWrap && opts.with) {
531
- for (const [nestedRelName, nestedSpec] of sortedEntries(opts.with)) {
532
- const nestedRelDef = ownLookup(targetMeta.relations, nestedRelName);
533
- if (!nestedRelDef)
534
- continue;
535
- collectRelationSubqueryParams(qi, nestedRelDef, nestedSpec, params, 'innerAlias', depth + 1);
536
- }
493
+ if (many && !qi.dialect.inlineLimitOffset) {
494
+ if (opts.limit !== undefined)
495
+ params.push(qi.paginationValue(opts.limit, 'relation limit'));
496
+ if (offset !== undefined)
497
+ params.push(qi.paginationValue(offset, 'relation offset'));
537
498
  }
499
+ if (nestedLast)
500
+ collectNested();
538
501
  }
539
502
  /**
540
503
  * Value-shape fingerprint for a single orderBy entry, so two queries whose
@@ -906,7 +869,7 @@ export function buildRelationOrderBy(qi, relName, value, alias, params, ctx, lat
906
869
  }
907
870
  // Pick-row ordering (`{ pick, by }`): order by a value from ONE related
908
871
  // row: a correlated scalar subquery with its own ORDER BY … LIMIT 1.
909
- // Top-level findMany only (`ctx` present means we are inside a relation
872
+ // Top-level findMany only (`ctx` present means this is inside a relation
910
873
  // subquery's orderBy) and hasMany only: validatePickOrderBy throws the
911
874
  // scope errors, shared with the cache-hit collect mirror.
912
875
  if (isRelationPickOrderBy(value)) {
@@ -1232,37 +1195,38 @@ export function buildRelationOrderClause(qi, targetTable, targetMeta, alias, ord
1232
1195
  * column validation so a warmed cache can never skip it.
1233
1196
  */
1234
1197
  export function collectRelationOrderParams(qi, targetTable, targetMeta, orderEntries, params) {
1235
- for (const [key, dirValue] of orderEntries) {
1236
- if (isVectorOrderBy(dirValue)) {
1237
- throw new ValidationError(`Vector distance ordering on "${key}" is only supported in a top-level findMany orderBy.`);
1198
+ collectOrderParams(qi, orderEntries, params, { meta: targetMeta, table: targetTable });
1199
+ }
1200
+ /** Shared root/relation cache-hit binding; nested-only refusals remain explicit. */
1201
+ export function collectOrderParams(qi, entries, params, scope) {
1202
+ const meta = scope?.meta ?? qi.tableMeta;
1203
+ const table = scope?.table ?? qi.table;
1204
+ for (const [key, value] of entries) {
1205
+ if (isVectorOrderBy(value)) {
1206
+ if (scope)
1207
+ throw new ValidationError(`Vector distance ordering on "${key}" is only supported in a top-level findMany orderBy.`);
1208
+ const column = qi.toColumn(key);
1209
+ whereMod.vectorOperator(qi, key, column, value.distance.metric);
1210
+ whereMod.pushVectorParam(qi, key, column, value.distance.to, params);
1238
1211
  }
1239
- if (isJsonPathOrderBy(dirValue)) {
1240
- validateJsonPathOrderBy(qi, targetTable, targetMeta, key, dirValue);
1241
- params.push(whereMod.jsonPathParam(qi, dirValue.path));
1242
- continue;
1212
+ else if (isJsonPathOrderBy(value)) {
1213
+ validateJsonPathOrderBy(qi, table, meta, key, value);
1214
+ params.push(whereMod.jsonPathParam(qi, value.path));
1243
1215
  }
1244
- if (isRelationOrderByValue(qi, dirValue)) {
1245
- // Pick-row ordering is top-level-only: the build path throws the same
1246
- // E003 (buildRelationOrderBy with ctx set), so the mirror must too.
1247
- if (isRelationPickOrderBy(dirValue)) {
1216
+ else if (isRelationOrderByValue(qi, value)) {
1217
+ if (scope && isRelationPickOrderBy(value))
1248
1218
  throw pickOrderNestedError(qi, key);
1249
- }
1250
- // resolveRelationDef, as buildRelationOrderBy resolves it, so a relation
1251
- // written in its table spelling binds its params on a cache hit too.
1252
- const relDef = resolveRelationDef(targetMeta.relations, key);
1253
- if (relDef && (relDef.type === 'hasMany' || relDef.type === 'manyToMany')) {
1254
- collectRelationCountParams(qi, relDef, params);
1255
- }
1256
- else if (relDef) {
1257
- collectToOneRelationOrderParams(qi, key, dirValue, params, {
1258
- meta: targetMeta,
1259
- table: targetTable,
1260
- parentRef: targetTable,
1261
- });
1262
- }
1263
- continue;
1219
+ const resolved = resolveRelation(meta.relations, key);
1220
+ const def = resolved?.def;
1221
+ if (def && isRelationPickOrderBy(value))
1222
+ collectRelationPickOrderParams(qi, resolved.name, def, value, params);
1223
+ else if (def && (def.type === 'hasMany' || def.type === 'manyToMany'))
1224
+ collectRelationCountParams(qi, def, params);
1225
+ else if (def)
1226
+ collectToOneRelationOrderParams(qi, key, value, params, scope ? { meta, table, parentRef: table } : undefined);
1264
1227
  }
1265
- resolveOrderByColumn(qi, targetTable, targetMeta, key);
1228
+ else if (scope)
1229
+ resolveOrderByColumn(qi, table, meta, key);
1266
1230
  }
1267
1231
  }
1268
1232
  /**
@@ -1443,12 +1407,27 @@ function parseScalarColumns(qi, row, table, meta, fromJson) {
1443
1407
  countObj[key.slice(COUNT_PREFIX.length)] = Number(parsed[key]);
1444
1408
  }
1445
1409
  if (countObj) {
1410
+ // Preserve the row and its descriptors. Copying it would read scalar
1411
+ // getters again, including accessors installed by inherited setters.
1446
1412
  for (const rel of Object.keys(countObj))
1447
1413
  delete parsed[`${COUNT_PREFIX}${rel}`];
1448
1414
  parsed._count = countObj;
1449
1415
  }
1450
1416
  return parsed;
1451
1417
  }
1418
+ /**
1419
+ * The warn-and-throw for a relation payload that could not be parsed as
1420
+ * JSON, shared by {@link parseRelationValue} and the object decode plan so
1421
+ * both report the same relation with the same cause chain.
1422
+ */
1423
+ function throwRelationPayloadError(qi, relName, err) {
1424
+ const log = whereMod.adviceLogger(qi);
1425
+ if (log && shouldWarnOnce(WARN_NS.relationParseFailure, `${qi.table}.${relName}`)) {
1426
+ logTo(log, 'warn', `Relation "${relName}" on "${qi.table}" returned a payload that is not valid JSON. ` +
1427
+ `This is a bug; please report it with the emitted SQL.`, { code: 'relation-payload-json', table: qi.table, relation: relName });
1428
+ }
1429
+ throw new InvariantError('relation-payload-json', `Relation "${relName}" on table "${qi.table}" returned a payload that could not be parsed as JSON.`, { cause: err });
1430
+ }
1452
1431
  /**
1453
1432
  * The relation half of {@link parseNestedRow}: one relation column's value
1454
1433
  * (never `undefined`, which the caller skips) as the parsed relation.
@@ -1465,18 +1444,9 @@ function parseRelationValue(qi, relName, relDef, rawValue) {
1465
1444
  // --- Non-empty values: full parse path ---
1466
1445
  if (typeof rawValue === 'string') {
1467
1446
  try {
1468
- const jsonVal = JSON.parse(rawValue);
1469
1447
  // After parsing, recurse via parseNestedRow so each item gets date
1470
1448
  // coercion AND its own sub-relations parsed at arbitrary depth.
1471
- if (Array.isArray(jsonVal)) {
1472
- return jsonVal.map((item) => typeof item === 'object' && item !== null
1473
- ? parseNestedRow(qi, item, relDef.to, true)
1474
- : item);
1475
- }
1476
- if (typeof jsonVal === 'object' && jsonVal !== null) {
1477
- return parseNestedRow(qi, jsonVal, relDef.to, true);
1478
- }
1479
- return jsonVal;
1449
+ return parseRelationObject(qi, relDef, JSON.parse(rawValue));
1480
1450
  }
1481
1451
  catch (err) {
1482
1452
  // A relation column that does not parse is a bug in the emitted SQL or
@@ -1490,14 +1460,13 @@ function parseRelationValue(qi, relName, relDef, rawValue) {
1490
1460
  // per-relation loop: one 10,000-row page was 10,000 warnings. The
1491
1461
  // parse error stays out of the entry: its message quotes the payload,
1492
1462
  // which is row data.
1493
- const log = whereMod.adviceLogger(qi);
1494
- if (log && shouldWarnOnce(WARN_NS.relationParseFailure, `${qi.table}.${relName}`)) {
1495
- logTo(log, 'warn', `Relation "${relName}" on "${qi.table}" returned a payload that is not valid JSON. ` +
1496
- `This is a bug; please report it with the emitted SQL.`, { code: 'relation-payload-json', table: qi.table, relation: relName });
1497
- }
1498
- throw new InvariantError('relation-payload-json', `Relation "${relName}" on table "${qi.table}" returned a payload that could not be parsed as JSON.`, { cause: err });
1463
+ throwRelationPayloadError(qi, relName, err);
1499
1464
  }
1500
1465
  }
1466
+ return parseRelationObject(qi, relDef, rawValue);
1467
+ }
1468
+ /** The same nested-object walk for driver-decoded JSON and JSON text. */
1469
+ function parseRelationObject(qi, relDef, rawValue) {
1501
1470
  if (Array.isArray(rawValue)) {
1502
1471
  return rawValue.map((item) => typeof item === 'object' && item !== null
1503
1472
  ? parseNestedRow(qi, item, relDef.to, true)
@@ -1691,13 +1660,13 @@ export function buildRelationShape(qi, relDef, spec, parentMeta, includePii) {
1691
1660
  return { keys, nested, cardinality };
1692
1661
  }
1693
1662
  /**
1694
- * Build the row parser for a `with` clause. In object mode this is just
1695
- * {@link parseNestedRow}. In positional mode the relation shapes are built
1696
- * once (not per row) and compiled into a decode plan
1697
- * ({@link makePositionalRowParser}) that turns each positional array straight
1698
- * into its parsed row. A query whose shapes the plan declines takes the
1699
- * reference path instead, which decodes each positional array into the object
1700
- * form and hands it to parseNestedRow.
1663
+ * Build the row parser for a `with` clause. The relation shapes are built
1664
+ * once per query (not per row) and compiled into a decode plan: in positional mode
1665
+ * {@link makePositionalRowParser} turns each positional array straight into
1666
+ * its parsed row, in object mode {@link makeObjectRowParser} does the same
1667
+ * for each keyed JSON object. A query whose shapes the plan declines takes
1668
+ * the reference path instead ({@link parseNestedRow}, in positional mode
1669
+ * after decoding each array into the object form).
1701
1670
  */
1702
1671
  export function makeNestedParser(qi, withClause, includePii, flattenPlan) {
1703
1672
  // A flatten plan and the positional encoding are mutually exclusive (the
@@ -1706,7 +1675,34 @@ export function makeNestedParser(qi, withClause, includePii, flattenPlan) {
1706
1675
  if (flattenPlan)
1707
1676
  return makeFlattenParser(qi, flattenPlan);
1708
1677
  if (qi.jsonEncoding !== 'positional') {
1709
- return (row) => parseNestedRow(qi, row, qi.table);
1678
+ // The plan reads a row by position, so it is only worth building where
1679
+ // the engine returns a JSON object's keys in the order the statement
1680
+ // wrote them. MySQL sorts them: every row would fall back to the walker,
1681
+ // and the plan would be built for each query and never used.
1682
+ if (!qi.dialect.capabilities.jsonObjectKeysAsWritten)
1683
+ return (row) => parseNestedRow(qi, row, qi.table);
1684
+ // Built lazily, on the first row actually decoded, never here: this
1685
+ // parser can be constructed before its statement exists (the stream
1686
+ // paths build it first), and the statement build owns validation and
1687
+ // diagnostic ordering. Shape building can throw the same validation
1688
+ // errors, so constructing eagerly would surface them ahead of that
1689
+ // ordering and skip its warnings. If construction fails for any
1690
+ // reason the query decodes through the reference; plan
1691
+ // construction surfaces no error and no log line of its own.
1692
+ let parser;
1693
+ return (row) => {
1694
+ if (parser === undefined) {
1695
+ parser = (r) => parseNestedRow(qi, r, qi.table);
1696
+ try {
1697
+ parser =
1698
+ makeObjectRowParser(qi, qi.table, buildRelationShapes(qi, qi.table, withClause, includePii)) ?? parser;
1699
+ }
1700
+ catch {
1701
+ // The reference parser above stays in place for this query.
1702
+ }
1703
+ }
1704
+ return parser(row);
1705
+ };
1710
1706
  }
1711
1707
  const shapes = buildRelationShapes(qi, qi.table, withClause, includePii);
1712
1708
  return makePositionalRowParser(qi, qi.table, shapes) ?? makeReferencePositionalParser(qi, shapes);
@@ -1874,6 +1870,7 @@ function planPositionalRow(qi, table, shape) {
1874
1870
  return undefined;
1875
1871
  return {
1876
1872
  table,
1873
+ keys,
1877
1874
  fields,
1878
1875
  wire,
1879
1876
  cellPositions,
@@ -1889,47 +1886,62 @@ function planPositionalRow(qi, table, shape) {
1889
1886
  * reference's on every shape it does take.
1890
1887
  */
1891
1888
  export function makePositionalRowParser(qi, table, shapes) {
1889
+ return makeTopRowParser(qi, table, shapes, false);
1890
+ }
1891
+ /**
1892
+ * The top-level planned parser both encodings share: the row's scalar half
1893
+ * through {@link parseScalarColumns} exactly as the reference runs it, then
1894
+ * each relation column replaced by its planned decode (or the reference's
1895
+ * {@link parseRelationValue} for a relation the `with` clause did not plan).
1896
+ * The encodings differ in three places, all keyed on `objectMode`: the
1897
+ * positional reference reads relation columns off a `{ ...row }` copy (own
1898
+ * enumerable only) with them already decoded, so it needs the plain-name and
1899
+ * column-collision declines below and decodes a present-but-`undefined`
1900
+ * slot, where the object reference reads the row directly and skips
1901
+ * `undefined`. An object
1902
+ * query with no planned relation at all (a bare `_count`) declines, where
1903
+ * the positional one still has decoding of its own to do.
1904
+ */
1905
+ function makeTopRowParser(qi, table, shapes, objectMode) {
1892
1906
  const meta = qi.schema.tables[table];
1893
1907
  if (!meta || !qi.rowDecodePlan || !qi.decodeCell)
1894
1908
  return undefined;
1895
1909
  const entries = getRelationEntries(qi, table, meta);
1896
- if (!entries.every(([name]) => isPlainKey(name)))
1910
+ if (!objectMode && !entries.every(([name]) => isPlainKey(name)))
1897
1911
  return undefined;
1898
1912
  const plans = [];
1913
+ let planned = false;
1899
1914
  for (const [name, def] of entries) {
1900
1915
  const shape = Object.hasOwn(shapes, name) ? shapes[name] : undefined;
1901
1916
  if (!shape) {
1902
1917
  plans.push(null);
1903
1918
  continue;
1904
1919
  }
1905
- // The reference runs the top-level row through parseRow with the relation
1906
- // columns already decoded; the plan runs it with them raw and replaces them
1907
- // after. Those agree only while parseRow copies a relation column through
1908
- // untouched, under its own name, and the `_count` fold never reads it.
1909
- if (name.startsWith(COUNT_PREFIX) || nameTouchesColumns(qi, table, meta, name))
1920
+ if (!objectMode && (name.startsWith(COUNT_PREFIX) || nameTouchesColumns(qi, table, meta, name)))
1910
1921
  return undefined;
1911
1922
  const row = planPositionalRow(qi, def.to, shape);
1912
1923
  if (!row)
1913
1924
  return undefined;
1914
1925
  plans.push({ name, def, many: shape.cardinality === 'many', position: -1, row });
1926
+ planned = true;
1915
1927
  }
1928
+ if (objectMode && !planned)
1929
+ return undefined;
1916
1930
  const isOwnEnumerable = Object.prototype.propertyIsEnumerable;
1917
1931
  return (row) => {
1918
1932
  const parsed = parseScalarColumns(qi, row, table, meta, false);
1919
1933
  for (let i = 0; i < entries.length; i++) {
1920
1934
  const [name, def] = entries[i];
1921
- // The reference reads relation columns off a `{ ...row }` copy, which
1922
- // holds exactly the row's own enumerable properties.
1923
- if (!isOwnEnumerable.call(row, name))
1935
+ if (objectMode ? row[name] === undefined : !isOwnEnumerable.call(row, name))
1924
1936
  continue;
1925
1937
  const plan = plans[i];
1938
+ const raw = row[name];
1926
1939
  if (plan !== null) {
1927
- parsed[name] = decodePlannedRelation(qi, row[name], plan);
1928
- continue;
1940
+ parsed[name] = objectMode ? decodeObjectRelation(qi, raw, plan) : decodePlannedRelation(qi, raw, plan);
1929
1941
  }
1930
- const raw = row[name];
1931
- if (raw !== undefined)
1942
+ else if (raw !== undefined) {
1932
1943
  parsed[name] = parseRelationValue(qi, name, def, raw);
1944
+ }
1933
1945
  }
1934
1946
  return parsed;
1935
1947
  };
@@ -1974,6 +1986,16 @@ function decodePlannedRelation(qi, raw, rel) {
1974
1986
  }
1975
1987
  /** One positional array through its row plan, into the parsed row. */
1976
1988
  function decodePlannedRow(qi, arr, plan) {
1989
+ return decodePlannedRowWith(qi, arr, plan, decodePlannedRelation);
1990
+ }
1991
+ /**
1992
+ * The planned row write both decoders share: scalars and cell decodes from a
1993
+ * values array in shape order (a positional array as it arrived, or
1994
+ * `Object.values` of a keyed row whose keys were verified to be in shape
1995
+ * order), then relation slots through the caller's relation decoder, which
1996
+ * is where the two encodings' value semantics differ.
1997
+ */
1998
+ function decodePlannedRowWith(qi, arr, plan, decodeRelation) {
1977
1999
  const out = {};
1978
2000
  const { fields, wire, cellPositions, cellKinds, relations, table } = plan;
1979
2001
  for (let i = 0; i < fields.length; i++) {
@@ -2000,7 +2022,7 @@ function decodePlannedRow(qi, arr, plan) {
2000
2022
  const order = plan.relationOrder;
2001
2023
  if (order === null) {
2002
2024
  for (const rel of relations)
2003
- out[rel.name] = decodePlannedRelation(qi, arr[rel.position], rel);
2025
+ out[rel.name] = decodeRelation(qi, arr[rel.position], rel);
2004
2026
  }
2005
2027
  else {
2006
2028
  // Claim the keys in key order first, then decode in the reference's order.
@@ -2008,13 +2030,110 @@ function decodePlannedRow(qi, arr, plan) {
2008
2030
  out[rel.name] = undefined;
2009
2031
  for (const index of order) {
2010
2032
  const rel = relations[index];
2011
- out[rel.name] = decodePlannedRelation(qi, arr[rel.position], rel);
2033
+ out[rel.name] = decodeRelation(qi, arr[rel.position], rel);
2012
2034
  }
2013
2035
  }
2014
2036
  }
2015
2037
  return out;
2016
2038
  }
2017
2039
  // ---------------------------------------------------------------------------
2040
+ // Object decode plan: one pass from a keyed JSON object to its parsed row
2041
+ //
2042
+ // The same plan the positional decoder runs, read by key instead of by
2043
+ // position. It is held to {@link parseNestedRow} the way the positional plan
2044
+ // is held to its reference: field names, cell kinds and wire rules come from
2045
+ // the shared {@link PositionalRowPlan} (so every decline check in
2046
+ // `planPositionalRow` applies here too), cell decodes go through
2047
+ // `qi.decodeCell`, and the work runs in the reference's order. One thing
2048
+ // differs from the positional decoder: a keyed row's own key order is not
2049
+ // guaranteed to be the shape's (MySQL sorts JSON object keys by length then
2050
+ // bytes, and a caller-supplied JSON type parser can reorder freely), and
2051
+ // the reference decodes cells in the order the row carries them, which is
2052
+ // observable through the logger. The plan therefore decodes only a row
2053
+ // whose keys are exactly the shape's keys in shape order; any other row
2054
+ // (permuted, a missing or extra key, a `_count__` field, a relation the
2055
+ // `with` clause did not ask for) falls back to `parseNestedRow`, decided
2056
+ // before any cell decode runs, so the fallback decodes exactly once. A
2057
+ // permuted row also marks its plan node (see `PositionalRowPlan.unordered`)
2058
+ // so an engine that never emits shape order pays the comparison once per
2059
+ // shape per result, not once per row.
2060
+ // ---------------------------------------------------------------------------
2061
+ /**
2062
+ * Compile a top-level object parser for `shapes` (see `makeTopRowParser`),
2063
+ * or `undefined` when a shape is declined or nothing is planned.
2064
+ */
2065
+ export function makeObjectRowParser(qi, table, shapes) {
2066
+ return makeTopRowParser(qi, table, shapes, true);
2067
+ }
2068
+ /**
2069
+ * One relation value through the object plan: exactly what the reference
2070
+ * produces by {@link parseRelationValue}. The shortcuts and the dispatch on
2071
+ * the value's type are the reference's; only the per-row walk is planned.
2072
+ */
2073
+ function decodeObjectRelation(qi, raw, rel) {
2074
+ if (raw === null || raw === 'null')
2075
+ return null;
2076
+ if (raw === '[]')
2077
+ return [];
2078
+ if (Array.isArray(raw) && raw.length === 0)
2079
+ return [];
2080
+ let value = raw;
2081
+ let wrapped = false;
2082
+ if (typeof raw === 'string') {
2083
+ try {
2084
+ value = JSON.parse(raw);
2085
+ }
2086
+ catch (err) {
2087
+ throwRelationPayloadError(qi, rel.name, err);
2088
+ }
2089
+ wrapped = true;
2090
+ }
2091
+ // The reference parses AND decodes a string payload inside one try, so a
2092
+ // failure deep in it is re-reported against THIS relation, with the inner
2093
+ // failure as its cause. The `wrapped` catch mirrors that exactly.
2094
+ try {
2095
+ if (Array.isArray(value)) {
2096
+ const out = [];
2097
+ for (let i = 0; i < value.length; i++) {
2098
+ const item = value[i];
2099
+ out.push(typeof item === 'object' && item !== null
2100
+ ? Array.isArray(item)
2101
+ ? parseNestedRow(qi, item, rel.def.to, true)
2102
+ : decodeObjectRow(qi, item, rel.row)
2103
+ : item);
2104
+ }
2105
+ return out;
2106
+ }
2107
+ if (typeof value === 'object' && value !== null) {
2108
+ return decodeObjectRow(qi, value, rel.row);
2109
+ }
2110
+ return value;
2111
+ }
2112
+ catch (err) {
2113
+ if (wrapped)
2114
+ throwRelationPayloadError(qi, rel.name, err);
2115
+ throw err;
2116
+ }
2117
+ }
2118
+ /** One keyed JSON object through its row plan, into the parsed row. */
2119
+ function decodeObjectRow(qi, row, plan) {
2120
+ const { keys, table } = plan;
2121
+ if (plan.unordered)
2122
+ return parseNestedRow(qi, row, table, true);
2123
+ const rowKeys = Object.keys(row);
2124
+ if (rowKeys.length !== keys.length)
2125
+ return parseNestedRow(qi, row, table, true);
2126
+ for (let i = 0; i < keys.length; i++) {
2127
+ if (rowKeys[i] !== keys[i]) {
2128
+ plan.unordered = true;
2129
+ return parseNestedRow(qi, row, table, true);
2130
+ }
2131
+ }
2132
+ // The compare above is what proves the row is in shape order, so nothing
2133
+ // is assumed; `Object.values` of such a row is its values in that order.
2134
+ return decodePlannedRowWith(qi, Object.values(row), plan, decodeObjectRelation);
2135
+ }
2136
+ // ---------------------------------------------------------------------------
2018
2137
  // relationLoadStrategy: 'flatten', to-one relations compiled as LEFT JOINs
2019
2138
  // ---------------------------------------------------------------------------
2020
2139
  /**
@@ -2113,19 +2232,7 @@ export function provableUniqueTargetKey(relDef, targetMeta) {
2113
2232
  return null;
2114
2233
  if (!cols.every((col) => targetMeta.allColumns.includes(col)))
2115
2234
  return null;
2116
- if (sameColumnSet(cols, targetMeta.primaryKey))
2117
- return cols;
2118
- for (const unique of targetMeta.uniqueColumns) {
2119
- if (sameColumnSet(cols, unique))
2120
- return cols;
2121
- }
2122
- for (const idx of targetMeta.indexes) {
2123
- if (!idx.unique || idx.partial || idx.docPath)
2124
- continue;
2125
- if (sameColumnSet(cols, idx.columns))
2126
- return cols;
2127
- }
2128
- return null;
2235
+ return uniqueKeyNames(targetMeta).some((key) => sameColumnSet(cols, key)) ? cols : null;
2129
2236
  }
2130
2237
  /**
2131
2238
  * Plan one relation as a flattened LEFT JOIN, or return `null` to leave it on
@@ -2251,7 +2358,7 @@ function flattenNodeSignature(node) {
2251
2358
  *
2252
2359
  * Off when `diagnostics` turn advice off, like the other planner notes, and
2253
2360
  * deduped through the shared registry so a hot query logs once rather than per
2254
- * call. Note that a flatten plan is recomputed on the build, param-collect and
2361
+ * call. A flatten plan is recomputed on the build, param-collect and
2255
2362
  * row-assembly paths for the same query; the registry is what keeps that to
2256
2363
  * one line.
2257
2364
  */
@@ -2589,7 +2696,7 @@ export function buildSelectWithRelations(qi, table, withClause, params, columnsL
2589
2696
  }
2590
2697
  const cols = columnsList ?? meta.allColumns;
2591
2698
  const qtbl = qi.q(table);
2592
- const baseCols = cols.map((col) => `${qtbl}.${qi.q(col)}`).join(', ');
2699
+ const baseCols = qualifiedColumns(qi, cols, qtbl);
2593
2700
  const relationSelects = [];
2594
2701
  const aliasCounter = { n: 0 };
2595
2702
  for (const [relName, relSpec] of sortedEntries(withClause)) {
@@ -2627,6 +2734,21 @@ export function buildSelectWithRelations(qi, table, withClause, params, columnsL
2627
2734
  }
2628
2735
  return [baseCols, ...relationSelects].join(', ');
2629
2736
  }
2737
+ /** Append nested JSON slots at the caller's existing parameter position. */
2738
+ function appendNestedJson(qi, pairs, relDef, targetMeta, withClause, params, parentAlias, aliasCounter, depth, path, includePii, manyFallback = false) {
2739
+ if (!withClause)
2740
+ return;
2741
+ for (const [name, spec] of sortedEntries(withClause)) {
2742
+ const nested = ownLookup(targetMeta.relations, name);
2743
+ if (!nested)
2744
+ throw new RelationError(`Unknown relation "${name}" on table "${relDef.to}". ` +
2745
+ availableClause(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
2746
+ const subquery = buildRelationSubquery(qi, nested, spec, params, parentAlias, aliasCounter, depth + 1, [...path, relDef.name], includePii);
2747
+ const array = manyFallback ? nested.type !== 'belongsTo' && nested.type !== 'hasOne' : nested.type === 'hasMany';
2748
+ const fallback = array ? qi.dialect.emptyJsonArrayLiteral : qi.dialect.nullJsonLiteral;
2749
+ pairs.push([name, qi.dialect.wrapJsonSubresult(subquery, fallback)]);
2750
+ }
2751
+ }
2630
2752
  /**
2631
2753
  * Generate a correlated subquery that returns JSON for a single relation.
2632
2754
  *
@@ -2747,7 +2869,7 @@ export function buildRelationSubquery(qi, relDef, spec, params, parentRef, alias
2747
2869
  if (log) {
2748
2870
  const warnKey = `${relDef.from}.${relDef.name}`;
2749
2871
  // Compute the (potentially costly) probe only for a key not yet warned, and
2750
- // claim the key through the process-wide registry ONLY when we actually warn,
2872
+ // claim the key through the process-wide registry ONLY when emitting a warning,
2751
2873
  // so a dual-package / HMR-reevaluated second module copy cannot re-warn the
2752
2874
  // same relation, and indexed relations never consume the dedupe cap.
2753
2875
  if (!hasWarnedOnce(WARN_NS.unindexedRelation, warnKey)) {
@@ -2827,7 +2949,7 @@ export function buildRelationSubquery(qi, relDef, spec, params, parentRef, alias
2827
2949
  const jsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, alias);
2828
2950
  // Determine if this hasMany will take the wrapped subquery path (LIMIT or ORDER BY).
2829
2951
  // When wrapping, nested relations are built in the wrapped path referencing innerAlias,
2830
- // so we must NOT build them here (they would push orphaned params).
2952
+ // so do NOT build them here (they would push orphaned params).
2831
2953
  // An orderBy with no defined entries (`orderBy: {}`) is treated as absent -
2832
2954
  // it must neither trigger the wrap (dropping nested relations) nor render a
2833
2955
  // dangling `ORDER BY `. `limit: 0` is meaningful (LIMIT 0) and DOES wrap.
@@ -2840,21 +2962,10 @@ export function buildRelationSubquery(qi, relDef, spec, params, parentRef, alias
2840
2962
  if (relDef.type === 'manyToMany') {
2841
2963
  return buildManyToManySubquery(qi, relDef, spec, params, parentRef, aliasCounter, currentDepth, currentPath, alias, targetMeta, targetColumns, includePii);
2842
2964
  }
2843
- // Nested relations, only in the non-wrapped path (wrapped path builds them separately)
2844
- if (!willWrap && opts.with) {
2845
- for (const [nestedRelName, nestedSpec] of sortedEntries(opts.with)) {
2846
- const nestedRelDef = ownLookup(targetMeta.relations, nestedRelName);
2847
- if (!nestedRelDef) {
2848
- throw new RelationError(`Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
2849
- availableClause(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
2850
- }
2851
- // Recursively build nested subquery, passing THIS alias as the parent reference
2852
- const nestedSubquery = buildRelationSubquery(qi, nestedRelDef, nestedSpec, params, alias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name], includePii);
2853
- // Use '[]'::json for hasMany (empty array), NULL for belongsTo/hasOne (no object)
2854
- const fallback = nestedRelDef.type === 'hasMany' ? qi.dialect.emptyJsonArrayLiteral : qi.dialect.nullJsonLiteral;
2855
- jsonPairs.push([nestedRelName, qi.dialect.wrapJsonSubresult(nestedSubquery, fallback)]);
2856
- }
2857
- }
2965
+ // The two SELECT levels differ only in their row alias. Invoke at the
2966
+ // original bind position so nested WHERE params stay before or after paging.
2967
+ if (!willWrap)
2968
+ appendNestedJson(qi, jsonPairs, relDef, targetMeta, opts.with, params, alias, aliasCounter, currentDepth, currentPath, includePii);
2858
2969
  const jsonObj = buildJsonRow(qi, jsonPairs);
2859
2970
  // Quote parent ref, can be a table name or auto-generated alias
2860
2971
  const qParent = qi.q(parentRef);
@@ -2911,22 +3022,10 @@ export function buildRelationSubquery(qi, relDef, spec, params, parentRef, alias
2911
3022
  const innerAlias = `${alias}i`;
2912
3023
  // Rewrite: SELECT json_agg(json_build_object(...)) FROM (SELECT * FROM table WHERE ... ORDER BY ... LIMIT N) AS alias
2913
3024
  // Inner SELECT always needs all columns for WHERE/ORDER to work; json_build_object filters later
2914
- const innerSql = `SELECT ${targetMeta.allColumns.map((c) => `${alias}.${qi.q(c)}`).join(', ')} FROM ${qTarget} ${alias} WHERE ${whereClause}${orderClause}${limitClause}`;
3025
+ const innerSql = `SELECT ${qualifiedColumns(qi, targetMeta.allColumns, alias)} FROM ${qTarget} ${alias} WHERE ${whereClause}${orderClause}${limitClause}`;
2915
3026
  // For the json_build_object, reference the inner alias, only include resolved columns
2916
3027
  const innerJsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, innerAlias);
2917
- // Build nested relation subqueries referencing innerAlias
2918
- if (opts.with) {
2919
- for (const [nestedRelName, nestedSpec] of sortedEntries(opts.with)) {
2920
- const nestedRelDef = ownLookup(targetMeta.relations, nestedRelName);
2921
- if (!nestedRelDef) {
2922
- throw new RelationError(`Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
2923
- availableClause(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
2924
- }
2925
- const nestedSub = buildRelationSubquery(qi, nestedRelDef, nestedSpec, params, innerAlias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name], includePii);
2926
- const fallback = nestedRelDef.type === 'hasMany' ? qi.dialect.emptyJsonArrayLiteral : qi.dialect.nullJsonLiteral;
2927
- innerJsonPairs.push([nestedRelName, qi.dialect.wrapJsonSubresult(nestedSub, fallback)]);
2928
- }
2929
- }
3028
+ appendNestedJson(qi, innerJsonPairs, relDef, targetMeta, opts.with, params, innerAlias, aliasCounter, currentDepth, currentPath, includePii);
2930
3029
  const innerJsonObj = buildJsonRow(qi, innerJsonPairs);
2931
3030
  return `SELECT ${qi.dialect.buildJsonArrayAgg(innerJsonObj)} FROM (${innerSql}) ${innerAlias}`;
2932
3031
  }
@@ -2976,7 +3075,7 @@ export function buildManyToManySubquery(qi, relDef, spec, params, parentRef, ali
2976
3075
  // JOIN: junction.targetKey = target.<targetPK>. Composite keys pair positionally.
2977
3076
  const targetKeys = normalizeKeyColumns(relDef.through.targetKey);
2978
3077
  // The target PK is the column(s) the junction's targetKey references. An empty
2979
- // introspected PK means we cannot know what to JOIN on, fail loudly rather than
3078
+ // introspected PK leaves no known JOIN column: fail loudly rather than
2980
3079
  // silently guessing `id` and generating a wrong JOIN.
2981
3080
  if (targetMeta.primaryKey.length === 0) {
2982
3081
  throw new ValidationError(`manyToMany relation "${relDef.name}" targets table "${targetTable}" which has no primary key; ` +
@@ -3023,48 +3122,15 @@ export function buildManyToManySubquery(qi, relDef, spec, params, parentRef, ali
3023
3122
  // LIMIT / OFFSET, `limit: 0` is honored (LIMIT 0 → empty array)
3024
3123
  const limitClause = relationPagination(qi, opts.limit, relationOffset(opts), params, relOrderEntries.length > 0);
3025
3124
  const fromJoin = `FROM ${qTarget} ${talias} JOIN ${qJunction} ${jalias} ON ${joinOn}`;
3026
- // When LIMIT or ORDER BY is present, wrap the joined rows in an inner subquery
3027
- // so the LIMIT applies to rows BEFORE aggregation (same approach as hasMany).
3028
- if (limitClause || orderClause) {
3029
- const innerAlias = `${talias}i`;
3030
- const innerSql = `SELECT ${targetMeta.allColumns.map((c) => `${talias}.${qi.q(c)}`).join(', ')} ` +
3031
- `${fromJoin} WHERE ${whereClause}${orderClause}${limitClause}`;
3032
- const innerJsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, innerAlias);
3033
- // Nested relations reference the inner alias.
3034
- if (opts.with) {
3035
- for (const [nestedRelName, nestedSpec] of sortedEntries(opts.with)) {
3036
- const nestedRelDef = ownLookup(targetMeta.relations, nestedRelName);
3037
- if (!nestedRelDef) {
3038
- throw new RelationError(`Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
3039
- availableClause(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
3040
- }
3041
- const nestedSub = buildRelationSubquery(qi, nestedRelDef, nestedSpec, params, innerAlias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name], includePii);
3042
- const fallback = nestedRelDef.type === 'belongsTo' || nestedRelDef.type === 'hasOne'
3043
- ? qi.dialect.nullJsonLiteral
3044
- : qi.dialect.emptyJsonArrayLiteral;
3045
- innerJsonPairs.push([nestedRelName, qi.dialect.wrapJsonSubresult(nestedSub, fallback)]);
3046
- }
3047
- }
3048
- const innerJsonObj = buildJsonRow(qi, innerJsonPairs);
3049
- return `SELECT ${qi.dialect.buildJsonArrayAgg(innerJsonObj)} FROM (${innerSql}) ${innerAlias}`;
3050
- }
3051
- // Simple path: build the json object pairs directly off the target alias,
3052
- // including any nested relations (correlated to the target alias).
3053
- const jsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, talias);
3054
- if (opts.with) {
3055
- for (const [nestedRelName, nestedSpec] of sortedEntries(opts.with)) {
3056
- const nestedRelDef = ownLookup(targetMeta.relations, nestedRelName);
3057
- if (!nestedRelDef) {
3058
- throw new RelationError(`Unknown relation "${nestedRelName}" on table "${targetTable}". ` +
3059
- availableClause(Object.keys(targetMeta.relations), `"${relDef.to}" has no relations.`));
3060
- }
3061
- const nestedSub = buildRelationSubquery(qi, nestedRelDef, nestedSpec, params, talias, aliasCounter, currentDepth + 1, [...currentPath, relDef.name], includePii);
3062
- const fallback = nestedRelDef.type === 'belongsTo' || nestedRelDef.type === 'hasOne'
3063
- ? qi.dialect.nullJsonLiteral
3064
- : qi.dialect.emptyJsonArrayLiteral;
3065
- jsonPairs.push([nestedRelName, qi.dialect.wrapJsonSubresult(nestedSub, fallback)]);
3066
- }
3067
- }
3125
+ // Both shapes project the same row after their filters and paging have
3126
+ // bound. Only its alias and FROM source differ.
3127
+ const wrapped = !!(limitClause || orderClause);
3128
+ const rowAlias = wrapped ? `${talias}i` : talias;
3129
+ const from = wrapped
3130
+ ? `FROM (SELECT ${qualifiedColumns(qi, targetMeta.allColumns, talias)} ${fromJoin} WHERE ${whereClause}${orderClause}${limitClause}) ${rowAlias}`
3131
+ : `${fromJoin} WHERE ${whereClause}`;
3132
+ const jsonPairs = jsonScalarPairs(qi, targetMeta, targetColumns, rowAlias);
3133
+ appendNestedJson(qi, jsonPairs, relDef, targetMeta, opts.with, params, rowAlias, aliasCounter, currentDepth, currentPath, includePii, true);
3068
3134
  const jsonObj = buildJsonRow(qi, jsonPairs);
3069
- return `SELECT ${qi.dialect.buildJsonArrayAgg(jsonObj)} ${fromJoin} WHERE ${whereClause}`;
3135
+ return `SELECT ${qi.dialect.buildJsonArrayAgg(jsonObj)} ${from}`;
3070
3136
  }