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
@@ -1,2004 +1,6 @@
1
- /**
2
- * turbine-orm, Query builder utilities
3
- *
4
- * Standalone utility functions and classes used by the query builder.
5
- */
1
+ /** PostgreSQL compatibility exports. The query engine uses query-utils. */
6
2
  import pg from '#pg';
7
- import { ValidationError } from '../errors.js';
8
- import { consoleLogger, logTo } from '../logger.js';
9
- import { camelToSnake, localDateTimeKind, snakeToCamel, timeOfDayKind } from '../schema.js';
10
- import { shouldWarnOnce, WARN_NS } from './warn-registry.js';
11
- // ---------------------------------------------------------------------------
12
- // Identifier quoting, prevents SQL injection via table/column names
13
- // ---------------------------------------------------------------------------
14
- /**
15
- * Quote a SQL identifier (table name, column name) using Postgres double-quote
16
- * rules: wrap in double quotes, escape internal double quotes by doubling them.
17
- *
18
- * @example
19
- * quoteIdent('users') → '"users"'
20
- * quoteIdent('my"table') → '"my""table"'
21
- * quoteIdent('user name') → '"user name"'
22
- */
23
- export function quoteIdent(name) {
24
- return `"${name.replace(/"/g, '""')}"`;
25
- }
26
- /**
27
- * Prototype-safe own-property read for the plain metadata maps (columnMap,
28
- * relations, reverseColumnMap). These are constructed as plain objects, so a
29
- * bare `map[key]` for a user-supplied field name like "constructor",
30
- * "toString", or "__proto__" returns an inherited member from
31
- * `Object.prototype`, a truthy value that slips past validation and produces a
32
- * cryptic `TypeError` instead of a clean `ValidationError`. Returns `undefined`
33
- * unless `key` is an OWN enumerable/non-enumerable property.
34
- */
35
- export function ownLookup(map, key) {
36
- return Object.hasOwn(map, key) ? map[key] : undefined;
37
- }
38
- /**
39
- * Resolve a user-supplied key to its unquoted column name, or `undefined` when
40
- * the key names no column on the table.
41
- *
42
- * THE key-resolution rule, in one place. `QueryInterface.toColumn` is this
43
- * function plus the E003 throw, so every SQL builder resolves keys through it,
44
- * and the value-side passes (write coercion, the `updatedAt` injector, the
45
- * nested-write foreign-key merge) call it directly rather than re-deriving the
46
- * rule. They used to read `columnMap` alone, which knows only the FIELD
47
- * spelling, so a key spelled as the snake_case COLUMN, which the SQL builders
48
- * accept and which is the natural spelling on an introspected schema, produced
49
- * correct SQL with an unprocessed value: byte-identical statement, silently
50
- * different bound param.
51
- *
52
- * The rule: the field map first, else `camelToSnake(key)` accepted ONLY when
53
- * that name is a real column. `camelToSnake` is idempotent on an already-snake
54
- * string, which is what makes the column spelling legal; arbitrary strings
55
- * still fail to resolve, so identifier validation is unchanged.
56
- *
57
- * Prototype-safe: both maps are plain objects, so a key like "constructor" or
58
- * "__proto__" would otherwise return an inherited member and pass for a column
59
- * name (see {@link ownLookup}).
60
- */
61
- export function resolveColumnName(meta, key) {
62
- const mapped = ownLookup(meta.columnMap, key);
63
- if (mapped)
64
- return mapped;
65
- const snake = camelToSnake(key);
66
- if (meta.reverseColumnMap && ownLookup(meta.reverseColumnMap, snake))
67
- return snake;
68
- if (meta.allColumns?.includes(snake))
69
- return snake;
70
- return undefined;
71
- }
72
- /**
73
- * Resolve a user-supplied key to a relation's CANONICAL name and definition, or
74
- * `undefined` when the key names no relation on the table.
75
- *
76
- * The relation-name half of the rule {@link resolveColumnName} states for
77
- * columns, and deliberately the same shape: the declared name first, else
78
- * `snakeToCamel(key)` accepted ONLY when that names a real relation.
79
- * `snakeToCamel` is idempotent on an already-camel string, so a canonical key
80
- * takes the first branch and this is a no-op for every existing caller.
81
- *
82
- * WHY IT EXISTS. A relation has one declared name, `ripeningChecks`, while the
83
- * DDL anyone reads has only the TABLE name, `ripening_checks`. Writing back
84
- * what the schema shows therefore failed with E005 in `with`, E003 in a
85
- * relation filter, and E005 in `orderBy`, on names the error text was already
86
- * computing correctly ("Did you mean ...?"). A system that can name the
87
- * intended relation can accept it.
88
- *
89
- * NOT A GUESS, for the same reason the column rule is not: the transformed name
90
- * is accepted only when it is a real declared relation, so an unknown key still
91
- * fails and a typo is still a typo. Exact match wins first, so a schema that
92
- * literally declares `ripening_checks` keeps it, even alongside a
93
- * `ripeningChecks`.
94
- *
95
- * The RESULT KEY is the canonical name, not the caller's spelling, matching the
96
- * column side (`select: { ledger_handle: true }` already returns
97
- * `{ ledgerHandle }`). Resolving here rather than normalizing the args up front
98
- * also means both spellings share one SQL-cache entry instead of minting two
99
- * templates for one query.
100
- *
101
- * Prototype-safe via {@link ownLookup}, so `__proto__` cannot name a relation.
102
- */
103
- export function resolveRelation(relations, key) {
104
- const direct = ownLookup(relations, key);
105
- if (direct !== undefined)
106
- return { name: key, def: direct };
107
- const camel = snakeToCamel(key);
108
- if (camel === key)
109
- return undefined;
110
- const mapped = ownLookup(relations, camel);
111
- return mapped === undefined ? undefined : { name: camel, def: mapped };
112
- }
113
- /**
114
- * {@link resolveRelation} when only the definition is wanted: a drop-in for the
115
- * `ownLookup(meta.relations, key)` it replaces, with the same signature and the
116
- * same `undefined` on a miss.
117
- */
118
- export function resolveRelationDef(relations, key) {
119
- return resolveRelation(relations, key)?.def;
120
- }
121
- // ---------------------------------------------------------------------------
122
- // Caller-controlled key ORDER, canonicalized
123
- // ---------------------------------------------------------------------------
124
- /**
125
- * THE canonical order for a caller-supplied set of columns: the table's own
126
- * `allColumns` order, which is the order `omit` and the default projection
127
- * already produce.
128
- *
129
- * ## The failure mode this exists to close, and it is NOT arity
130
- *
131
- * Every distinct SQL text Turbine emits is parsed on the server as a NAMED
132
- * prepared statement and is never DEALLOCATEd. The arity rule
133
- * (`markVariableArity`) bounds the shapes whose LENGTH the caller picks. It
134
- * does nothing about the shapes whose length is fixed and whose ORDER the
135
- * caller picks, and those grow the SQL text just as freely: `select: { a, b }`
136
- * and `select: { b, a }` are the same query and two different statements.
137
- *
138
- * Measured against PostgreSQL 16 on a SEVEN-column table, one connection, with
139
- * the arity fix already landed:
140
- *
141
- * baseline prepared= 0 CachedPlanSource= 0.0 MB
142
- * after 5040 `select` permutations prepared= 5040 CachedPlanSource=39.4 MB
143
- * after 300 varying-arity ORs prepared= 5040 CachedPlanSource=39.4 MB
144
- * after 5040 `distinct` permutations prepared=10080 CachedPlanSource=59.1 MB
145
- * 720 reordered PATCH bodies (update) prepared= 720 CachedPlanSource= 2.8 MB
146
- *
147
- * The write row is the realistic one: `JSON.parse` preserves insertion order,
148
- * so `update({ where, data: JSON.parse(reqBody) })` hands a request body the
149
- * SET-clause column order for free. No arrays, no unusual input, no opt-in.
150
- *
151
- * The reachable space is ORDERED subsets, sum over k of k! * C(n,k): 9.9e6 for
152
- * 10 columns, 6.6e18 for 20. Canonicalizing collapses each permutation class to
153
- * one statement, leaving the UNORDERED subsets (2^n) that `omit` has always
154
- * had.
155
- *
156
- * ## Why ordering is the right remedy here rather than withholding the name
157
- *
158
- * A projection's SELECT-list order is not semantically meaningful to Turbine:
159
- * rows are assembled by NAME (`parseRow`, `jsonScalarPairs` and
160
- * `buildRelationShape` all key off the same resolved list), so reordering it
161
- * changes no value. Where an order IS meaningful (`orderBy`, and `DISTINCT ON`,
162
- * whose list is re-emitted as an ORDER BY prefix), the statement is sent
163
- * unnamed instead. See `MAX_NAMED_ORDER_KEYS` in filters.ts and the `distinct`
164
- * mark in builder.ts.
165
- *
166
- * Duplicates collapse, which is the other half of "canonical": two spellings of
167
- * one column (`userId` and `user_id`, both legal on an introspected schema)
168
- * used to emit that column twice in the SELECT list.
169
- *
170
- * Cost is one Set of the projected columns plus one pass over `allColumns`, on
171
- * a path that already walks the caller's keys.
172
- *
173
- * @param meta the table the columns belong to; without `allColumns` there is no
174
- * canonical order to appeal to and the input is returned untouched.
175
- * @param columns already-resolved snake_case column names.
176
- */
177
- export function canonicalColumnOrder(meta, columns) {
178
- const all = meta.allColumns;
179
- if (all === undefined || columns.length < 2)
180
- return columns;
181
- const wanted = new Set(columns);
182
- const ordered = [];
183
- for (const col of all) {
184
- if (wanted.delete(col))
185
- ordered.push(col);
186
- }
187
- // A resolved column absent from `allColumns` is only reachable from
188
- // hand-built metadata whose maps disagree with each other. Keep it (in the
189
- // caller's relative order) rather than silently dropping it from the
190
- // projection: this function reorders, it never decides what is projected.
191
- if (wanted.size > 0) {
192
- for (const col of columns) {
193
- if (wanted.delete(col))
194
- ordered.push(col);
195
- }
196
- }
197
- return ordered;
198
- }
199
- /**
200
- * {@link canonicalColumnOrder} for a write's `data` entries: same order, same
201
- * reason, two deliberate differences.
202
- *
203
- * DUPLICATES ARE KEPT. Two keys resolving to one column (`{ userId, user_id }`)
204
- * is a caller error that PostgreSQL reports precisely ("multiple assignments to
205
- * same column", 42701, and the INSERT equivalent). Collapsing them here would
206
- * turn that error into a silent write of whichever value survived, so the entry
207
- * list is REORDERED and never shortened. A stable sort keeps such a pair
208
- * adjacent and in the caller's relative order, so the engine still sees, and
209
- * still rejects, both assignments.
210
- *
211
- * THE KEY SPELLING IS PRESERVED. Everything downstream (`coerceWriteValue`,
212
- * `buildSetClause`, `toSqlColumn`) re-resolves the caller's key itself, so only
213
- * the ORDER of the entries changes here, never their content.
214
- *
215
- * A key that resolves to no column sorts LAST, in the caller's relative order.
216
- * It is about to raise E003 from the SQL builder either way, and the builder is
217
- * where that error belongs; ordering must not pre-empt it with a worse one.
218
- */
219
- export function canonicalWriteEntries(meta, entries) {
220
- const all = meta.allColumns;
221
- if (all === undefined || entries.length < 2)
222
- return entries;
223
- const index = new Map();
224
- for (let i = 0; i < all.length; i++)
225
- index.set(all[i], i);
226
- const rank = (key) => {
227
- const column = resolveColumnName(meta, key);
228
- const at = column === undefined ? undefined : index.get(column);
229
- return at ?? Number.MAX_SAFE_INTEGER;
230
- };
231
- // Ranks are computed once per entry rather than inside the comparator, which
232
- // would re-resolve every key O(k log k) times.
233
- const ranked = entries.map((entry, at) => ({ entry, rank: rank(entry[0]), at }));
234
- // `at` breaks ties explicitly rather than relying on sort stability, so two
235
- // spellings of one column, and every unresolvable key, keep the order the
236
- // caller wrote them in.
237
- ranked.sort((a, b) => a.rank - b.rank || a.at - b.at);
238
- return ranked.map((r) => r.entry);
239
- }
240
- // ---------------------------------------------------------------------------
241
- // Internally-synthesized combinator brand
242
- // ---------------------------------------------------------------------------
243
- /**
244
- * Brands a WHERE object whose `AND` / `OR` array Turbine ITSELF synthesized,
245
- * rather than one the caller wrote.
246
- *
247
- * The distinction matters for exactly one rule: a caller-written combinator
248
- * array is treated as a VARIABLE-ARITY shape and its statement is sent unnamed
249
- * (see `markVariableArity` in where.ts, and `acquireSql` in builder.ts).
250
- * Turbine's own wrappers, the `{ AND: [userWhere, globalFilter] }` the
251
- * global-filter merge produces and the `{ AND: [where, correlation] }` the
252
- * batched loader produces, have a FIXED arity of two, decided by Turbine, not
253
- * reachable from a request body. Counting them would have taken every query on
254
- * a table with a configured global filter off named prepared statements, i.e.
255
- * penalised precisely the multi-tenant setups the rule exists to protect.
256
- *
257
- * A `Symbol.for` key for the same cross-copy-identity reason the warn registry
258
- * uses one (an ESM and a CJS copy of this module in one process must agree),
259
- * and a SYMBOL rather than a string key so `Object.keys` (which is what every
260
- * where walker enumerates) never sees it and no emitted SQL can change.
261
- */
262
- export const INTERNAL_COMBINATOR = Symbol.for('turbine.internalCombinator');
263
- /** Shared by every brand: a frozen descriptor saves an allocation per branded where. */
264
- const INTERNAL_COMBINATOR_DESCRIPTOR = Object.freeze({
265
- value: true,
266
- enumerable: false,
267
- configurable: true,
268
- });
269
- /** Tag `where` as carrying a Turbine-synthesized combinator, and return it. */
270
- export function markInternalCombinator(where) {
271
- Object.defineProperty(where, INTERNAL_COMBINATOR, INTERNAL_COMBINATOR_DESCRIPTOR);
272
- return where;
273
- }
274
- /** Was this WHERE object's combinator synthesized by Turbine? */
275
- export function isInternalCombinator(where) {
276
- return (typeof where === 'object' && where !== null && where[INTERNAL_COMBINATOR] === true);
277
- }
278
- /**
279
- * Escape single quotes for use as string keys in json_build_object().
280
- * Doubles single quotes per SQL quoting rules.
281
- */
282
- export function escSingleQuote(s) {
283
- return s.replace(/'/g, "''");
284
- }
285
- const LIKE_META = /[\\%_]/;
286
- const LIKE_META_G = /[\\%_]/g;
287
- /**
288
- * Escape LIKE pattern metacharacters: %, _, and \.
289
- * Must be used with `ESCAPE '\'` in the LIKE clause.
290
- */
291
- export function escapeLike(value) {
292
- // One pass, and none at all for the common operand with no metacharacter.
293
- // Identical output to escaping `\` then `%` then `_` in turn: the backslashes
294
- // the first step adds are never `%` or `_`, so the steps never interact.
295
- return LIKE_META.test(value) ? value.replace(LIKE_META_G, '\\$&') : value;
296
- }
297
- // ---------------------------------------------------------------------------
298
- // LRU cache, bounded SQL template cache to prevent memory leaks
299
- // ---------------------------------------------------------------------------
300
- /**
301
- * Simple LRU (Least Recently Used) cache with a fixed maximum size.
302
- * When the cache exceeds maxSize, the oldest (least recently used) entry is
303
- * evicted. Uses Map insertion order, so EVICTION is O(1).
304
- *
305
- * The access-order reorder in {@link get} is not: `Map.delete` + `Map.set`
306
- * leaves a tombstone, and V8 rehashes the whole table once live plus deleted
307
- * entries reach capacity, so the reorder amortizes to O(capacity) per hit.
308
- * At the 1,000-entry default that measured 1,356 ns against 2.6 ns for a plain
309
- * `Map.get`, on the hottest lookup in the SQL build. See {@link get} for why
310
- * skipping it below capacity is not merely an optimization but exact.
311
- */
312
- export class LRUCache {
313
- maxSize;
314
- cache = new Map();
315
- constructor(maxSize) {
316
- this.maxSize = maxSize;
317
- }
318
- get(key) {
319
- const value = this.cache.get(key);
320
- // Access order is only ever CONSUMED by eviction (`set` drops the first
321
- // key once the cache is full), so while it is still filling, maintaining
322
- // that order cannot change WHICH entries are present: nothing is evicted,
323
- // and the reorder is pure cost. So it starts the moment the cache is full,
324
- // and from then on every hit reorders exactly as before.
325
- //
326
- // What is traded, stated plainly: reads that happened while the cache was
327
- // filling are not reflected in the order, so the first evictions after it
328
- // fills can drop an entry that was hot early rather than the true
329
- // least-recently-used one. Reads after that point are ordered normally, so
330
- // the effect does not accumulate, and the worst case is one extra SQL
331
- // rebuild on the next miss. This cache decides speed, never results.
332
- if (value !== undefined && this.cache.size >= this.maxSize) {
333
- // Move to end (most recently used)
334
- this.cache.delete(key);
335
- this.cache.set(key, value);
336
- }
337
- return value;
338
- }
339
- set(key, value) {
340
- if (this.cache.has(key)) {
341
- this.cache.delete(key);
342
- }
343
- else if (this.cache.size >= this.maxSize) {
344
- // Delete oldest (first) entry
345
- const firstKey = this.cache.keys().next().value;
346
- if (firstKey !== undefined)
347
- this.cache.delete(firstKey);
348
- }
349
- this.cache.set(key, value);
350
- }
351
- get size() {
352
- return this.cache.size;
353
- }
354
- }
355
- /**
356
- * FNV-1a 64-bit hash returning 16 lowercase hex chars.
357
- * Single-loop string iteration. Uses BigInt for 64-bit math.
358
- *
359
- * @internal Exported for testing only.
360
- */
361
- export function fnv1a64Hex(s) {
362
- // FNV-1a offset basis and prime for 64-bit
363
- let hash = 0xcbf29ce484222325n;
364
- const prime = 0x100000001b3n;
365
- const mask = 0xffffffffffffffffn; // 64-bit mask
366
- for (let i = 0; i < s.length; i++) {
367
- hash ^= BigInt(s.charCodeAt(i));
368
- hash = (hash * prime) & mask;
369
- }
370
- return hash.toString(16).padStart(16, '0');
371
- }
372
- /**
373
- * Derive a prepared-statement name from a SQL string.
374
- * Format: `t_<16hex>`, always 18 chars, well under NAMEDATALEN (63).
375
- *
376
- * @internal Exported for testing only.
377
- */
378
- export function sqlToPreparedName(sql) {
379
- return `t_${fnv1a64Hex(sql)}`;
380
- }
381
- /**
382
- * How many distinct statement names one process hands out. Every connection
383
- * keeps each named statement it has prepared, at 9 to 45 KB of server memory
384
- * apiece, until the connection closes, so the number of names is what bounds
385
- * that memory. A statement past the budget is sent unnamed: parsed on every
386
- * execution and never kept, which costs a few microseconds on a cheap query.
387
- */
388
- export const PREPARED_STATEMENT_BUDGET = 200;
389
- /** `Symbol.for` so the ESM and CJS copies of this module share one budget. */
390
- const PREPARED_NAMES = Symbol.for('turbine.preparedStatementNames');
391
- function preparedNames() {
392
- const holder = globalThis;
393
- let names = holder[PREPARED_NAMES];
394
- if (!names) {
395
- names = new Set();
396
- holder[PREPARED_NAMES] = names;
397
- }
398
- return names;
399
- }
400
- /**
401
- * The prepared-statement name for `sql`, or `''` (send it unnamed) once the
402
- * process has named {@link PREPARED_STATEMENT_BUDGET} other statements.
403
- *
404
- * The first shapes a process runs keep their names for its lifetime, which in
405
- * practice are its hot shapes. A server-side `DEALLOCATE` cannot replace this:
406
- * a pooled query does not know which connection it will run on, and a
407
- * connection keeps every name it ever prepared.
408
- */
409
- export function boundedPreparedName(sql) {
410
- return claimPreparedName(sqlToPreparedName(sql));
411
- }
412
- /**
413
- * Claim an already derived statement name from the same budget as
414
- * {@link boundedPreparedName}: `name` itself, or `''` (send it unnamed) once
415
- * the budget is spent. `sqlComment`'s `c_` names (query/sql-comment.ts) are
416
- * claimed here, so a commented statement costs one slot like any other.
417
- */
418
- export function claimPreparedName(name) {
419
- const names = preparedNames();
420
- if (names.has(name))
421
- return name;
422
- if (names.size >= PREPARED_STATEMENT_BUDGET)
423
- return '';
424
- names.add(name);
425
- return name;
426
- }
427
- /** @internal Tests only: forget every name handed out. */
428
- export function resetPreparedNameBudget() {
429
- preparedNames().clear();
430
- }
431
- function argsRewriteError(model, action, path) {
432
- return new TypeError(`[turbine] middleware cannot change \`params.${path}\` on ${model}.${action}: the query is compiled from the ` +
433
- 'arguments the caller passed, so a change made in middleware would not reliably reach it. Put the ' +
434
- 'condition in the query itself, or use `globalFilters` for a filter that applies to every query.');
435
- }
436
- /** Plain objects and arrays are copied; a Date, Buffer, class instance or other value is shared as it is. */
437
- function isPlainContainer(value) {
438
- if (value === null || typeof value !== 'object')
439
- return false;
440
- if (Array.isArray(value))
441
- return true;
442
- const proto = Object.getPrototypeOf(value);
443
- return proto === Object.prototype || proto === null;
444
- }
445
- /** Nesting past this is shared, not copied, so a cyclic object cannot recurse without end. */
446
- const MIDDLEWARE_ARGS_MAX_DEPTH = 100;
447
- /**
448
- * A copy of `value` that middleware may read, spread, serialize or
449
- * `structuredClone`: plain objects and arrays are copied at every depth, and
450
- * everything else (Date, Buffer, bigint, symbol, class instance) is shared.
451
- * Symbol-keyed properties are copied by descriptor, so the markers the
452
- * pipeline reads (the internal-combinator brand, the inclusive-cursor flag,
453
- * column and expression brands) are on the copy exactly as on the original,
454
- * non-enumerable ones included.
455
- */
456
- function copyArgs(value, depth) {
457
- if (depth > MIDDLEWARE_ARGS_MAX_DEPTH || !isPlainContainer(value))
458
- return value;
459
- let out;
460
- if (Array.isArray(value)) {
461
- const items = new Array(value.length);
462
- // A long list of ids is the common big argument; keep its scalars off the call path.
463
- for (let i = 0; i < value.length; i++) {
464
- const item = value[i];
465
- items[i] = item !== null && typeof item === 'object' ? copyArgs(item, depth + 1) : item;
466
- }
467
- out = items;
468
- }
469
- else {
470
- out = Object.getPrototypeOf(value) === null ? Object.create(null) : {};
471
- for (const key of Object.keys(value)) {
472
- const item = value[key];
473
- const copied = item !== null && typeof item === 'object' ? copyArgs(item, depth + 1) : item;
474
- // `__proto__` from JSON.parse is an own key; assigning it would set the prototype.
475
- if (key === '__proto__')
476
- Object.defineProperty(out, key, { value: copied, enumerable: true, writable: true, configurable: true });
477
- else
478
- out[key] = copied;
479
- }
480
- }
481
- for (const sym of Object.getOwnPropertySymbols(value)) {
482
- Object.defineProperty(out, sym, Object.getOwnPropertyDescriptor(value, sym));
483
- }
484
- return out;
485
- }
486
- /**
487
- * Where `b` first differs from `a`, as a path suffix (`.where.id`, or `''` for
488
- * the values themselves), or undefined when they are structurally equal. The
489
- * suffix is built on the way back out, so an equal pair costs no string work.
490
- */
491
- function argsDifference(a, b, depth) {
492
- if (Object.is(a, b))
493
- return undefined;
494
- if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object')
495
- return '';
496
- if (a instanceof Date || b instanceof Date) {
497
- return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime()) ? undefined : '';
498
- }
499
- if (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {
500
- if (!(ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) || a.byteLength !== b.byteLength)
501
- return '';
502
- const x = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
503
- const y = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
504
- for (let i = 0; i < x.length; i++)
505
- if (x[i] !== y[i])
506
- return '';
507
- return undefined;
508
- }
509
- if (a instanceof RegExp || b instanceof RegExp)
510
- return String(a) === String(b) ? undefined : '';
511
- if (a instanceof Map || a instanceof Set || b instanceof Map || b instanceof Set)
512
- return '';
513
- if (Array.isArray(a) !== Array.isArray(b) || depth > MIDDLEWARE_ARGS_MAX_DEPTH)
514
- return '';
515
- if (Array.isArray(a)) {
516
- const other = b;
517
- const shared = Math.min(a.length, other.length);
518
- for (let i = 0; i < shared; i++) {
519
- if (Object.is(a[i], other[i]))
520
- continue;
521
- const inner = argsDifference(a[i], other[i], depth + 1);
522
- if (inner !== undefined)
523
- return `.${i}${inner}`;
524
- }
525
- return a.length === other.length ? undefined : `.${shared}`;
526
- }
527
- const left = a;
528
- const right = b;
529
- for (const key of Object.keys(left)) {
530
- if (!Object.hasOwn(right, key))
531
- return `.${key}`;
532
- const inner = argsDifference(left[key], right[key], depth + 1);
533
- if (inner !== undefined)
534
- return `.${key}${inner}`;
535
- }
536
- for (const key of Object.keys(right))
537
- if (!Object.hasOwn(left, key))
538
- return `.${key}`;
539
- return undefined;
540
- }
541
- const MIDDLEWARE_ARGS = new WeakMap();
542
- /** The key Node's `util.inspect` looks for, from the global registry so no `node:` import is needed. */
543
- const NODE_INSPECT = Symbol.for('nodejs.util.inspect.custom');
544
- /** Makes `console.log(params)` show the values rather than an accessor. Not own, so a spread of `params` never carries it. */
545
- const MIDDLEWARE_PARAMS_PROTOTYPE = Object.defineProperty({}, NODE_INSPECT, {
546
- value(_depth, options, inspect) {
547
- return inspect({ model: this.model, action: this.action, args: this.args }, options);
548
- },
549
- });
550
- /**
551
- * The `params` a middleware receives. `params.args` is a plain copy of the
552
- * caller's args, made when it is first read, so middleware can read it, spread
553
- * it, serialize it and `structuredClone` it, and one that never reads it pays
554
- * nothing.
555
- *
556
- * It is a copy because the query is compiled from the caller's args, not from
557
- * what middleware sees. A change to the copy would never reach the query, so
558
- * {@link assertMiddlewareArgsKept} refuses it, naming the path, when the
559
- * middleware calls `next`. That check compares contents, which is why the copy
560
- * is not frozen: a frozen object ignores a write silently in a script that is
561
- * not in strict mode, and a filter added there would be dropped without a word.
562
- * Assigning to `params.args` itself throws at once.
563
- */
564
- export function readOnlyMiddlewareParams(model, action, args) {
565
- const state = { model, action, original: args, copy: undefined };
566
- const params = {
567
- __proto__: MIDDLEWARE_PARAMS_PROTOTYPE,
568
- model,
569
- action,
570
- get args() {
571
- if (state.copy === undefined)
572
- state.copy = copyArgs(args, 0);
573
- return state.copy;
574
- },
575
- set args(_replacement) {
576
- throw argsRewriteError(model, action, 'args');
577
- },
578
- };
579
- MIDDLEWARE_ARGS.set(params, state);
580
- return params;
581
- }
582
- /**
583
- * Refuse a `next(p)` whose `p.args` is not the caller's args: one that
584
- * middleware changed in place, or replaced with an object that differs from
585
- * them. A copy that is structurally equal passes (`structuredClone(params.args)`,
586
- * `{ ...params.args }`), because nothing it would change is lost. Throws a
587
- * TypeError naming the first path that differs.
588
- */
589
- export function assertMiddlewareArgsKept(handedOut, passed) {
590
- const state = MIDDLEWARE_ARGS.get(handedOut);
591
- if (passed === handedOut) {
592
- if (handedOut.model !== state.model)
593
- throw argsRewriteError(state.model, state.action, 'model');
594
- if (handedOut.action !== state.action)
595
- throw argsRewriteError(state.model, state.action, 'action');
596
- // Nothing has read the args, so nothing could have changed them.
597
- if (state.copy === undefined)
598
- return;
599
- }
600
- const given = passed?.args;
601
- if (given === state.original)
602
- return;
603
- const changed = argsDifference(state.original, given, 0);
604
- if (changed !== undefined)
605
- throw argsRewriteError(state.model, state.action, `args${changed}`);
606
- }
607
- /** Whether `pool` is a node-postgres `Pool`, whose checkouts are real backend connections. */
608
- export function isNodePostgresPool(pool) {
609
- const Pool = pg.Pool;
610
- return typeof Pool === 'function' && pool instanceof Pool;
611
- }
612
- /** Whether `client` is a node-postgres connection a cancel request can reach. */
613
- export function canCancelBackend(client) {
614
- const c = client;
615
- return (typeof pg.Connection === 'function' &&
616
- !!c &&
617
- typeof c.processID === 'number' &&
618
- typeof c.secretKey === 'number' &&
619
- (typeof c.port === 'number' || typeof c.port === 'string'));
620
- }
621
- /**
622
- * Ask the server to cancel whatever `client`'s backend is running, with the
623
- * protocol's CancelRequest: a separate short connection carrying the backend's
624
- * process id and secret key. No login, no session state, and a pooler forwards
625
- * it to the right server backend, which `pg_cancel_backend(pid)` through a
626
- * pooler would not.
627
- *
628
- * Resolves `true` once the server has closed the cancel connection, i.e. has
629
- * signalled the backend; `false` when the request could not be delivered
630
- * within `waitMs`. A cancel that arrives after the statement finished is
631
- * ignored by the server.
632
- */
633
- export function sendCancelRequest(client, waitMs) {
634
- if (!canCancelBackend(client))
635
- return Promise.resolve(false);
636
- const target = client;
637
- const Connection = pg.Connection;
638
- return new Promise((resolve) => {
639
- let con;
640
- let sent = false;
641
- let done = false;
642
- const finish = (delivered) => {
643
- if (done)
644
- return;
645
- done = true;
646
- clearTimeout(timer);
647
- try {
648
- con?.stream?.destroy?.();
649
- }
650
- catch {
651
- // already closed
652
- }
653
- resolve(delivered);
654
- };
655
- const timer = setTimeout(() => finish(false), waitMs);
656
- try {
657
- con = new Connection({ ssl: target.ssl, sslNegotiation: target.sslNegotiation });
658
- const send = () => {
659
- sent = true;
660
- con?.cancel(target.processID, target.secretKey);
661
- };
662
- con.on('error', () => finish(false));
663
- con.on('end', () => finish(sent));
664
- con.on('connect', () => {
665
- if (!target.ssl)
666
- send();
667
- else if (target.sslNegotiation !== 'direct')
668
- con?.requestSsl();
669
- });
670
- con.on('sslconnect', send);
671
- const host = typeof target.host === 'string' ? target.host : undefined;
672
- if (host?.startsWith('/'))
673
- con.connect(`${host}/.s.PGSQL.${String(target.port)}`);
674
- else
675
- con.connect(target.port, host);
676
- }
677
- catch {
678
- finish(false);
679
- }
680
- });
681
- }
682
- /** Known operator keys, used to detect operator objects vs plain values */
683
- export const OPERATOR_KEYS = new Set([
684
- 'equals',
685
- 'gt',
686
- 'gte',
687
- 'lt',
688
- 'lte',
689
- 'not',
690
- 'in',
691
- 'notIn',
692
- 'contains',
693
- 'startsWith',
694
- 'endsWith',
695
- 'mode',
696
- ]);
697
- // ---------------------------------------------------------------------------
698
- // Composite key correlation helper
699
- // ---------------------------------------------------------------------------
700
- /**
701
- * Build a correlation clause joining columns between two table references.
702
- * Handles both single-column (string) and multi-column (string[]) foreign keys.
703
- *
704
- * For single-column: `"alias"."col" = "parent"."col"`
705
- * For multi-column: `"alias"."col_a" = "parent"."ref_a" AND "alias"."col_b" = "parent"."ref_b"`
706
- */
707
- export function buildCorrelation(leftRef, leftColumns, rightRef, rightColumns) {
708
- const leftCols = Array.isArray(leftColumns) ? leftColumns : [leftColumns];
709
- const rightCols = Array.isArray(rightColumns) ? rightColumns : [rightColumns];
710
- return leftCols
711
- .map((col, i) => `${leftRef}.${quoteIdent(col)} = ${rightRef}.${quoteIdent(rightCols[i])}`)
712
- .join(' AND ');
713
- }
714
- /**
715
- * Render a JS `Date` as a TIME-OF-DAY literal for a `time` / `timetz` column.
716
- *
717
- * Which time of day? The **UTC** components of the Date, never the process
718
- * local zone. That is what Prisma does (`new Date('1970-01-01T09:00:00Z')`
719
- * written to a `@db.Time(6)` column stores `09:00:00`), and the affected
720
- * consumers are porting from Prisma, so Prisma is the contract. It is also the
721
- * only choice that round-trips: the same Date produces the same literal no
722
- * matter where the process runs.
723
- *
724
- * `timetz` gets an explicit `+00:00`, because the value's zone IS UTC and
725
- * omitting it would let Postgres attach the session's `TimeZone` instead.
726
- * Fractional seconds are emitted only when non-zero, so an even-second Date
727
- * binds the plain `HH:MM:SS` form.
728
- */
729
- export function toTimeOfDayLiteral(value, kind) {
730
- const pad = (n, width = 2) => String(n).padStart(width, '0');
731
- const ms = value.getUTCMilliseconds();
732
- const literal = `${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}` +
733
- (ms === 0 ? '' : `.${pad(ms, 3)}`);
734
- return kind === 'timetz' ? `${literal}+00:00` : literal;
735
- }
736
- /** Render the UTC calendar date of a `Date` as `YYYY-MM-DD`. */
737
- function utcDatePart(value) {
738
- const year = value.getUTCFullYear();
739
- const y = year < 0 ? `-${String(-year).padStart(4, '0')}` : String(year).padStart(4, '0');
740
- const pad = (n) => String(n).padStart(2, '0');
741
- return `${y}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())}`;
742
- }
743
- /**
744
- * Render a JS `Date` as a literal for a zone-less `date` / `timestamp` column,
745
- * using the value's **UTC** components.
746
- *
747
- * This is the write-side mirror of `parseDbDate`, which reads an offset-less
748
- * database value back as UTC. Without it the driver serializes the Date with
749
- * the PROCESS's offset (`prepareValue` → `dateToString`), so a `timestamp`
750
- * column is not round-trip stable outside a UTC process: writing
751
- * `2026-07-25T00:00Z` from `America/Los_Angeles` stores
752
- * `2026-07-24 17:00:00` and reads back as `2026-07-24T17:00Z`. It also matches
753
- * the choice {@link toTimeOfDayLiteral} already makes for `time` columns, and
754
- * Prisma, which writes UTC components to zone-less columns.
755
- *
756
- * `timestamptz` is NOT handled here (and must not be): it stores a real
757
- * instant, so the driver's local-offset string is already correct.
758
- */
759
- export function toLocalDateTimeLiteral(value, kind) {
760
- const datePart = utcDatePart(value);
761
- if (kind === 'date')
762
- return datePart;
763
- return `${datePart} ${toTimeOfDayLiteral(value, 'time')}`;
764
- }
765
- /**
766
- * Classify a column's database type for temporal bind rewriting.
767
- *
768
- * `utcDateTimes: false` restricts the classification to the time-of-day types,
769
- * whose rewrite is a hard-error fix (Postgres rejects an ISO timestamp for a
770
- * `time` column outright) rather than a value correction.
771
- */
772
- export function temporalBindKind(dbType, utcDateTimes = true) {
773
- const timeKind = timeOfDayKind(dbType);
774
- if (timeKind)
775
- return timeKind;
776
- return utcDateTimes ? localDateTimeKind(dbType) : null;
777
- }
778
- /**
779
- * Rewrite one bound value for a temporal column: a JS `Date` on a `time` /
780
- * `timetz` / `date` / `timestamp` column becomes the corresponding UTC literal,
781
- * and an array of Dates on such a column is rewritten element-wise (the
782
- * per-element rewrite is what a `time[]` column needs, and matches the scalar
783
- * case rather than silently binding an ISO timestamp).
784
- *
785
- * Everything else, every non-Date, every non-temporal column, and every
786
- * `timestamptz` column, is returned by IDENTITY, so this is a byte-for-byte
787
- * no-op outside the shapes above.
788
- */
789
- export function coerceTemporalValue(dbType, value, utcDateTimes = true) {
790
- const isDate = value instanceof Date;
791
- if (!isDate && !Array.isArray(value))
792
- return value;
793
- if (isDate && Number.isNaN(value.getTime()))
794
- return value;
795
- // An array value is either an `in`/`notIn` list on a scalar temporal column
796
- // (type already the element type) or the value of an array column, whose
797
- // introspected type is the `_time` / `_timestamp` array spelling.
798
- const kind = temporalBindKind(isDate ? dbType : arrayElementDbType(dbType), utcDateTimes);
799
- if (!kind)
800
- return value;
801
- if (isDate)
802
- return renderTemporal(value, kind);
803
- // Rewrite only if the list actually holds a Date, so a string list stays
804
- // byte-identical (and the same array instance is returned).
805
- if (!value.some((v) => v instanceof Date))
806
- return value;
807
- return value.map((v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? renderTemporal(v, kind) : v));
808
- }
809
- /** `_time` → `time`, `time[]` → `time`, anything else unchanged. */
810
- function arrayElementDbType(dbType) {
811
- if (!dbType)
812
- return dbType;
813
- if (dbType.startsWith('_'))
814
- return dbType.slice(1);
815
- return dbType.endsWith('[]') ? dbType.slice(0, -2) : dbType;
816
- }
817
- function renderTemporal(value, kind) {
818
- return kind === 'date' || kind === 'timestamp'
819
- ? toLocalDateTimeLiteral(value, kind)
820
- : toTimeOfDayLiteral(value, kind);
821
- }
822
- /**
823
- * Matches an explicit timezone suffix on a date-time string: a trailing `Z`
824
- * or a `±HH`, `±HHMM`, `±HH:MM` offset.
825
- */
826
- const TZ_SUFFIX_RE = /(?:Z|[+-]\d{2}(?::?\d{2})?)$/;
827
- const COLON_CHAR = 58;
828
- const PLUS_CHAR = 43;
829
- const MINUS_CHAR = 45;
830
- /** `0`-`9` as a char code. */
831
- function isDigitCode(code) {
832
- return code >= 48 && code <= 57;
833
- }
834
- /**
835
- * Parse a database date-time string deterministically.
836
- *
837
- * Postgres `timestamp` (without time zone) values arrive with no offset -
838
- * both from the driver and from `json_agg`/`json_build_object` subquery JSON
839
- * (`2026-07-07T17:15:41.896`). JavaScript's `new Date()` interprets such
840
- * strings in the SERVER'S LOCAL TIME ZONE, so the same row parses to a
841
- * different instant depending on where the code runs. The universal ORM
842
- * convention (Prisma, Rails, Django) is to treat offset-less timestamps as
843
- * UTC, that is also the only interpretation that round-trips: Postgres
844
- * stores exactly the wall-clock fields you sent.
845
- *
846
- * Strings that carry an explicit offset (`timestamptz` output) are parsed
847
- * as-is.
848
- */
849
- export function parseDbDate(value) {
850
- const date = parseDbDateCommon(value);
851
- // The shapes JS cannot parse (a BC year, an offset with seconds, a year past
852
- // 9999) come out invalid; only those pay for the general parse.
853
- return Number.isNaN(date.getTime()) ? (parseDbDateGeneral(value) ?? date) : date;
854
- }
855
- function parseDbDateCommon(value) {
856
- // Fast path for the shape `timestamptz` arrives in, a trailing `±HH:MM`
857
- // offset (`2026-07-07T17:15:41.896+00:00`). It is exactly the general path's
858
- // answer for that shape, not an approximation of it: the string contains a
859
- // ':' (at length-3), TZ_SUFFIX_RE matches, and neither normalizing replace
860
- // below can fire (the first needs four digits after the sign, the second two
861
- // digits at the very end after it), so that path also ends in
862
- // `new Date(value)`. All six offset characters are checked, so a near miss
863
- // (`+0a:00`, `05:30` without a sign) still takes the general path. It skips
864
- // one regex test and two regex replaces per value, which on a nested read is
865
- // the single largest cost in the decode. The invalid-date fallback in
866
- // parseDbDate still runs on the result, so a BC or five-digit year is
867
- // unchanged.
868
- const n = value.length;
869
- if (n >= 6 && value.charCodeAt(n - 3) === COLON_CHAR) {
870
- const sign = value.charCodeAt(n - 6);
871
- if ((sign === PLUS_CHAR || sign === MINUS_CHAR) &&
872
- isDigitCode(value.charCodeAt(n - 5)) &&
873
- isDigitCode(value.charCodeAt(n - 4)) &&
874
- isDigitCode(value.charCodeAt(n - 2)) &&
875
- isDigitCode(value.charCodeAt(n - 1))) {
876
- return new Date(value);
877
- }
878
- }
879
- // Date-only values (`2026-07-07`, from `date` columns in json_agg output)
880
- // have no time to zone-pin, and their `-07` tail must not be read as an
881
- // offset. JS parses bare ISO dates as UTC midnight already.
882
- if (!value.includes(':'))
883
- return new Date(value);
884
- if (TZ_SUFFIX_RE.test(value)) {
885
- // JS Date can't parse colon-less (`-0430`) or bare-hour (`+02`) offsets -
886
- // normalize both to `±HH:MM`. Postgres emits the bare-hour form for
887
- // whole-hour zones in some text outputs.
888
- return new Date(value.replace(/([+-]\d{2})(\d{2})$/, '$1:$2').replace(/([+-]\d{2})$/, '$1:00'));
889
- }
890
- // normalize `YYYY-MM-DD HH:MM:SS` (driver form) to ISO before pinning UTC
891
- return new Date(`${value.replace(' ', 'T')}Z`);
892
- }
893
- const DB_DATE_GENERAL_RE = /^(\d{4,})-(\d\d)-(\d\d)(?:[T ](\d\d):(\d\d):(\d\d)(\.\d+)?)?(?:(Z)|([+-])(\d\d)(?::?(\d\d))?(?::?(\d\d))?)?( BC)?$/;
894
- /**
895
- * The Postgres renderings JS `Date` cannot parse: a ` BC` suffix, a
896
- * local-mean-time offset with seconds (`-04:56:02`, any zone before about
897
- * 1900), and years of five or more digits. Offset-less text is read as UTC,
898
- * as in {@link parseDbDate}. `undefined` when the text is none of these.
899
- */
900
- function parseDbDateGeneral(value) {
901
- const m = DB_DATE_GENERAL_RE.exec(value);
902
- if (!m)
903
- return undefined;
904
- let year = Number(m[1]);
905
- if (m[13])
906
- year = 1 - year;
907
- const month = Number(m[2]) - 1;
908
- const ms = m[7] ? Math.trunc(1000 * Number(`0${m[7]}`)) : 0;
909
- const date = new Date(Date.UTC(2000, month, Number(m[3]), Number(m[4] ?? 0), Number(m[5] ?? 0), Number(m[6] ?? 0), ms));
910
- // setUTCFullYear, not Date.UTC: Date.UTC reads years 0-99 as 1900-1999.
911
- date.setUTCFullYear(year, month, Number(m[3]));
912
- if (m[9]) {
913
- const offset = Number(m[10]) * 3600 + Number(m[11] ?? 0) * 60 + Number(m[12] ?? 0);
914
- return new Date(date.getTime() - (m[9] === '-' ? -offset : offset) * 1000);
915
- }
916
- return date;
917
- }
918
- /**
919
- * Per-cell decode work in a row decode plan (`RowDecodePlan` in builder.ts).
920
- * Defined here rather than in builder.ts because the positional nested-row
921
- * plan in relations.ts reads the same codes, and relations.ts cannot import
922
- * builder.ts.
923
- */
924
- export const CELL_PLAIN = 0;
925
- export const CELL_TEMPORAL = 1;
926
- export const CELL_FLOAT = 2;
927
- export const CELL_FLOAT_ARRAY = 3;
928
- export const CELL_TEXT_ARRAY = 4;
929
- /** The dialect's own decode for a type whose storage differs (see `Dialect.decodeColumnValue`). */
930
- export const CELL_DIALECT = 5;
931
- /**
932
- * A float column's value as the driver reads it. JSON has no NaN or infinity,
933
- * so `json_build_object` renders them as the strings "NaN", "Infinity" and
934
- * "-Infinity"; every other value passes through.
935
- */
936
- export function readJsonFloat(value) {
937
- if (typeof value !== 'string')
938
- return value;
939
- if (value === 'NaN')
940
- return Number.NaN;
941
- if (value === 'Infinity')
942
- return Number.POSITIVE_INFINITY;
943
- if (value === '-Infinity')
944
- return Number.NEGATIVE_INFINITY;
945
- return value;
946
- }
947
- /** {@link readJsonFloat} over a float array (at any depth); the input when nothing changes. */
948
- export function readJsonFloatArray(value) {
949
- if (!Array.isArray(value))
950
- return value;
951
- let out;
952
- for (let i = 0; i < value.length; i++) {
953
- const el = value[i];
954
- const read = Array.isArray(el) ? readJsonFloatArray(el) : readJsonFloat(el);
955
- if (read !== el) {
956
- out ??= value.slice();
957
- out[i] = read;
958
- }
959
- }
960
- return out ?? value;
961
- }
962
- let textArrayParser;
963
- /**
964
- * An array column the driver has no parser for (an enum array) arrives as
965
- * Postgres array text, `{ok,sad}`; read it into an array of strings, as the
966
- * same column reads through a relation. The input when it cannot be parsed.
967
- */
968
- export function readTextArray(value) {
969
- if (typeof value !== 'string' || value.charCodeAt(0) !== 123)
970
- return value;
971
- try {
972
- textArrayParser ??= createPgArrayParser((text) => text);
973
- return textArrayParser(value) ?? value;
974
- }
975
- catch {
976
- return value;
977
- }
978
- }
979
- /**
980
- * Is `value` one of the two representations a Postgres temporal `infinity` /
981
- * `-infinity` reaches the ORM row parser in?
982
- *
983
- * TWO representations, because a temporal column is read two different ways
984
- * and they disagree on the wire:
985
- *
986
- * driver the pg text parser for `timestamp` / `date` does not
987
- * recognise the word, so it falls through to the driver's own
988
- * parser, which returns the JS NUMBERS `Infinity` /
989
- * `-Infinity`. This is what a top-level row, the batched and
990
- * flatten strategies, a write `RETURNING` projection and a
991
- * `groupBy` key all see.
992
- * JSON wire `json_build_object` renders the same value as the STRING
993
- * `"infinity"`, and scalar `timestamp` / `timestamptz` are
994
- * deliberately absent from {@link JSON_WIRE_COERCION_OIDS},
995
- * so no driver parser runs over it. This is what the `'join'`
996
- * strategy and the positional encoding see.
997
- *
998
- * Both are normalized in one place ({@link QueryInterface}'s row parser), to
999
- * whichever reading `temporalInfinity` selects (the JS number by default, or
1000
- * `null`), so the same stored value cannot read differently depending on which
1001
- * plan the query happened to take. The string form is only ever consulted for a column
1002
- * the schema says is temporal, so a `text` column holding the word "infinity"
1003
- * is untouched.
1004
- *
1005
- * Not dialect-gated. Postgres is the only engine with an infinite temporal
1006
- * value, but the row parser is engine-shared and the alternative reading on the
1007
- * other engines (a stray `'infinity'` string becoming an Invalid Date) is not
1008
- * one worth preserving.
1009
- */
1010
- export function isTemporalInfinity(value) {
1011
- if (typeof value === 'number')
1012
- return value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY;
1013
- return value === 'infinity' || value === '-infinity';
1014
- }
1015
- // ---------------------------------------------------------------------------
1016
- // Driver type parsers for the zone-less temporal OIDs
1017
- // ---------------------------------------------------------------------------
1018
- // ---------------------------------------------------------------------------
1019
- // The fast temporal scan
1020
- //
1021
- // Every temporal parser below is a two-stage function: a hand-written
1022
- // character scan that claims the ONE wire shape a busy application actually
1023
- // produces, and behind it the general parser, which is where every other shape
1024
- // (and every shape a future server adds) still goes.
1025
- //
1026
- // WHY IT EXISTS, stated as a measurement rather than an intuition. Draining
1027
- // 50,000 rows of the benchmark `comments` fixture spends ~23.5 ms in
1028
- // client-side type decoding, and `timestamptz` alone is 20.7 ms of it (88%).
1029
- // The remaining types are not worth touching: `text`, `numeric`, `uuid` and
1030
- // `bool` cost nothing at all, because pg registers no parser for them. Two
1031
- // hard bounds were verified in node-postgres' source before any of this was
1032
- // written, and they say what a decoder rewrite can and cannot reach: every
1033
- // cell is materialised as a JS string by `reader.string(len)` before any
1034
- // parser is consulted, so the `utf8Slice` half is unreachable; and the binary
1035
- // protocol is not an escape hatch, the parser constructor throws
1036
- // `Binary mode not supported yet`. The type-PARSING half is the whole budget,
1037
- // and this is a claim on it.
1038
- //
1039
- // THE RULE, and it is the only thing that makes a fast path acceptable here:
1040
- // **the scan must return exactly what the parser it replaces returned, or
1041
- // return `null` and not claim the value at all.** It never guesses, never
1042
- // "handles" a shape approximately, and never widens what it accepts to cover
1043
- // one more case. Every refusal costs a few charCode compares and is repaid by
1044
- // the general parser being correct.
1045
- //
1046
- // Two traps are baked into the refusals rather than into corrections, because
1047
- // a throwaway version of this decoder wrote during the ceiling measurement got
1048
- // 3 of 15 edge values wrong while believing it had delegated the hard ones:
1049
- //
1050
- // 1. `Date.UTC` maps years 0-99 onto 1900-1999, so `0044-03-15` decodes as
1051
- // 1944 and `0001-01-01` as 1901. The obvious repair, build the Date then
1052
- // `setUTCFullYear`, is ALSO wrong: year 0 is a leap year in the proleptic
1053
- // Gregorian calendar and 1900 is not, so `0000-02-29` built that way
1054
- // lands on March 1st. The scan refuses `year < 100` and lets the general
1055
- // parser's `new Date(0)` + `setUTCFullYear(y, m, d)` assembly (which sets
1056
- // all three fields against the right year's calendar) answer it.
1057
- // 2. An offset parse that runs to end-of-string silently EATS a trailing
1058
- // ` BC`: `4713-01-01 00:00:00+00 BC` decodes as AD 4713, off by 9,424
1059
- // years with no error. The scan requires end-of-string after the offset.
1060
- //
1061
- // Differential coverage: src/test/fast-temporal-decode.test.ts compares the
1062
- // scan against the parser it replaces value for value, and
1063
- // src/test/fast-temporal-decode.integration.test.ts does the same against a
1064
- // live server with `DateStyle` and `TimeZone` varied, because the wire shape
1065
- // is a server setting and a decoder tuned to one `DateStyle` is a latent
1066
- // corruption bug.
1067
- // ---------------------------------------------------------------------------
1068
- // Wire shape the scan is reading. Plain module constants rather than an enum:
1069
- // this repo's lint config rejects `const enum` (it does not survive
1070
- // `isolatedModules`), and a plain `enum` emits a runtime object, so every
1071
- // `Shape.Date` in the scan below would become a property load in the hottest
1072
- // loop in the library. These are values, never serialized, never persisted.
1073
- /** `YYYY-MM-DD` (OID 1082). */
1074
- const SHAPE_DATE = 0;
1075
- /** `YYYY-MM-DD[ T]HH:MM:SS[.f…]` (OID 1114), never an offset. */
1076
- const SHAPE_TIMESTAMP = 1;
1077
- /** `YYYY-MM-DD HH:MM:SS[.f…](Z|±HH[:MM[:SS]])` (OID 1184), offset REQUIRED. */
1078
- const SHAPE_TIMESTAMPTZ = 2;
1079
- const CH_HYPHEN = 45;
1080
- const CH_COLON = 58;
1081
- const CH_DOT = 46;
1082
- const CH_SPACE = 32;
1083
- const CH_T = 84;
1084
- const CH_Z = 90;
1085
- const CH_PLUS = 43;
1086
- /** Same code point as {@link CH_HYPHEN}; named separately because the two read
1087
- * as different things (a date separator, an offset sign) at their use sites. */
1088
- const CH_MINUS = 45;
1089
- /**
1090
- * Two ASCII digits at `i` as a number, or `-1` if either character is not a
1091
- * digit. `charCodeAt` past the end returns `NaN`, and `NaN - 48` is `NaN`,
1092
- * which fails both range tests, so this needs no separate length check.
1093
- */
1094
- function twoDigitsAt(text, i) {
1095
- const hi = text.charCodeAt(i) - 48;
1096
- const lo = text.charCodeAt(i + 1) - 48;
1097
- return hi >= 0 && hi <= 9 && lo >= 0 && lo <= 9 ? hi * 10 + lo : -1;
1098
- }
1099
- /**
1100
- * Decode `text` if it is exactly the canonical ISO wire shape for `shape`, or
1101
- * return `null` to say "not mine" (see the rule in the block comment above).
1102
- *
1103
- * Deliberately NOT accepted, each because the parser it replaces would answer
1104
- * differently:
1105
- *
1106
- * - a year that is not exactly four digits. A 5-digit year is a real
1107
- * PostgreSQL output and the general parser handles it; a fast path that
1108
- * matched a variable-width year would have to re-find every later field.
1109
- * - a year below 100 (trap 1 above).
1110
- * - a `T` separator for `SHAPE_TIMESTAMPTZ`. `postgres-date`'s
1111
- * own date-time regex requires a literal SPACE, so it returns `null` for
1112
- * `2024-01-01T00:00:00+00`; a scan that accepted `T` there would invent a
1113
- * Date where the driver hands back null. `timestamp` (1114) does accept it
1114
- * because the general parser it replaces does.
1115
- * - a missing offset for `SHAPE_TIMESTAMPTZ`. `postgres-date` reads an
1116
- * offset-less value in the process's LOCAL zone, which is not what this
1117
- * scan computes.
1118
- * - a colon-less offset (`+0530`), an alphabetic zone (` UTC`), or anything
1119
- * at all after the offset, including ` BC` (trap 2 above).
1120
- * - a bare `.` with no fractional digits.
1121
- *
1122
- * Field-value overflow (`2024-13-45`, `25:70:99`) IS accepted, because
1123
- * `Date.UTC` rolls those over exactly as the general parser's `setUTCFullYear`
1124
- * / `setUTCHours` do. PostgreSQL never emits them; agreeing on them is free.
1125
- */
1126
- function scanIsoTemporal(text, shape) {
1127
- const len = text.length;
1128
- if (len < 10)
1129
- return null;
1130
- if (text.charCodeAt(4) !== CH_HYPHEN || text.charCodeAt(7) !== CH_HYPHEN)
1131
- return null;
1132
- const yearHi = twoDigitsAt(text, 0);
1133
- const yearLo = twoDigitsAt(text, 2);
1134
- if (yearHi < 0 || yearLo < 0)
1135
- return null;
1136
- const year = yearHi * 100 + yearLo;
1137
- if (year < 100)
1138
- return null;
1139
- const month = twoDigitsAt(text, 5);
1140
- const day = twoDigitsAt(text, 8);
1141
- if (month < 0 || day < 0)
1142
- return null;
1143
- if (shape === SHAPE_DATE) {
1144
- return len === 10 ? new Date(Date.UTC(year, month - 1, day)) : null;
1145
- }
1146
- if (len < 19)
1147
- return null;
1148
- const sep = text.charCodeAt(10);
1149
- if (shape === SHAPE_TIMESTAMP ? sep !== CH_SPACE && sep !== CH_T : sep !== CH_SPACE)
1150
- return null;
1151
- if (text.charCodeAt(13) !== CH_COLON || text.charCodeAt(16) !== CH_COLON)
1152
- return null;
1153
- const hour = twoDigitsAt(text, 11);
1154
- const minute = twoDigitsAt(text, 14);
1155
- const second = twoDigitsAt(text, 17);
1156
- if (hour < 0 || minute < 0 || second < 0)
1157
- return null;
1158
- let i = 19;
1159
- let ms = 0;
1160
- if (text.charCodeAt(i) === CH_DOT) {
1161
- i++;
1162
- let digits = 0;
1163
- for (;;) {
1164
- const d = text.charCodeAt(i) - 48;
1165
- if (!(d >= 0 && d <= 9))
1166
- break;
1167
- // Only the first three digits survive: PostgreSQL emits up to six and a
1168
- // JS Date holds milliseconds. `postgres-date` gets the same answer by a
1169
- // different route (`1000 * parseFloat('.476603')`, truncated by
1170
- // `Date.UTC`), and the two agree on every 1-to-6-digit fraction.
1171
- if (digits < 3)
1172
- ms = ms * 10 + d;
1173
- digits++;
1174
- i++;
1175
- }
1176
- if (digits === 0)
1177
- return null;
1178
- if (digits === 1)
1179
- ms *= 100;
1180
- else if (digits === 2)
1181
- ms *= 10;
1182
- }
1183
- if (shape === SHAPE_TIMESTAMP) {
1184
- return i === len ? new Date(Date.UTC(year, month - 1, day, hour, minute, second, ms)) : null;
1185
- }
1186
- let offsetMs = 0;
1187
- const signCode = text.charCodeAt(i);
1188
- if (signCode === CH_Z) {
1189
- i++;
1190
- }
1191
- else if (signCode === CH_PLUS || signCode === CH_MINUS) {
1192
- i++;
1193
- const offsetHours = twoDigitsAt(text, i);
1194
- if (offsetHours < 0)
1195
- return null;
1196
- i += 2;
1197
- let offsetMinutes = 0;
1198
- let offsetSeconds = 0;
1199
- if (text.charCodeAt(i) === CH_COLON) {
1200
- offsetMinutes = twoDigitsAt(text, i + 1);
1201
- if (offsetMinutes < 0)
1202
- return null;
1203
- i += 3;
1204
- // A zone whose historical LMT offset was not a whole minute emits
1205
- // seconds too (`1850-01-01 00:00:00+00:19:32`).
1206
- if (text.charCodeAt(i) === CH_COLON) {
1207
- offsetSeconds = twoDigitsAt(text, i + 1);
1208
- if (offsetSeconds < 0)
1209
- return null;
1210
- i += 3;
1211
- }
1212
- }
1213
- offsetMs =
1214
- (offsetHours * 3_600_000 + offsetMinutes * 60_000 + offsetSeconds * 1000) * (signCode === CH_MINUS ? -1 : 1);
1215
- }
1216
- else {
1217
- return null;
1218
- }
1219
- if (i !== len)
1220
- return null;
1221
- return new Date(Date.UTC(year, month - 1, day, hour, minute, second, ms) - offsetMs);
1222
- }
1223
- /**
1224
- * A Postgres `date` wire value: `YYYY-MM-DD`, optionally with more than four
1225
- * year digits, optionally suffixed ` BC`. Anything else (`infinity`,
1226
- * `-infinity`, and any shape a future server adds) is deliberately NOT matched
1227
- * so it falls through to the driver's own parser untouched.
1228
- */
1229
- const PG_DATE_TEXT_RE = /^(\d{4,})-(\d{2})-(\d{2})( BC)?$/;
1230
- /**
1231
- * Build the driver parser for Postgres `date` (OID 1082) that reads a
1232
- * zone-less calendar day as **UTC midnight**.
1233
- *
1234
- * The pg default builds the Date from the process's LOCAL zone, so the stored
1235
- * calendar day `2026-07-21` comes back as `2026-07-20T22:00:00Z` in
1236
- * `Europe/Berlin` and `2026-07-20T15:00:00Z` in `Asia/Tokyo`: the wrong
1237
- * calendar day everywhere east of UTC, and the wrong instant everywhere except
1238
- * UTC itself. It is also the exact mirror-image of the WRITE side, which
1239
- * already renders a bound `Date` from its UTC components
1240
- * ({@link toLocalDateTimeLiteral}), so today a read-modify-write cycle on a
1241
- * `date` column east of UTC walks the stored day one day earlier per cycle.
1242
- * This is the missing read half of `utcTimestamps`, matching what
1243
- * {@link parseDbDate} already does for the JSON path and what the OID 1114
1244
- * parser already does for `timestamp`.
1245
- *
1246
- * `fallback` is the parser this one REPLACES, and it must be captured with
1247
- * `pg.types.getTypeParser(1082, 'text')` BEFORE registration (reading it after
1248
- * would hand back this function and recurse forever). It keeps `infinity` /
1249
- * `-infinity` on the driver's `Infinity` / `-Infinity`.
1250
- *
1251
- * `setUTCFullYear` rather than the `Date` constructor, so a two-or-three-digit
1252
- * year is not silently mapped into the 1900s, and ` BC` maps to the
1253
- * astronomical year (`0044 BC` → -43) the way the driver's own parser does.
1254
- */
1255
- export function createUtcDateParser(fallback) {
1256
- const general = createUtcDateParserGeneral(fallback);
1257
- return (text) => scanIsoTemporal(text, SHAPE_DATE) ?? general(text);
1258
- }
1259
- /**
1260
- * The `date` (OID 1082) parser WITHOUT the fast scan in front of it: the regex
1261
- * implementation described by {@link createUtcDateParser}, and the reference
1262
- * side of the differential test.
1263
- *
1264
- * Exported so "what the fast path must agree with" is the running code rather
1265
- * than a transcription of it in a test file. Two hand-synced copies of a
1266
- * parser is the drift class this repo has been bitten by before; there is one
1267
- * copy, and the fast path delegates to it.
1268
- *
1269
- * @internal
1270
- */
1271
- export function createUtcDateParserGeneral(fallback) {
1272
- return (text) => {
1273
- const m = PG_DATE_TEXT_RE.exec(text);
1274
- if (!m)
1275
- return fallback(text);
1276
- const year = m[4] ? -(Number(m[1]) - 1) : Number(m[1]);
1277
- const date = new Date(0);
1278
- date.setUTCFullYear(year, Number(m[2]) - 1, Number(m[3]));
1279
- date.setUTCHours(0, 0, 0, 0);
1280
- return date;
1281
- };
1282
- }
1283
- /**
1284
- * A Postgres `timestamp` (without time zone) wire value:
1285
- * `YYYY-MM-DD HH:MM:SS`, optionally with more than four year digits, optional
1286
- * fractional seconds, optional ` BC`. As with {@link PG_DATE_TEXT_RE},
1287
- * `infinity` / `-infinity` and any shape a future server adds deliberately do
1288
- * NOT match, so they fall through to the driver's own parser untouched.
1289
- */
1290
- const PG_TIMESTAMP_TEXT_RE = /^(\d{4,})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?( BC)?$/;
1291
- /**
1292
- * Build the driver parser for Postgres `timestamp` (OID 1114) that reads an
1293
- * offset-less date-time as UTC. Also lifted to the `_timestamp` array OID
1294
- * (1115), so the scalar and the array can never settle on different
1295
- * interpretations.
1296
- *
1297
- * `fallback` is the parser this one REPLACES and must be captured with
1298
- * `pg.types.getTypeParser(1114, 'text')` BEFORE registration (see
1299
- * {@link createUtcDateParser}). It is what keeps `infinity` / `-infinity` on
1300
- * the driver's `Infinity` / `-Infinity`: the earlier
1301
- * `new Date(text.replace(' ', 'T') + 'Z')` form turned `'infinity'` into
1302
- * `'infinityZ'` and so into an `Invalid Date` that flowed on silently.
1303
- *
1304
- * Component assembly rather than `Date` string parsing, for the same reason as
1305
- * the `date` parser: a year outside four digits and a ` BC` suffix are not
1306
- * parseable as ISO-8601 and would otherwise also become `Invalid Date`.
1307
- * Fractional seconds are truncated to milliseconds, which is what
1308
- * `Date`-string parsing did too.
1309
- */
1310
- export function createUtcTimestampParser(fallback) {
1311
- const general = createUtcTimestampParserGeneral(fallback);
1312
- return (text) => scanIsoTemporal(text, SHAPE_TIMESTAMP) ?? general(text);
1313
- }
1314
- /**
1315
- * The `timestamp` (OID 1114) parser WITHOUT the fast scan in front of it: the
1316
- * regex implementation described by {@link createUtcTimestampParser}, and the
1317
- * reference side of the differential test. Same reasoning as
1318
- * {@link createUtcDateParserGeneral}.
1319
- *
1320
- * @internal
1321
- */
1322
- export function createUtcTimestampParserGeneral(fallback) {
1323
- return (text) => {
1324
- const m = PG_TIMESTAMP_TEXT_RE.exec(text);
1325
- if (!m)
1326
- return fallback(text);
1327
- const year = m[8] ? -(Number(m[1]) - 1) : Number(m[1]);
1328
- const ms = m[7] ? Number(m[7].slice(0, 3).padEnd(3, '0')) : 0;
1329
- const date = new Date(0);
1330
- date.setUTCFullYear(year, Number(m[2]) - 1, Number(m[3]));
1331
- date.setUTCHours(Number(m[4]), Number(m[5]), Number(m[6]), ms);
1332
- return date;
1333
- };
1334
- }
1335
- /**
1336
- * Build the driver parser for Postgres `timestamptz` (OID 1184): the ISO wire
1337
- * shape decoded by {@link scanIsoTemporal}, everything else handed straight to
1338
- * `fallback`.
1339
- *
1340
- * UNLIKE the `date` and `timestamp` parsers beside it, this one changes NO
1341
- * READING. A `timestamptz` arrives with an explicit offset, so its instant is
1342
- * unambiguous and both this and `postgres-date` produce the same `Date`; the
1343
- * only difference is how long it takes. That is also why it is not governed by
1344
- * a semantic decision the way `utcTimestamps` governs the zone-less types: there
1345
- * is no second interpretation to choose between.
1346
- *
1347
- * `fallback` must be captured with `pg.types.getTypeParser(1184, 'text')`
1348
- * BEFORE registration, for the same reason as the parsers above: reading it
1349
- * afterwards hands back this function and recurses forever. It is what keeps
1350
- * `infinity` / `-infinity`, ` BC`, wide and low years, and every non-ISO
1351
- * `DateStyle` on `postgres-date`, which already handles them.
1352
- */
1353
- export function createFastTimestamptzParser(fallback) {
1354
- return (text) => scanIsoTemporal(text, SHAPE_TIMESTAMPTZ) ?? fallback(text);
1355
- }
1356
- /**
1357
- * The offset-less-timestamp-as-UTC reading, with no fallback: `text` must be a
1358
- * plain `YYYY-MM-DD HH:MM:SS[.ffffff]`. Used where the input shape is already
1359
- * known (tests, JSON-wire coercion); the DRIVER parser is
1360
- * {@link createUtcTimestampParser}, which delegates everything else.
1361
- */
1362
- export function parseUtcTimestampText(text) {
1363
- return new Date(`${text.replace(' ', 'T')}Z`);
1364
- }
1365
- /**
1366
- * Lift an element parser to the matching Postgres array OID.
1367
- *
1368
- * Array OIDs do NOT inherit their element type's parser: registering a parser
1369
- * for `date` (1082) leaves `date[]` (1182) on the driver's default, so the same
1370
- * value read from a scalar column and from an array column would disagree by
1371
- * the process offset. Every scalar temporal parser Turbine registers is
1372
- * therefore registered in its array form too.
1373
- *
1374
- * `pg.types.arrayParser` is a public member of the `pg` module (it is what the
1375
- * driver's own `_text` / `_date` parsers are built from), so this adds no
1376
- * dependency. NULL elements stay `null` and are never handed to `element`.
1377
- *
1378
- * The empty-string guard mirrors pg's own `parseDateArray`, which opens
1379
- * `if (!value) return null`. Turbine's copy did not, and answered `[]` where
1380
- * the driver answers `null` for the same input. No column produces it (a SQL
1381
- * NULL never reaches a parser, and an empty array is `{}`), so this is parity
1382
- * for its own sake rather than a bug report; it matters because these parsers
1383
- * are registered process-globally over pg's, and a shape where Turbine's
1384
- * answer differs from the driver's is a difference somebody eventually finds
1385
- * the hard way.
1386
- */
1387
- export function createPgArrayParser(element) {
1388
- const arrayParser = pg.types.arrayParser;
1389
- return (text) => text
1390
- ? arrayParser.create(text, (entry) => (entry === null || entry === undefined ? null : element(entry))).parse()
1391
- : null;
1392
- }
1393
- /**
1394
- * A canonical wire value per OID, plus the JS value pg's OWN default text
1395
- * parser produces from it, used to tell "still on the driver default" from
1396
- * "somebody else already customized this OID" (see
1397
- * {@link isDefaultTextParser}).
1398
- *
1399
- * The expected values are computed from LOCAL date components on purpose: pg's
1400
- * default for the zone-less temporal OIDs builds its `Date` in the process's
1401
- * zone (that is the reading `utcTimestamps` exists to replace), so the
1402
- * expectation has to be computed the same way in whatever zone the process runs.
1403
- */
1404
- const DEFAULT_PARSER_PROBES = {
1405
- 20: { text: '9007199254740993', expected: () => '9007199254740993' },
1406
- 1082: { text: '2020-01-02', expected: () => new Date(2020, 0, 2) },
1407
- 1114: { text: '2020-01-02 03:04:05', expected: () => new Date(2020, 0, 2, 3, 4, 5) },
1408
- 1115: { text: '{"2020-01-02 03:04:05"}', expected: () => [new Date(2020, 0, 2, 3, 4, 5)] },
1409
- 1182: { text: '{2020-01-02}', expected: () => [new Date(2020, 0, 2)] },
1410
- // The `timestamptz` pair carries an explicit offset, so unlike the four
1411
- // above its expectation is NOT computed from local components: pg's default
1412
- // and Turbine's fast scan produce the same instant in every zone. These two
1413
- // probes are consulted by {@link registerFastTemporalParserIfDefault}, which
1414
- // DECLINES to install rather than warning-and-overwriting.
1415
- 1184: { text: '2020-01-02 03:04:05+00', expected: () => new Date(Date.UTC(2020, 0, 2, 3, 4, 5)) },
1416
- 1185: { text: '{"2020-01-02 03:04:05+00"}', expected: () => [new Date(Date.UTC(2020, 0, 2, 3, 4, 5))] },
1417
- };
1418
- /**
1419
- * Marks a text parser as one TURBINE installed, so a later registration in the
1420
- * same process (a client plus `turbine studio`, ESM plus CJS copies of this
1421
- * module) does not report Turbine's own parser as "somebody else's". A
1422
- * `Symbol.for` key, for the same cross-copy-identity reason the warn registry
1423
- * uses one.
1424
- */
1425
- const TURBINE_PARSER = Symbol.for('turbine.typeParser');
1426
- /**
1427
- * The OIDs the `utcTimestamps` flag governs, and so the ones it can opt out of.
1428
- *
1429
- * 1184 / 1185 are in the set because the flag gates their registration too,
1430
- * but they are there for a different reason from the other four: those four
1431
- * change a READING (local zone to UTC), while the `timestamptz` pair changes
1432
- * only decode SPEED. See {@link registerUtcTemporalParsers}.
1433
- */
1434
- const TEMPORAL_PARSER_OIDS = new Set([1114, 1082, 1115, 1182, 1184, 1185]);
1435
- /** Tag `parser` as Turbine's own and return it (see {@link TURBINE_PARSER}). */
1436
- export function markTurbineParser(parser) {
1437
- parser[TURBINE_PARSER] = true;
1438
- return parser;
1439
- }
1440
- /** Comparable rendering of a parser result (Date by instant, array by element). */
1441
- function parserResultSignature(value) {
1442
- if (value === null || value === undefined)
1443
- return String(value);
1444
- if (value instanceof Date)
1445
- return `date:${value.getTime()}`;
1446
- if (Array.isArray(value))
1447
- return `[${value.map(parserResultSignature).join(',')}]`;
1448
- return `${typeof value}:${String(value)}`;
1449
- }
1450
- /**
1451
- * Is the parser currently registered for `oid` still pg's own default?
1452
- *
1453
- * DETECTED BY BEHAVIOUR, NOT BY IDENTITY, and deliberately so. `pg-types` keeps
1454
- * its default parser table private: `getTypeParser` hands back whatever is
1455
- * registered NOW, and there is no exported way to ask what the default WAS, so
1456
- * a function-identity comparison would need a deep import of a file the package
1457
- * does not publish as an entry point. Instead this runs the registered parser
1458
- * over a canonical wire value and compares the result with what pg's default
1459
- * produces for it.
1460
- *
1461
- * What that buys and what it costs, stated honestly:
1462
- * - Every parser that behaves OBSERVABLY differently on the probe value is
1463
- * detected, which is the case worth warning about (someone else's reading
1464
- * is about to be replaced by Turbine's).
1465
- * - A replacement that is observably EQUIVALENT on the probe is reported as
1466
- * the default and draws no warning. That is a false negative, and an
1467
- * acceptable one: if it agrees with the default here it is not a reading
1468
- * anybody would notice Turbine overwriting.
1469
- * - A parser that THROWS on the probe is reported as non-default; pg's own
1470
- * never throws on a valid value of its type.
1471
- * - An OID with no probe entry is reported as default (never warn on a guess).
1472
- *
1473
- * The registered parser is invoked once, on a synthetic value, at client
1474
- * construction. A decode parser with side effects would be surprising, and pg's
1475
- * own have none.
1476
- */
1477
- export function isDefaultTextParser(oid, parser) {
1478
- const probe = DEFAULT_PARSER_PROBES[oid];
1479
- if (!probe)
1480
- return true;
1481
- try {
1482
- return parserResultSignature(parser(probe.text)) === parserResultSignature(probe.expected());
1483
- }
1484
- catch {
1485
- return false;
1486
- }
1487
- }
1488
- /**
1489
- * Warn ONCE per OID when Turbine is about to replace a text parser that is not
1490
- * pg's default, i.e. when some other module in the process has already
1491
- * customized it.
1492
- *
1493
- * `pg.types.setTypeParser` is process-global and retroactive: it changes how
1494
- * every `pg.Pool` in the process decodes that OID, including pools that were
1495
- * constructed and were already querying before the Turbine client existed. When
1496
- * the OID was still on pg's default that is the documented, intended trade (the
1497
- * whole point of `utcTimestamps`). When somebody else had already installed
1498
- * their own reading, Turbine is silently rewriting an expectation it cannot see
1499
- * the origin of, and the resulting bug is order-dependent: which reading wins
1500
- * depends on module evaluation order, which lazy route imports make unstable
1501
- * between requests. So say it out loud, once.
1502
- *
1503
- * NOT DEV-ONLY. It used to go quiet under `NODE_ENV=production`, along with
1504
- * every other dev warning, and that was the wrong rule for THIS one, for the
1505
- * same reason the temporal-infinity warning (builder.ts `warnTemporalInfinity`)
1506
- * is not dev-only either. A parser overwrite is ORDER-DEPENDENT: which module
1507
- * calls `setTypeParser` last decides the reading, and evaluation order is
1508
- * exactly what differs between a dev process (eager imports, one route
1509
- * exercised at a time) and a production one (bundled or lazily imported routes,
1510
- * warmed in whatever order traffic arrives). So a process can be clean in dev
1511
- * and wrong in production purely from import order, which makes production the
1512
- * case that matters MOST, and it was the case that was silent. The cost is
1513
- * bounded to the point of irrelevance: once per OID per process, at client
1514
- * construction, and only when somebody else's non-default parser is actually
1515
- * being replaced.
1516
- */
1517
- export function warnParserOverwrite(oid, typeName, logger = consoleLogger) {
1518
- const getParser = pg.types.getTypeParser;
1519
- const current = getParser(oid, 'text');
1520
- // Turbine's own earlier registration is not a third party's expectation.
1521
- if (current[TURBINE_PARSER])
1522
- return;
1523
- if (isDefaultTextParser(oid, current))
1524
- return;
1525
- if (!shouldWarnOnce(WARN_NS.parserOverwrite, String(oid)))
1526
- return;
1527
- // The `utcTimestamps: false` opt-out only governs the six TEMPORAL OIDs.
1528
- // Offering it as the remedy for int8 (20) would name a setting that does
1529
- // nothing for the OID being warned about; that registration has no opt-out.
1530
- // (1184 / 1185 never reach this warning at all: they DECLINE over a
1531
- // non-default parser instead of overwriting it. They are named in the
1532
- // sentence because it describes what the flag leaves alone.)
1533
- const remedy = TEMPORAL_PARSER_OIDS.has(oid)
1534
- ? ' `utcTimestamps: false` leaves the six temporal OIDs (1114, 1082, 1115, 1182, 1184, 1185) alone entirely.'
1535
- : ' There is no opt-out for this OID: Turbine registers it so bigint values come back as numbers.';
1536
- logTo(logger, 'warn', `pg type parser for OID ${oid} (${typeName}) was already customized by something else in this ` +
1537
- 'process, and Turbine is replacing it. `pg.types.setTypeParser` is process-global and takes effect ' +
1538
- 'immediately for EVERY pg.Pool in the process, including pools that already exist and are already ' +
1539
- 'querying, so whatever set that parser will now read this column differently. If yours should win, ' +
1540
- `register it AFTER constructing the client.${remedy} This warning fires under \`NODE_ENV=production\` ` +
1541
- 'too: which parser wins depends on module evaluation order, so a process can be clean in dev and wrong ' +
1542
- 'in production from import order alone.', { code: 'parser-overwrite', oid, type: typeName });
1543
- }
1544
- /**
1545
- * Register Turbine's temporal text parsers on the pg module. SIX OIDs, doing
1546
- * two different jobs:
1547
- *
1548
- * 1114 / 1082 / 1115 / 1182 the UTC READING of the zone-less types,
1549
- * `timestamp`, `date` and their array forms.
1550
- * This changes what a column means and is what
1551
- * `utcTimestamps` is named for.
1552
- * 1184 / 1185 the fast decode path for `timestamptz` and
1553
- * `timestamptz[]`. This changes NOTHING about
1554
- * what a column means: an offset-carrying value
1555
- * has one instant and this reads the same one.
1556
- * It is here for speed, `timestamptz` being ~88%
1557
- * of the client-side decode cost of a wide row
1558
- * drain, and it DECLINES rather than overwrites
1559
- * (see the comment at the call site).
1560
- *
1561
- * ONE place, because `pg.types.setTypeParser` is process-global and the pairing
1562
- * matters: registering a scalar without its array form, or a `date` without the
1563
- * `timestamp` beside it, produces two columns of the same row disagreeing about
1564
- * what the same wire text means. Both callers are processes Turbine owns the
1565
- * pg module in: `TurbineClient` on a pool it created (never on an external
1566
- * pool, whose parser configuration belongs to the caller), and `turbine studio`,
1567
- * which builds a raw pool of its own and must render what the application sees.
1568
- *
1569
- * Each fallback is read BEFORE its parser is installed, so an unrecognised wire
1570
- * value (`infinity`, and whatever a future server adds) still reaches the
1571
- * driver's own parser.
1572
- *
1573
- * Registration is RETROACTIVE for the whole process, pools included that were
1574
- * created and are already querying (there is one parser table, and it is read
1575
- * per row at decode time, not captured per pool). If any of the four OIDs is
1576
- * already on a NON-default parser, {@link warnParserOverwrite} says so once.
1577
- */
1578
- export function registerUtcTemporalParsers(logger) {
1579
- // pg-types declares get/setTypeParser over its own OID enum, which lists the
1580
- // scalar types only. The array OIDs are just as real, so both calls are
1581
- // retyped over a plain number rather than the incomplete enum.
1582
- const getParser = pg.types.getTypeParser;
1583
- const setParser = pg.types.setTypeParser;
1584
- warnParserOverwrite(1114, 'timestamp', logger);
1585
- warnParserOverwrite(1082, 'date', logger);
1586
- warnParserOverwrite(1115, 'timestamp[]', logger);
1587
- warnParserOverwrite(1182, 'date[]', logger);
1588
- const parseDate = createUtcDateParser(getParser(1082, 'text'));
1589
- const parseTimestamp = createUtcTimestampParser(getParser(1114, 'text'));
1590
- setParser(1114, markTurbineParser(parseTimestamp));
1591
- setParser(1082, markTurbineParser(parseDate));
1592
- // Array OIDs do not inherit their element parser, so `date[]` / `timestamp[]`
1593
- // would otherwise keep returning local-zone Dates while the scalar columns
1594
- // beside them returned UTC ones.
1595
- setParser(1182, markTurbineParser(createPgArrayParser(parseDate)));
1596
- setParser(1115, markTurbineParser(createPgArrayParser(parseTimestamp)));
1597
- // `timestamptz` (1184) and `timestamptz[]` (1185). SPEED ONLY: an offset-
1598
- // carrying value has exactly one instant, and this reads it as the same
1599
- // instant `postgres-date` does, so nothing here changes what a column means.
1600
- //
1601
- // Two things about it are deliberate and neither is obvious.
1602
- //
1603
- // It is gated behind `utcTimestamps` along with the other four, even though
1604
- // that flag is about a READING and this is not. The alternative was a second
1605
- // registration site outside this function, and one process-global parser
1606
- // table with two places that write to it is the exact shape the "ONE place"
1607
- // rule above exists to prevent. So the flag reads as "leave pg's temporal
1608
- // parser table alone", and `utcTimestamps: false` costs the optimisation as
1609
- // well as the UTC reading. That is a documented cost, not an oversight.
1610
- //
1611
- // And it DECLINES rather than overwrites (see
1612
- // {@link registerFastTemporalParserIfDefault}), which is the opposite of what
1613
- // the four above do. They MUST overwrite: they exist to replace a reading,
1614
- // and a process where half the temporal columns read local and half read UTC
1615
- // is broken. This one exists only to be faster, so a caller who installed
1616
- // their own `timestamptz` parser (to get strings, or Luxon objects, or a
1617
- // Temporal instant) keeps it. Overwriting them would trade their correctness
1618
- // for our speed, which is never the right trade, and Turbine has never
1619
- // touched 1184 before now, so declining is also what preserves that.
1620
- const parseTimestamptz = registerFastTemporalParserIfDefault(1184, createFastTimestamptzParser);
1621
- if (parseTimestamptz) {
1622
- registerFastTemporalParserIfDefault(1185, () => createPgArrayParser(parseTimestamptz));
1623
- }
1624
- }
1625
- /**
1626
- * Install a SPEED-ONLY parser for `oid`, but only over pg's own default (or
1627
- * over a parser Turbine itself installed earlier in this process).
1628
- *
1629
- * Returns the installed parser, or `undefined` when it declined, so a caller
1630
- * can hold a scalar and its array form to the same decision: registering the
1631
- * array half over a caller's customized scalar half would make the two
1632
- * disagree, which is worse than leaving both slow.
1633
- *
1634
- * `build` receives the parser being replaced, which becomes the fast path's
1635
- * fallback. That is only sound because the parser being replaced is known to
1636
- * be pg's default (or Turbine's own wrapper around it); the check below is
1637
- * what makes it so, and is not an optimisation of it.
1638
- */
1639
- function registerFastTemporalParserIfDefault(oid, build) {
1640
- const getParser = pg.types.getTypeParser;
1641
- const setParser = pg.types.setTypeParser;
1642
- const current = getParser(oid, 'text');
1643
- const isTurbines = current[TURBINE_PARSER] === true;
1644
- if (!isTurbines && !isDefaultTextParser(oid, current))
1645
- return undefined;
1646
- const parser = markTurbineParser(build(current));
1647
- setParser(oid, parser);
1648
- return parser;
1649
- }
1650
- // ---------------------------------------------------------------------------
1651
- // JSON-wire value coercion (relationLoadStrategy: 'join')
1652
- // ---------------------------------------------------------------------------
1653
- /**
1654
- * Postgres type name → OID, for every type family whose `json_build_object`
1655
- * rendering is NOT the value the pg driver produces for the same column.
1656
- *
1657
- * Why this table exists: the `'join'` strategy reads a relation through
1658
- * `json_agg(json_build_object(...))`, so its values are whatever
1659
- * `JSON.parse` makes of Postgres's JSON rendering. Every other read path in
1660
- * the library, a top-level row, `'batched'`, `'flatten'`, reads the column
1661
- * through the driver and gets the driver's representation. Measured against
1662
- * PostgreSQL 17, those two disagree for exactly the families below, which
1663
- * made the SAME query return a different JS type depending on which plan ran
1664
- * (and `'auto'` picks the plan from a row-count heuristic, so it could differ
1665
- * between two runs of one query). Three of these are lossy, not merely
1666
- * different:
1667
- *
1668
- * type driver (target) json_build_object
1669
- * ──────────── ──────────────────────────── ─────────────────────────────
1670
- * numeric '1000.50' (string) 1000.5 (number, LOSSY)
1671
- * int8 '9007199254740993' 9007199254740992 (LOSSY)
1672
- * bytea Buffer '\xdeadbeef' (string)
1673
- * date Date (UTC midnight) Date (UTC midnight, by coincidence)
1674
- * interval { days, hours, … } '1 day 02:03:04' (string)
1675
- * point { x, y } '(1,2)' (string)
1676
- * circle { x, y, radius } '<(1,2),3>' (string)
1677
- *
1678
- * The array forms diverge the same way, plus `_timestamp`/`_timestamptz`
1679
- * (driver: `Date[]`; JSON: `string[]`), the scalar `timestamp` /
1680
- * `timestamptz` are deliberately ABSENT because the existing `dateColumns`
1681
- * coercion in `parseRow` already lands them on the driver's value, and they
1682
- * are the hottest column type in a typical schema (no reason to add a cast to
1683
- * every `created_at`).
1684
- *
1685
- * The fix these OIDs drive: emit the column as `col::text` inside
1686
- * `json_build_object` so the JSON carries the same wire text the driver would
1687
- * receive, then run the DRIVER'S OWN parser for that OID over it. Parity is
1688
- * then by construction rather than by coincidence, and it automatically
1689
- * honours a caller's `pg.types.setTypeParser` (including the int8 parser
1690
- * TurbineClient itself registers) instead of second-guessing it.
1691
- *
1692
- * Postgres-only: the JSON functions and the divergence set are both
1693
- * engine-specific, so callers gate this on the postgres dialect.
1694
- */
1695
- export const JSON_WIRE_COERCION_OIDS = {
1696
- numeric: 1700,
1697
- int8: 20,
1698
- bytea: 17,
1699
- date: 1082,
1700
- interval: 1186,
1701
- point: 600,
1702
- circle: 718,
1703
- _numeric: 1231,
1704
- _int8: 1016,
1705
- _bytea: 1001,
1706
- _date: 1182,
1707
- _interval: 1187,
1708
- _point: 1017,
1709
- _timestamp: 1115,
1710
- _timestamptz: 1185,
1711
- };
1712
- /**
1713
- * The OID whose driver parser reproduces `pgType`'s driver representation from
1714
- * its text rendering, or `undefined` when the type's JSON rendering already
1715
- * matches the driver (the common case: text, uuid, bool, int4, float8, json,
1716
- * jsonb, arrays of those, …).
1717
- */
1718
- export function jsonWireCoercionOid(pgType) {
1719
- if (!pgType)
1720
- return undefined;
1721
- return JSON_WIRE_COERCION_OIDS[pgType];
1722
- }
1723
- /**
1724
- * Apply the driver's text parser for `oid` to a JSON-sourced wire string.
1725
- *
1726
- * Resolved through `pg.types.getTypeParser` on every call rather than
1727
- * memoized: parser registration is process-global and happens in the
1728
- * TurbineClient constructor (int8, and `timestamp` under `utcTimestamps`), and
1729
- * a caller may register their own at any point. A stale memo would silently
1730
- * reintroduce the very divergence this exists to remove. The lookup is a plain
1731
- * object index in pg-types, so it is not worth caching.
1732
- */
1733
- export function coerceJsonWireValue(oid, value) {
1734
- if (typeof value !== 'string')
1735
- return value;
1736
- return pg.types.getTypeParser(oid, 'text')(value);
1737
- }
1738
- // ---------------------------------------------------------------------------
1739
- // Unknown-field diagnostics
1740
- // ---------------------------------------------------------------------------
1741
- /**
1742
- * Case-insensitive closeness of `candidate` to `input`, higher is better,
1743
- * 0 meaning "not worth suggesting". Deliberately tiny: this runs only on the
1744
- * error path, and its whole job is to turn a guessed name into the real one.
1745
- *
1746
- * Substring containment is scored ABOVE edit distance because the real-world
1747
- * miss is a longer, more descriptive guess than the actual name (`modelVersions`
1748
- * for a relation turbine derived as `versions`), where the edit distance is
1749
- * large but the containment is exact.
1750
- */
1751
- function nameCloseness(input, candidate) {
1752
- const a = input.toLowerCase();
1753
- const b = candidate.toLowerCase();
1754
- if (a === b)
1755
- return 1000;
1756
- // Containment only between names of 3+ characters: `id` sits inside almost
1757
- // any name, so `tenentId` must reach `tenantId` by edit distance instead.
1758
- if (Math.min(a.length, b.length) >= 3 && (a.includes(b) || b.includes(a))) {
1759
- return 500 + Math.min(a.length, b.length);
1760
- }
1761
- // Levenshtein, bounded: only near-misses are worth suggesting.
1762
- const rows = a.length + 1;
1763
- const cols = b.length + 1;
1764
- let prev = Array.from({ length: cols }, (_, j) => j);
1765
- for (let i = 1; i < rows; i++) {
1766
- const cur = [i];
1767
- for (let j = 1; j < cols; j++) {
1768
- cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
1769
- }
1770
- prev = cur;
1771
- }
1772
- const distance = prev[cols - 1];
1773
- const limit = Math.max(2, Math.floor(Math.max(a.length, b.length) / 3));
1774
- return distance <= limit ? 100 - distance : 0;
1775
- }
1776
- /** The closest name in `candidates` to `input`, or null when none is close. */
1777
- export function closestName(input, candidates) {
1778
- let best = null;
1779
- let bestScore = 0;
1780
- for (const c of candidates) {
1781
- const score = nameCloseness(input, c);
1782
- if (score > bestScore) {
1783
- bestScore = score;
1784
- best = c;
1785
- }
1786
- }
1787
- return best;
1788
- }
1789
- /** camelCase name → its lowercased words (`logQueryParams` → log, query, params). */
1790
- function camelWords(name) {
1791
- return name
1792
- .split(/(?=[A-Z])/)
1793
- .map((w) => w.toLowerCase())
1794
- .filter(Boolean);
1795
- }
1796
- /**
1797
- * The real option key `key` most likely meant, or null when nothing is close.
1798
- *
1799
- * Shared by every "unknown option" diagnostic (the client-config warner in
1800
- * client.ts and the prisma-compat query-option warner), so a reader who has
1801
- * seen one recognizes the ranking in the other.
1802
- *
1803
- * {@link closestName} decides first, which is bounded by edit distance and
1804
- * covers typos. It does not cover the miss these warnings exist for: a guessed
1805
- * name that omits a whole WORD. `logParams` is five edits from `logQueryParams`,
1806
- * past the bound, yet it names the same words in the same order; likewise
1807
- * `customPlan` for `forceCustomPlan`. So a second pass accepts a candidate whose
1808
- * camelCase words CONTAIN the guess's words in order, preferring the one that
1809
- * adds fewest words.
1810
- */
1811
- export function suggestKey(key, candidates) {
1812
- const direct = closestName(key, candidates);
1813
- if (direct)
1814
- return direct;
1815
- const wanted = camelWords(key);
1816
- if (wanted.length < 2)
1817
- return null;
1818
- let best = null;
1819
- let bestExtra = Number.POSITIVE_INFINITY;
1820
- for (const candidate of candidates) {
1821
- const words = camelWords(candidate);
1822
- if (words.length <= wanted.length)
1823
- continue;
1824
- let i = 0;
1825
- for (const w of words)
1826
- if (w === wanted[i])
1827
- i++;
1828
- if (i !== wanted.length)
1829
- continue;
1830
- const extra = words.length - wanted.length;
1831
- if (extra < bestExtra) {
1832
- bestExtra = extra;
1833
- best = candidate;
1834
- }
1835
- }
1836
- return best;
1837
- }
1838
- /**
1839
- * The "unknown field" error text, listing RELATIONS as well as columns.
1840
- *
1841
- * The message used to read `Known fields: id, name.` and nothing else. That is
1842
- * actively misleading when the key was a relation name: relation filters ARE
1843
- * valid in a `where`, so a user who guessed the wrong relation name concluded
1844
- * from this message that turbine cannot filter by relations at all. Relation
1845
- * names are frequently guessed wrong because introspection derives them, and
1846
- * two foreign keys to one table produce names (`msgsBySender`) that no one
1847
- * would predict.
1848
- */
1849
- export function unknownFieldMessage(table, field, meta) {
1850
- const columns = Object.keys(meta.columnMap);
1851
- const relations = Object.keys(meta.relations ?? {});
1852
- const suggestion = closestName(field, [...columns, ...relations]);
1853
- const didYouMean = suggestion
1854
- ? ` Did you mean "${suggestion}"${relations.includes(suggestion) ? ' (a relation)' : ''}?`
1855
- : '';
1856
- return (`Unknown field "${field}" on table "${table}".${didYouMean}` +
1857
- ` Known columns: ${columns.join(', ') || '(none)'}.` +
1858
- (relations.length ? ` Known relations (valid in \`where\` and \`with\`): ${relations.join(', ')}.` : ''));
1859
- }
1860
- /**
1861
- * The trailing "Available: a, b, c" clause of a name-not-found error, or
1862
- * `emptySentence` when there is nothing to list.
1863
- *
1864
- * The empty branch is the whole reason this exists. Fifteen error sites
1865
- * interpolated `Object.keys(...).join(', ')` directly, and on a table with no
1866
- * relations (or a schema with no tables) that renders a dangling
1867
- * `Available: ` with nothing after the colon, which reads as a broken error
1868
- * message rather than as an answer. One site already got this right by hand;
1869
- * the other fourteen are now the same function, so the next one cannot get it
1870
- * wrong by omission.
1871
- */
1872
- export function availableClause(names, emptySentence) {
1873
- return names.length > 0 ? `Available: ${names.join(', ')}` : emptySentence;
1874
- }
1875
- /**
1876
- * The error text for a RELATION named inside `select` / `omit`.
1877
- *
1878
- * Separate from {@link unknownFieldMessage} because the generic text degrades
1879
- * into nonsense here: `closestName` matches an exactly-spelled relation name at
1880
- * distance zero, so the message would read `Unknown field "comments". Did you
1881
- * mean "comments" (a relation)?`, which answers a question nobody asked and
1882
- * hides the actual fix.
1883
- *
1884
- * It is worth its own message for a second reason: this is not really a typo,
1885
- * it is a habit. Prisma nests a relation inside `select`, so writing
1886
- * `select: { comments: true }` is the natural first guess, and in Turbine a
1887
- * relation is loaded by `with`, which sits BESIDE `select` rather than inside
1888
- * it. Naming the fix costs one sentence and saves a search.
1889
- */
1890
- export function relationInProjectionMessage(table, field, clause) {
1891
- const head = `"${field}" is a relation on table "${table}", not a column, so it cannot be named in \`${clause}\`.`;
1892
- return clause === 'select'
1893
- ? `${head} Load it with \`with: { ${field}: true }\`, which is a sibling of \`select\`, not a member of it.` +
1894
- " To narrow the relation's own columns, put a `select` inside that relation's options:" +
1895
- ` \`with: { ${field}: { select: { … } } }\`.`
1896
- : `${head} A relation is only present when you ask for it in \`with\`, so leave it out of \`with\` to leave it` +
1897
- ' out of the result.';
1898
- }
1899
- /**
1900
- * Advice (`diagnostics.advice`) for a sort/grouping term Turbine dropped as redundant
1901
- * (`filters.ts` `dedupeOrderEntries` / `dedupeColumnList`).
1902
- *
1903
- * Deliberately a WARNING and not an error, and deliberately not silent either.
1904
- * The dropped term provably cannot change a result, so failing the query would
1905
- * be a false alarm on a shape correct code produces (a caller-chosen sort key
1906
- * plus an unconditional primary-key tiebreak, which collide exactly when the
1907
- * caller sorts by the primary key). But a caller who wrote the duplicate by
1908
- * hand, or who believes a second key is doing something, should hear about it
1909
- * once. Advice for the usual reason: it describes the QUERY the application
1910
- * sends, which does not vary with the environment, so a production process
1911
- * learns nothing from repeating it. The caller passes its advice logger, or
1912
- * `undefined` when advice is off.
1913
- *
1914
- * Keyed per dropped key, so a sort assembled per request from the same UI says
1915
- * it once rather than once per request.
1916
- */
1917
- export function warnRedundantSortTerm(advice, table, clause, dropped) {
1918
- if (!advice)
1919
- return;
1920
- for (const d of dropped) {
1921
- if (!shouldWarnOnce(WARN_NS.redundantSortTerm, `${table}|${clause}|${d.key}`))
1922
- continue;
1923
- const how = d.first === d.key
1924
- ? `"${d.key}" is named twice`
1925
- : `"${d.key}" and the earlier "${d.first}" both target ${d.resolved}`;
1926
- logTo(advice, 'warn', `${clause} on table "${table}": ${how}, so the later one was dropped. It could not have ` +
1927
- 'changed the result (the earlier term already orders those rows), and dropping it keeps the query on ' +
1928
- 'a shared prepared statement. Remove it to silence this.', { code: 'redundant-sort-term', table, clause, key: d.key });
1929
- }
1930
- }
1931
- /**
1932
- * The two projection SHAPE refusals (0.65), shared by the SQL engines' single
1933
- * resolver, the batched loader's raw-arg check, and PowDB, so every path that
1934
- * refuses these shapes does so with one message.
1935
- *
1936
- * Both checks look at TRUTHY keys, and the raw-arg check in the batched
1937
- * loader exists because the loader force-adds correlation keys to a `select`
1938
- * before the resolver sees it: evaluated after that adjustment, an all-falsy
1939
- * user `select` looks populated and the verdict flips between strategies,
1940
- * which is exactly the class 0.64/0.65 exist to kill.
1941
- */
1942
- export function selectNamesNothingMessage(table) {
1943
- return (`"select" names no fields (on table "${table}"): every value is false or it is empty. ` +
1944
- `Pass at least one field as true, or drop "select" to get the default projection.`);
1945
- }
1946
- export function selectOmitExclusiveMessage(table) {
1947
- return (`"select" and "omit" are mutually exclusive (on table "${table}"). ` +
1948
- `A select already lists exactly the fields you want.`);
1949
- }
1950
- /**
1951
- * The Prisma pagination aliases, folded into Turbine's own spelling ONCE,
1952
- * before anything reads them.
1953
- *
1954
- * Turbine's names are `limit` / `offset`; Prisma's are `take` / `skip`. `take`
1955
- * was accepted and `skip` was not, which is the worst of the three possible
1956
- * states: `{ take: 20, skip: 40 }` is what a Prisma habit writes, it looks
1957
- * accepted because half of it is, and the query silently returns page one
1958
- * forever. An unknown key is at least inert on its own; a HALF-recognized pair
1959
- * changes the answer.
1960
- *
1961
- * Folded here rather than read at each site deliberately. `take` used to be
1962
- * handled by six separate `args?.take ?? args?.limit` reads, one of which is
1963
- * the SQL-cache FINGERPRINT, so adding `skip` the same way would have meant
1964
- * teaching six places about it and a miss in the fingerprint is not a missing
1965
- * feature, it is two different pages sharing one cached statement. Normalizing
1966
- * up front leaves `limit` / `offset` as the single authority and the aliases
1967
- * cease to exist below this line.
1968
- *
1969
- * Returns the SAME object when neither alias is present, so the common path
1970
- * allocates nothing.
1971
- */
1972
- export function normalizePagination(args) {
1973
- if (!args)
1974
- return args;
1975
- const a = args;
1976
- if (a.take === undefined && a.skip === undefined)
1977
- return args;
1978
- const out = { ...args };
1979
- if (a.take !== undefined) {
1980
- assertAliasAgrees('take', a.take, 'limit', a.limit);
1981
- out.limit = a.take;
1982
- delete out.take;
1983
- }
1984
- if (a.skip !== undefined) {
1985
- assertAliasAgrees('skip', a.skip, 'offset', a.offset);
1986
- out.offset = a.skip;
1987
- delete out.skip;
1988
- }
1989
- return out;
1990
- }
1991
- /**
1992
- * Both spellings of one bound, disagreeing. Refused rather than resolved: the
1993
- * old `take ?? limit` silently preferred one of the two numbers the caller
1994
- * wrote, and there is no reading of `{ limit: 10, take: 5 }` that makes one of
1995
- * them the intended answer. Equal values are accepted, since there is nothing
1996
- * to choose between.
1997
- */
1998
- function assertAliasAgrees(alias, aliasValue, native, nativeValue) {
1999
- if (nativeValue === undefined || nativeValue === aliasValue)
2000
- return;
2001
- throw new ValidationError(`"${alias}" and "${native}" are the same option and were given different values ` +
2002
- `(${alias}: ${String(aliasValue)}, ${native}: ${String(nativeValue)}). ` +
2003
- `"${alias}" is Prisma's spelling of "${native}"; pass one of them.`);
2004
- }
3
+ import { registerQueryDriver } from '../query-utils.js';
4
+ registerQueryDriver(pg);
5
+ export * from '../query-utils.js';
6
+ export { createPgArrayParser, isDefaultTextParser, markTurbineParser, registerUtcTemporalParsers, warnParserOverwrite, } from './pg-type-parsers.js';