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
package/dist/mysql.js CHANGED
@@ -14,8 +14,7 @@
14
14
  * rows. `mysqlDialect.resultStrategy = 'reselect'`: the executor runs the
15
15
  * write, then issues a follow-up `SELECT` by primary key (using mysql2's
16
16
  * `insertId` for auto-increment PKs) / by the `where` predicate, so
17
- * `create`/`update`/`upsert`/`delete` still return real rows. This is the
18
- * first shipped engine to exercise the Phase-0 `reselect` path.
17
+ * `create`/`update`/`upsert`/`delete` still return real rows.
19
18
  * 2. **Positional `?` is broken for this builder.** Turbine pushes params in
20
19
  * 1-indexed generation order but EMITS them in a different SQL-text position
21
20
  * (e.g. a `with`-relation `LIMIT` lands in the SELECT list, ahead of the
@@ -64,8 +63,9 @@
64
63
  */
65
64
  import { TurbineClient, } from './client.js';
66
65
  import { postgresDialect, } from './dialect.js';
67
- import { ConnectionError, malformedConnectionStringMessage, markValueBearingMessage, UnsupportedFeatureError, ValidationError, } from './errors.js';
66
+ import { ConnectionError, malformedConnectionStringMessage, markValueBearingMessage, TimeoutError, TransactionOutcomeUnknownError, UnsupportedFeatureError, ValidationError, } from './errors.js';
68
67
  import { applyTableFilters, assertDistinctColumnFields, deriveEngineRelations, nullRecord } from './introspect.js';
68
+ import { consoleLogger, logTo } from './logger.js';
69
69
  import importOptionalPeer from './optional-peer-import.cjs';
70
70
  import { isDateType, snakeToCamel, } from './schema.js';
71
71
  import { rewritePositionalPlaceholders, scanPlaceholders } from './sql-placeholders.js';
@@ -134,34 +134,55 @@ function paddedListLength(n) {
134
134
  function refusePlaceholder(message) {
135
135
  throw new ValidationError(message);
136
136
  }
137
+ /** Bounded SQL-only templates. Neither bindings nor list contents are retained. */
138
+ const bindingTemplates = new Map();
139
+ function bindingTemplate(sql, count) {
140
+ const cached = bindingTemplates.get(sql);
141
+ if (cached?.count === count)
142
+ return cached;
143
+ // Arity is part of admission: a warmed $2 must still refuse one supplied value.
144
+ const template = {
145
+ count,
146
+ sql: rewritePositionalPlaceholders(sql, 'mysql', count, (i) => `:p${i}`, refusePlaceholder),
147
+ names: Array.from({ length: count }, (_, i) => `p${i + 1}`),
148
+ };
149
+ if (sql.length <= 8192 && count <= 128) {
150
+ if (bindingTemplates.size >= 128)
151
+ bindingTemplates.delete(bindingTemplates.keys().next().value);
152
+ bindingTemplates.set(sql, template);
153
+ }
154
+ return template;
155
+ }
137
156
  /**
138
157
  * The statement text and named binding for one execution: `$n` placeholders
139
158
  * (the spelling `rawUnsafe` documents) rewritten to `:pN`, every
140
159
  * {@link MysqlInList} expanded, and every other value bound by name. Mapping by
141
160
  * NAME makes binding independent of where each placeholder lands in the SQL
142
- * text, the same guarantee Postgres' numbered `$N` gives. `binding` is
161
+ * text, the same guarantee Postgres' numbered `$N` gives. No wrapper is needed
162
+ * for an empty parameter array. `binding` is
143
163
  * `undefined` when nothing is bound, so parameter-less statements (BEGIN,
144
164
  * COMMIT, DDL) run through `.query()`.
145
165
  */
146
166
  function bindStatement(sql, values) {
147
167
  if (values.length === 0)
148
- return { sql, binding: undefined };
149
- const text = rewritePositionalPlaceholders(sql, 'mysql', values.length, (i) => `:p${i}`, refusePlaceholder);
168
+ return undefined;
169
+ const template = bindingTemplate(sql, values.length);
150
170
  const named = {};
151
171
  let lists;
152
172
  for (let i = 0; i < values.length; i++) {
153
173
  const value = values[i];
174
+ const name = i < template.names.length ? template.names[i] : `p${i + 1}`;
154
175
  if (value instanceof MysqlInList) {
155
176
  lists ??= new Map();
156
- lists.set(`p${i + 1}`, value);
177
+ lists.set(name, value);
157
178
  }
158
179
  else {
159
- named[`p${i + 1}`] = toMysqlParam(value);
180
+ named[name] = toMysqlParam(value);
160
181
  }
161
182
  }
162
183
  if (lists === undefined)
163
- return { sql: text, binding: named };
164
- const expanded = expandInLists(text, lists, named);
184
+ return { sql: template.sql, binding: named };
185
+ const expanded = expandInLists(template.sql, lists, named);
165
186
  return { sql: expanded, binding: Object.keys(named).length > 0 ? named : undefined };
166
187
  }
167
188
  /**
@@ -248,15 +269,16 @@ const MYSQL_FIELD_TYPE_TINY = 1;
248
269
  function coerceBooleanColumns(rows, fields) {
249
270
  if (!Array.isArray(fields) || rows.length === 0)
250
271
  return;
251
- const names = [];
272
+ let names;
252
273
  for (const f of fields) {
253
274
  if (!f || f.columnType !== MYSQL_FIELD_TYPE_TINY || f.columnLength !== 1)
254
275
  continue;
255
276
  if (typeof f.name !== 'string')
256
277
  continue;
278
+ names ??= [];
257
279
  names.push(f.name);
258
280
  }
259
- if (names.length === 0)
281
+ if (names === undefined || names.length === 0)
260
282
  return;
261
283
  for (const row of rows) {
262
284
  for (const name of names) {
@@ -286,7 +308,7 @@ function shapeResult(result, fields) {
286
308
  * deadlock / lock-wait-timeout become retryable (E012/E013). The original mysql2
287
309
  * error (with its real message) is preserved as the wrapped error's `.cause`
288
310
  * downstream. Returns the value unchanged when it is not a recognizable mysql2
289
- * error. We only annotate here, `wrapPgError` (invoked downstream in the query
311
+ * error. This only annotates the error; `wrapPgError` (invoked downstream in the query
290
312
  * executor / transaction proxy) does the actual translation.
291
313
  */
292
314
  function augmentMysqlError(err) {
@@ -399,6 +421,43 @@ function normalizeQueryArgs(arg, values) {
399
421
  return { text: arg, params: values ?? [] };
400
422
  return { text: arg.text, params: arg.values ?? values ?? [] };
401
423
  }
424
+ /**
425
+ * Only the bulk INSERT builder knows that its placeholders occur exactly once,
426
+ * in parameter order, with no value expressions or SQL literals between them.
427
+ * Keep its positional driver statement private, keyed by the actual parameter
428
+ * array. The public DeferredQuery still contains the same named SQL. A copied
429
+ * array, edited SQL (including comments), or changed arity uses normal binding.
430
+ * No values or statements outlive the parameter array.
431
+ */
432
+ const bulkInsertBindings = new WeakMap();
433
+ /** Arity-only templates: eight entries of at most 8,192 cells, never caller values or identifiers. */
434
+ const bulkInsertTuples = new Map();
435
+ function mysqlParamPlaceholder(index) {
436
+ return `:p${index}`;
437
+ }
438
+ function bulkTuples(rows) {
439
+ const width = rows[0]?.length ?? 0;
440
+ const uniform = rows.every((row) => row.length === width);
441
+ const cacheable = uniform && width > 0 && rows.length * width <= 8192;
442
+ const key = `${rows.length}:${width}`;
443
+ const cached = cacheable ? bulkInsertTuples.get(key) : undefined;
444
+ if (cached)
445
+ return cached;
446
+ let n = 0;
447
+ const named = rows.map((row) => `(${row.map(() => `:p${++n}`).join(', ')})`).join(', ');
448
+ const positional = uniform
449
+ ? Array(rows.length)
450
+ .fill(`(${Array(width).fill('?').join(', ')})`)
451
+ .join(', ')
452
+ : rows.map((row) => `(${row.map(() => '?').join(', ')})`).join(', ');
453
+ const tuples = { named, positional };
454
+ if (cacheable) {
455
+ if (bulkInsertTuples.size >= 8)
456
+ bulkInsertTuples.delete(bulkInsertTuples.keys().next().value);
457
+ bulkInsertTuples.set(key, tuples);
458
+ }
459
+ return tuples;
460
+ }
402
461
  /**
403
462
  * Run one statement against a mysql2 queryable (pool or connection). Parameterized
404
463
  * statements use `.execute()` (mysql2 server-side prepared statements, cached per
@@ -407,10 +466,15 @@ function normalizeQueryArgs(arg, values) {
407
466
  * the `{ p1, p2, … }` object built from the positional params.
408
467
  */
409
468
  async function execOne(runner, sql, params) {
410
- const bound = bindStatement(sql, params);
411
- const binding = bound.binding;
469
+ const bulk = bulkInsertBindings.get(params);
470
+ const bound = bulk && bulk.sql === sql && bulk.count === params.length && !params.some((v) => v instanceof MysqlInList)
471
+ ? { sql: bulk.positional, binding: Array.from(params, toMysqlParam) }
472
+ : bindStatement(sql, params);
473
+ const binding = bound?.binding;
412
474
  try {
413
- const [result, fields] = binding ? await runner.execute(bound.sql, binding) : await runner.query(bound.sql);
475
+ const [result, fields] = binding
476
+ ? await runner.execute(bound.sql, binding)
477
+ : await runner.query(bound?.sql ?? sql);
414
478
  return shapeResult(result, fields);
415
479
  }
416
480
  catch (err) {
@@ -428,16 +492,335 @@ async function execOne(runner, sql, params) {
428
492
  */
429
493
  async function runOnConnection(conn, sql, params) {
430
494
  if (params.length === 0 && /^SET TRANSACTION ISOLATION LEVEL /i.test(sql) && sql.includes('; ')) {
431
- let last = shapeResult([]);
495
+ let last;
432
496
  for (const part of sql.split('; ')) {
433
497
  const trimmed = part.trim();
434
498
  if (trimmed)
435
499
  last = await execOne(conn, trimmed, []);
436
500
  }
437
- return last;
501
+ // The first real statement supplies the result; only an empty split needs
502
+ // a fallback. Do not allocate a discarded row array and result per BEGIN.
503
+ return last ?? shapeResult([]);
438
504
  }
439
505
  return execOne(conn, sql, params);
440
506
  }
507
+ /**
508
+ * Whether the server answered with `err`: an error packet on a live connection
509
+ * (a numeric `errno`, not fatal), as the error or its cause. A lost or
510
+ * timed-out connection is no answer. So are a shutdown (1053), an interrupted
511
+ * statement (1317) and a killed connection (1927), which can arrive while a
512
+ * COMMIT is being written.
513
+ */
514
+ function answeredByServer(err) {
515
+ for (let e = err, depth = 0; depth < 4 && e !== null && typeof e === 'object'; depth++) {
516
+ const { errno, fatal } = e;
517
+ if (typeof errno === 'number')
518
+ return errno > 0 && fatal !== true && ![1053, 1317, 1927].includes(errno);
519
+ e = e.cause;
520
+ }
521
+ return false;
522
+ }
523
+ /**
524
+ * Close a connection Turbine is discarding, in both directions, so the server
525
+ * ends its session now.
526
+ *
527
+ * mysql2's own `destroy()` is `stream.end()`, a half-close, and it drops the
528
+ * connection from the pool at once. A server still writing a result to a
529
+ * client that stopped reading (a stream returned early) never reads that close,
530
+ * so its session stayed in "Sending to client", holding its metadata lock,
531
+ * until `net_write_timeout`, outside the pool limit. The half-closed client
532
+ * also kept reading: the execute mysql2 queues behind a prepare was sent on the
533
+ * closed socket, and the server's parting error packet arrived as its answer,
534
+ * which mysql2 prints as "got packets out of order".
535
+ *
536
+ * Destroying the socket closes both directions (a reset while unread rows are
537
+ * buffered), which the server sees on its next read or write. mysql2 handles it
538
+ * as any lost connection: queued commands fail, and the pool drops the
539
+ * connection when the socket closes. Nothing waits on this connection any
540
+ * more, so the error mysql2 reports for it is absorbed.
541
+ */
542
+ function destroyConnection(raw) {
543
+ raw.on?.('error', () => { });
544
+ if (typeof raw.stream?.destroy === 'function')
545
+ raw.stream.destroy();
546
+ else
547
+ raw.destroy?.();
548
+ }
549
+ /** A checked-out connection never queues another statement behind a paused result. */
550
+ class MysqlStreamClient {
551
+ conn;
552
+ released = false;
553
+ discarded = false;
554
+ inTransaction = false;
555
+ pending = 0;
556
+ committing = false;
557
+ deadlineError;
558
+ active;
559
+ constructor(conn) {
560
+ this.conn = conn;
561
+ }
562
+ timeoutError(timeout, confirmed = false) {
563
+ return new TimeoutError(timeout, 'Transaction', {
564
+ outcome: confirmed ? 'not-executed' : 'unknown',
565
+ message: `Transaction timed out after ${timeout}ms. ${confirmed ? 'Rollback was confirmed.' : 'Cancellation and rollback are not confirmed; its outcome is unknown.'}`,
566
+ });
567
+ }
568
+ transactionRecovery = {
569
+ assertTimeout: () => { },
570
+ pendingMessage: 'transaction cannot commit; rollback is not yet confirmed. ',
571
+ sessionMessage: 'Your callback did not run; rollback is not yet confirmed.',
572
+ timeoutError: (timeout) => (this.deadlineError = this.timeoutError(timeout)),
573
+ rollback: async (running, send, graceMs) => {
574
+ // mysql2 cannot cancel a running statement. A failed COMMIT response is
575
+ // uncertain even if a later ROLLBACK answers successfully.
576
+ if (running || this.pending || this.committing)
577
+ return false;
578
+ let timer;
579
+ try {
580
+ return await Promise.race([
581
+ send().then(() => true, () => false),
582
+ new Promise((resolve) => {
583
+ timer = setTimeout(() => resolve(false), graceMs);
584
+ }),
585
+ ]);
586
+ }
587
+ finally {
588
+ clearTimeout(timer);
589
+ }
590
+ },
591
+ finish: (state, clean, error, logger) => {
592
+ state.end(clean ? 'was rolled back' : 'ended with an unknown outcome');
593
+ if (!clean && logger)
594
+ logTo(logger, 'debug', 'Transaction ended with an unknown outcome', {
595
+ code: 'transaction-outcome-unknown',
596
+ operation: '$transaction',
597
+ });
598
+ if (clean && this.deadlineError === error && this.deadlineError)
599
+ return this.timeoutError(this.deadlineError.timeoutMs, true);
600
+ // A COMMIT the server did not answer (a lost or timed-out connection)
601
+ // may have committed. An error the server answered with keeps its class.
602
+ return this.committing && !answeredByServer(error) ? new TransactionOutcomeUnknownError(error) : error;
603
+ },
604
+ };
605
+ assertOpen() {
606
+ if (this.released || this.discarded)
607
+ throw new ConnectionError('This MySQL checkout has been released or discarded.');
608
+ }
609
+ // biome-ignore lint/suspicious/noExplicitAny: pg-compat query is generic over the row shape.
610
+ async query(text, values) {
611
+ this.pending++;
612
+ try {
613
+ return await this.runQuery(text, values);
614
+ }
615
+ finally {
616
+ this.pending--;
617
+ }
618
+ }
619
+ // biome-ignore lint/suspicious/noExplicitAny: see query().
620
+ async runQuery(text, values) {
621
+ this.assertOpen();
622
+ const { text: sql, params } = normalizeQueryArgs(text, values);
623
+ if (this.active) {
624
+ if (params.length === 0 && /^\s*(?:COMMIT|ROLLBACK|SAVEPOINT|RELEASE SAVEPOINT)\b/i.test(sql)) {
625
+ await this.active.close();
626
+ this.assertOpen();
627
+ }
628
+ else
629
+ throw new ValidationError('A MySQL native stream is active on this connection. Close it before another statement.');
630
+ }
631
+ if (sql === 'COMMIT' && params.length === 0)
632
+ this.committing = true;
633
+ const result = await runOnConnection(this.conn, sql, params);
634
+ if (/^\s*(?:(?:SET TRANSACTION ISOLATION LEVEL [A-Z ]+; )?START TRANSACTION|BEGIN)\b/i.test(sql) &&
635
+ params.length === 0)
636
+ this.inTransaction = true;
637
+ else if (/^\s*(?:COMMIT|ROLLBACK(?!\s+TO))\b/i.test(sql) && params.length === 0)
638
+ this.inTransaction = false;
639
+ return result;
640
+ }
641
+ async *streamBatches(text, values, batchSize, signal) {
642
+ this.assertOpen();
643
+ if (this.active)
644
+ throw new ValidationError('A MySQL native stream is already active on this connection.');
645
+ if (this.pending)
646
+ throw new ValidationError('A MySQL statement is still running on this connection.');
647
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1)
648
+ throw new ValidationError('Native stream batchSize must be a positive safe integer.');
649
+ signal?.throwIfAborted();
650
+ const raw = this.conn.connection;
651
+ if (!raw ||
652
+ typeof raw.destroy !== 'function' ||
653
+ typeof raw.pause !== 'function' ||
654
+ typeof raw.resume !== 'function' ||
655
+ typeof raw.execute !== 'function' ||
656
+ typeof raw.query !== 'function') {
657
+ throw new UnsupportedFeatureError('native streaming', 'mysql', 'The mysql2 callback connection with pause(), resume() and destroy() is required.');
658
+ }
659
+ const bound = bindStatement(text, values);
660
+ let command;
661
+ let fields;
662
+ let rows = [];
663
+ let wake;
664
+ const notify = () => {
665
+ const resolve = wake;
666
+ wake = undefined;
667
+ resolve?.();
668
+ };
669
+ let resultSets = 0;
670
+ let complete = false;
671
+ let closed = false;
672
+ let failure;
673
+ let settle;
674
+ const settled = new Promise((resolve) => {
675
+ settle = resolve;
676
+ });
677
+ const discard = () => {
678
+ if (this.discarded)
679
+ return;
680
+ this.discarded = true;
681
+ destroyConnection(raw);
682
+ };
683
+ const onEnd = () => {
684
+ complete = true;
685
+ notify();
686
+ settle();
687
+ };
688
+ const onError = (error) => {
689
+ if (failure === undefined)
690
+ failure = augmentMysqlError(error);
691
+ notify();
692
+ settle();
693
+ };
694
+ const onFields = (next) => {
695
+ if (++resultSets > 1)
696
+ cancel(new UnsupportedFeatureError('multiple native stream result sets', 'mysql', 'Stream a single row result set per statement.'));
697
+ else
698
+ fields = next;
699
+ };
700
+ const onRow = (row) => {
701
+ // Callbackless mysql2 commands never collect rows. Keep exactly one
702
+ // batch here and pause packet decoding until the consumer asks again.
703
+ // ResultSetHeader has no fields and must not become a streamed row.
704
+ if (closed || failure !== undefined || !Array.isArray(fields))
705
+ return;
706
+ if (rows.length === batchSize) {
707
+ cancel(new ConnectionError('The MySQL driver exceeded native stream backpressure.'));
708
+ return;
709
+ }
710
+ rows.push(row);
711
+ if (rows.length === batchSize) {
712
+ raw.pause();
713
+ notify();
714
+ }
715
+ };
716
+ const cancel = (error) => {
717
+ if (failure === undefined)
718
+ failure = error;
719
+ closed = true;
720
+ command?.removeListener('result', onRow);
721
+ discard();
722
+ rows = [];
723
+ notify();
724
+ settle();
725
+ signal?.removeEventListener('abort', onAbort);
726
+ if (this.active === state)
727
+ this.active = undefined;
728
+ };
729
+ let closing;
730
+ const close = () => (closing ??= (async () => {
731
+ const priorFailure = failure;
732
+ closed = true;
733
+ command?.removeListener('result', onRow);
734
+ rows = [];
735
+ notify();
736
+ if (!complete && failure === undefined) {
737
+ // Callbackless commands do not collect result arrays. Detach delivery
738
+ // and resume the wire to discard a transaction's remainder. Standalone
739
+ // streams can discard their checkout instead of draining.
740
+ if (this.inTransaction) {
741
+ raw.resume();
742
+ await settled;
743
+ }
744
+ else
745
+ discard();
746
+ }
747
+ if (failure !== undefined && !complete)
748
+ discard();
749
+ if (this.active === state)
750
+ this.active = undefined;
751
+ signal?.removeEventListener('abort', onAbort);
752
+ command?.removeListener('end', onEnd);
753
+ command?.removeListener('fields', onFields);
754
+ if (!this.discarded)
755
+ raw.removeListener?.('error', onError);
756
+ if (priorFailure === undefined && failure !== undefined)
757
+ throw failure;
758
+ })());
759
+ const state = { close, cancel };
760
+ this.active = state;
761
+ const onAbort = () => cancel(signal.reason);
762
+ try {
763
+ // Fatal parser/socket failures can bypass a callbackless command and
764
+ // reach only the connection's error event.
765
+ raw.on?.('error', onError);
766
+ command = bound?.binding ? raw.execute(bound.sql, bound.binding) : raw.query(bound?.sql ?? text);
767
+ command.on('end', onEnd);
768
+ command.on('error', onError);
769
+ command.on('fields', onFields);
770
+ command.on('result', onRow);
771
+ signal?.addEventListener('abort', onAbort, { once: true });
772
+ if (signal?.aborted)
773
+ onAbort();
774
+ while (true) {
775
+ if (failure !== undefined)
776
+ throw failure;
777
+ if (closed)
778
+ throw new ValidationError('This MySQL native stream has been closed.');
779
+ if (rows.length === batchSize || (complete && rows.length > 0)) {
780
+ const batch = rows;
781
+ rows = [];
782
+ coerceBooleanColumns(batch, fields);
783
+ yield batch;
784
+ if (!closed && failure === undefined && !complete)
785
+ raw.resume();
786
+ }
787
+ else if (complete)
788
+ return;
789
+ else
790
+ await new Promise((resolve) => {
791
+ wake = resolve;
792
+ });
793
+ }
794
+ }
795
+ catch (error) {
796
+ if (failure === undefined)
797
+ failure = closed ? new ValidationError('This MySQL native stream has been closed.') : augmentMysqlError(error);
798
+ throw failure;
799
+ }
800
+ finally {
801
+ signal?.removeEventListener('abort', onAbort);
802
+ await close();
803
+ // A destroyed mysql2 command may still report a late connection error.
804
+ // Keep its harmless error listener until the command is collected.
805
+ }
806
+ }
807
+ release(error) {
808
+ if (this.released)
809
+ return;
810
+ this.released = true;
811
+ if (this.active)
812
+ this.active.cancel(new ConnectionError('The MySQL checkout was released during a native stream.'));
813
+ if (!this.discarded) {
814
+ const raw = this.conn.connection;
815
+ if ((error || this.pending) && typeof raw?.destroy === 'function') {
816
+ this.discarded = true;
817
+ destroyConnection(raw);
818
+ }
819
+ else
820
+ this.conn.release();
821
+ }
822
+ }
823
+ }
441
824
  /**
442
825
  * A {@link PgCompatPool} backed by a `mysql2` pool. Non-transaction queries run
443
826
  * on the pool directly (any connection); `connect()` checks out a dedicated
@@ -458,14 +841,7 @@ export class MysqlPool {
458
841
  }
459
842
  async connect() {
460
843
  const conn = await this.pool.getConnection();
461
- return {
462
- // biome-ignore lint/suspicious/noExplicitAny: see query() above.
463
- query: async (text, values) => {
464
- const { text: sql, params } = normalizeQueryArgs(text, values);
465
- return runOnConnection(conn, sql, params);
466
- },
467
- release: () => conn.release(),
468
- };
844
+ return new MysqlStreamClient(conn);
469
845
  }
470
846
  async end() {
471
847
  if (this.closed)
@@ -680,7 +1056,9 @@ export const mysqlDialect = {
680
1056
  name: 'mysql',
681
1057
  capabilities: Object.freeze({
682
1058
  distinctOn: false,
1059
+ tupleCursorPredicate: false,
683
1060
  positionalJson: false,
1061
+ jsonObjectKeysAsWritten: false,
684
1062
  nullsOrderingClause: false,
685
1063
  nullsSortHigh: false,
686
1064
  insensitiveInList: false,
@@ -713,6 +1091,7 @@ export const mysqlDialect = {
713
1091
  backendCancel: false,
714
1092
  idleTransactionTimeout: false,
715
1093
  abortsTransactionOnError: false,
1094
+ classifiesCommitAnswer: false,
716
1095
  connectionDriver: 'engine-driver',
717
1096
  // mysql2 execute() prepares each statement text; max_prepared_stmt_count caps them server-wide.
718
1097
  preparesEveryStatement: true,
@@ -722,7 +1101,7 @@ export const mysqlDialect = {
722
1101
  // TEXT / BLOB need a prefix length in a key (ER_BLOB_KEY_WITHOUT_LENGTH).
723
1102
  unboundedTextKeys: false,
724
1103
  }),
725
- // No RETURNING → run the write, then re-SELECT by PK/where (Phase-0 reselect).
1104
+ // No RETURNING → run the write, then re-SELECT by PK/where.
726
1105
  resultStrategy: 'reselect',
727
1106
  supportsReturning: false,
728
1107
  // `ON DUPLICATE KEY UPDATE` has no predicate slot, so `buildUpsertStatement`
@@ -770,9 +1149,7 @@ export const mysqlDialect = {
770
1149
  // text position; positional `?` mis-binds. mysql2 named parameters bind by
771
1150
  // name, so `:pN` ↔ `params[N-1]` mirrors Postgres' `$N` regardless of text
772
1151
  // order. The driver shim binds via a `{ p1, p2, … }` object.
773
- paramPlaceholder(index) {
774
- return `:p${index}`;
775
- },
1152
+ paramPlaceholder: mysqlParamPlaceholder,
776
1153
  quoteIdentifier(name) {
777
1154
  return `\`${name.replace(/`/g, '``')}\``;
778
1155
  },
@@ -945,19 +1322,32 @@ export const mysqlDialect = {
945
1322
  return `INSERT INTO ${input.table} (${input.columns.join(', ')}) VALUES (${input.valuePlaceholders.join(', ')})`;
946
1323
  },
947
1324
  buildBulkInsertStatement(input) {
948
- // No UNNEST in MySQL, emit multi-row VALUES with flattened, named
949
- // placeholders (`:p1`, `:p2`, …) matching the flat param order.
950
- let n = 0;
951
- const placeholders = input.rowValues
952
- .map((row) => `(${row.map(() => this.paramPlaceholder(++n)).join(', ')})`)
953
- .join(', ');
1325
+ const standard = this.paramPlaceholder === mysqlParamPlaceholder;
1326
+ let next = 0;
1327
+ const tuples = standard
1328
+ ? bulkTuples(input.rowValues)
1329
+ : {
1330
+ named: input.rowValues
1331
+ .map((row) => `(${row.map(() => this.paramPlaceholder(++next)).join(', ')})`)
1332
+ .join(', '),
1333
+ positional: '',
1334
+ };
954
1335
  // skipDuplicates → no-op ON DUPLICATE KEY UPDATE (keeps the existing row).
955
1336
  const firstCol = input.columns[0] ?? '`id`';
956
1337
  const conflict = input.skipDuplicates ? ` ON DUPLICATE KEY UPDATE ${firstCol} = ${firstCol}` : '';
957
- return {
958
- sql: `INSERT INTO ${input.table} (${input.columns.join(', ')}) VALUES ${placeholders}${conflict}`,
959
- params: input.rowValues.flat(),
960
- };
1338
+ const prefix = `INSERT INTO ${input.table} (${input.columns.join(', ')}) VALUES `;
1339
+ const sql = `${prefix}${tuples.named}${conflict}`;
1340
+ const params = [];
1341
+ for (const row of input.rowValues)
1342
+ for (const value of row)
1343
+ params.push(value);
1344
+ if (standard && params.length > 0)
1345
+ bulkInsertBindings.set(params, {
1346
+ sql,
1347
+ positional: `${prefix}${tuples.positional}${conflict}`,
1348
+ count: params.length,
1349
+ });
1350
+ return { sql, params };
961
1351
  },
962
1352
  buildBulkUpsertStatement(input) {
963
1353
  // 8.0.19's row alias (`VALUES(col)` is deprecated since 8.0.20). There is
@@ -999,7 +1389,7 @@ export const mysqlDialect = {
999
1389
  // MySQL ignores the explicit conflict target, ON DUPLICATE KEY UPDATE keys
1000
1390
  // off the table's PK/unique indexes. The `where`-derived conflictColumns
1001
1391
  // (input.conflictColumns) must therefore correspond to a real unique/PK index
1002
- // for the upsert to target the intended row (plan §4 / R9).
1392
+ // for the upsert to target the intended row.
1003
1393
  return (`INSERT INTO ${input.table} (${input.insertColumns.join(', ')}) VALUES (${input.valuePlaceholders.join(', ')})` +
1004
1394
  ` ON DUPLICATE KEY UPDATE ${input.updateSetClauses.join(', ')}`);
1005
1395
  },
@@ -1125,17 +1515,11 @@ export const mysqlDialect = {
1125
1515
  throw new UnsupportedFeatureError('sessionContext (RLS session GUCs)', 'mysql', 'MySQL has no transaction-local GUCs / set_config equivalent.');
1126
1516
  },
1127
1517
  // ---- Streaming ----------------------------------------------------------
1128
- /**
1129
- * The {@link StreamableConnection} seam only exposes `query()`, not mysql2's
1130
- * native `.stream()`, so the "stream" fetches once and yields the rows in
1131
- * `batchSize` chunks. True server-side streaming would require direct mysql2
1132
- * access (documented limitation).
1133
- */
1134
- async *openStream(connection, sql, params, batchSize) {
1135
- const result = await connection.query(sql, params);
1136
- for (let i = 0; i < result.rows.length; i += batchSize) {
1137
- yield result.rows.slice(i, i + batchSize);
1138
- }
1518
+ /** Incremental mysql2 consumption; query-only connections cannot stream. */
1519
+ async *openStream(connection, sql, params, batchSize, options) {
1520
+ if (!connection.streamBatches)
1521
+ throw new UnsupportedFeatureError('native streaming', 'mysql', 'An acquired MysqlPool connection is required.');
1522
+ yield* connection.streamBatches(sql, params, batchSize, options?.signal);
1139
1523
  },
1140
1524
  // ---- Introspection ------------------------------------------------------
1141
1525
  introspector: {
@@ -1153,46 +1537,117 @@ const num = (v) => (typeof v === 'string' ? Number(v) : (v ?? 0));
1153
1537
  * same logical schema, legacy-first naming, per-column disambiguation, and
1154
1538
  * collision resolution against scalar column fields included.
1155
1539
  */
1156
- function buildRelationsFromForeignKeys(tableNames, foreignKeys, pkByTable, columnsByTable, logger) {
1157
- return deriveEngineRelations(tableNames, foreignKeys, pkByTable, columnsByTable, logger);
1540
+ function buildRelationsFromForeignKeys(tableNames, foreignKeys, pkByTable, columnsByTable, logger, isToOne) {
1541
+ return deriveEngineRelations(tableNames, foreignKeys, pkByTable, columnsByTable, logger, isToOne);
1542
+ }
1543
+ /** Only comparison domains whose native equality also enforces the unique key. */
1544
+ function mysqlSameKeyEquality(child, parent) {
1545
+ if (!child || !parent)
1546
+ return false;
1547
+ const type = child.COLUMN_TYPE.toLowerCase();
1548
+ if (type !== parent.COLUMN_TYPE.toLowerCase())
1549
+ return false;
1550
+ if (/^(?:char|varchar)\(\d+\)$/.test(type)) {
1551
+ return (typeof child.CHARACTER_SET_NAME === 'string' &&
1552
+ child.CHARACTER_SET_NAME === parent.CHARACTER_SET_NAME &&
1553
+ typeof child.COLLATION_NAME === 'string' &&
1554
+ child.COLLATION_NAME === parent.COLLATION_NAME);
1555
+ }
1556
+ // ENUM/SET, approximate numbers and unrecognized domains stay conservative.
1557
+ return /^(?:(?:tinyint|smallint|mediumint|int|bigint)(?:\(\d+\))?(?: unsigned)?|decimal\(\d+,\d+\)(?: unsigned)?|(?:var)?binary\(\d+\)|date|(?:datetime|timestamp|time)(?:\(\d+\))?|year)$/.test(type);
1558
+ }
1559
+ /** Decode COLUMN_TYPE's catalog serialization, independently of DDL sql_mode. */
1560
+ function parseMysqlEnum(source) {
1561
+ const labels = [];
1562
+ const token = /'((?:[^'\\]|''|\\[\\0nr])*)'([,)])/gy;
1563
+ token.lastIndex = 5;
1564
+ if (/^enum\(/i.test(source)) {
1565
+ for (let match = token.exec(source); match; match = token.exec(source)) {
1566
+ labels.push(match[1].replace(/''|\\[\\0nr]/g, (escaped) => escaped === "''"
1567
+ ? "'"
1568
+ : escaped === '\\0'
1569
+ ? '\u0000'
1570
+ : escaped === '\\n'
1571
+ ? '\n'
1572
+ : escaped === '\\r'
1573
+ ? '\r'
1574
+ : '\\'));
1575
+ if (match[2] === ')') {
1576
+ if (token.lastIndex === source.length)
1577
+ return labels;
1578
+ break;
1579
+ }
1580
+ }
1581
+ }
1582
+ throw new ValidationError('Invalid MySQL ENUM catalog definition.');
1583
+ }
1584
+ /**
1585
+ * Character sets that can encode a code point the catalog text cannot.
1586
+ * `information_schema` reports `COLUMN_TYPE` in utf8mb3 (verified on MySQL
1587
+ * 8.4.0: `SELECT CHARSET(COLUMN_TYPE)` is `utf8mb3`, and the bytes are `?`
1588
+ * where a supplementary character was), so only a column in one of these
1589
+ * sets can hold a label the catalog rendering loses. Every other MySQL
1590
+ * charset has a BMP-only repertoire, which utf8mb3 renders exactly (a
1591
+ * literal `?` in such a label really is a question mark).
1592
+ */
1593
+ const SUPPLEMENTARY_CHARSETS = new Set(['utf8mb4', 'utf16', 'utf16le', 'utf32', 'gb18030']);
1594
+ /**
1595
+ * Whether catalog-decoded `labels` may have lost a supplementary character:
1596
+ * some label holds a `?` and the column's charset can encode what utf8mb3
1597
+ * cannot. The loss always surfaces as `?` (the conversion has no other
1598
+ * substitute), so its absence proves the labels exact; its presence is
1599
+ * ambiguous with a literal question mark, which catalog text cannot settle,
1600
+ * so a suspect list is withheld whatever it holds. A missing charset is
1601
+ * suspect too: the catalog always reports one for an ENUM, so a custom
1602
+ * executor that omits it has not proven the column BMP-only.
1603
+ */
1604
+ function enumLabelsSuspect(labels, charset) {
1605
+ if (!labels.some((label) => label.includes('?')))
1606
+ return false;
1607
+ // Loose null on purpose: a custom executor's row can omit the field the
1608
+ // catalog query selected, and absent is not proof of a BMP-only column.
1609
+ return charset == null || SUPPLEMENTARY_CHARSETS.has(charset.toLowerCase());
1158
1610
  }
1159
1611
  /**
1160
1612
  * Introspect a MySQL database into the same {@link SchemaMetadata} shape the
1161
1613
  * Postgres catalog introspector produces, using a caller-supplied query
1162
1614
  * executor (so tests can dogfood an already-open mysql2 pool/connection).
1163
1615
  *
1616
+ * Every statement is a `SELECT`. An ENUM column whose catalog labels may have
1617
+ * lost a supplementary character (the utf8mb3 `COLUMN_TYPE` text holds `?` on
1618
+ * a charset that can encode past the BMP) is marked
1619
+ * `enumLabelsUnrecoverable`, warned about by name, and typed `string` instead
1620
+ * of a union guessed from the damaged text; labels declared explicitly (an
1621
+ * `enums` entry, or a `columnTypes` override at generation) outrank it.
1622
+ *
1164
1623
  * @param exec Runs a parameterized (`:p1`, `:p2`, …) query and returns rows.
1165
1624
  * @param schema The MySQL database (schema) name to introspect.
1166
- * @param options Optional include / exclude table-name filters, and the logger
1167
- * that receives relation-naming notes (console when absent).
1625
+ * @param options Table-name filters, relation-naming logger, and the legacy
1626
+ * opt-out from proven unique-FK reverse to-one cardinality.
1168
1627
  */
1169
1628
  export async function introspectMysqlWith(exec, schema, options = {}) {
1170
1629
  // ----- Tables -----
1171
1630
  const candidateTables = (await exec("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = :p1 AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME", [schema])).map((r) => String(r.TABLE_NAME));
1172
- // include / exclude + default bookkeeping-table exclusions (F12).
1631
+ // include / exclude + default bookkeeping-table exclusions.
1173
1632
  const tableNames = applyTableFilters(candidateTables, options);
1174
1633
  const tableSet = new Set(tableNames);
1175
1634
  // ----- Columns -----
1176
1635
  const columnRows = (await exec(`SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY,
1177
- COLUMN_DEFAULT, EXTRA, CHARACTER_MAXIMUM_LENGTH
1636
+ COLUMN_DEFAULT, EXTRA, CHARACTER_MAXIMUM_LENGTH, CHARACTER_SET_NAME, COLLATION_NAME,
1637
+ GENERATION_EXPRESSION
1178
1638
  FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = :p1 ORDER BY TABLE_NAME, ORDINAL_POSITION`, [schema]));
1179
1639
  const columnsByTable = new Map();
1640
+ const nativeColumns = new Map();
1180
1641
  const enums = nullRecord();
1642
+ const logger = options.logger ?? consoleLogger;
1181
1643
  for (const c of columnRows) {
1182
1644
  if (!tableSet.has(c.TABLE_NAME))
1183
1645
  continue;
1646
+ nativeColumns.set(JSON.stringify([c.TABLE_NAME, c.COLUMN_NAME]), c);
1184
1647
  const nullable = c.IS_NULLABLE === 'YES' && c.COLUMN_KEY !== 'PRI';
1648
+ const computed = /\b(?:VIRTUAL|STORED) GENERATED\b/i.test(c.EXTRA) || !!c.GENERATION_EXPRESSION;
1185
1649
  const dataType = c.DATA_TYPE.toLowerCase();
1186
- // Inline ENUM parsing from COLUMN_TYPE: enum('a','b','c')
1187
- if (dataType === 'enum') {
1188
- const m = /^enum\((.*)\)$/i.exec(c.COLUMN_TYPE);
1189
- if (m?.[1]) {
1190
- enums[`${c.TABLE_NAME}.${c.COLUMN_NAME}`] = m[1].split(',').map((s) => s
1191
- .trim()
1192
- .replace(/^'(.*)'$/, '$1')
1193
- .replace(/''/g, "'"));
1194
- }
1195
- }
1650
+ const enumLabels = dataType === 'enum' ? parseMysqlEnum(c.COLUMN_TYPE) : undefined;
1196
1651
  const maxLen = c.CHARACTER_MAXIMUM_LENGTH != null ? num(c.CHARACTER_MAXIMUM_LENGTH) : undefined;
1197
1652
  // `tinyint(1)` is the one type whose DATA_TYPE is not enough to identify it
1198
1653
  // (see MYSQL_BOOLEAN_TYPE); everything else keeps the bare DATA_TYPE.
@@ -1204,15 +1659,38 @@ export async function introspectMysqlWith(exec, schema, options = {}) {
1204
1659
  pgType: recordedType,
1205
1660
  tsType: mysqlTypeToTs(dataType, nullable, c.COLUMN_TYPE),
1206
1661
  nullable,
1207
- hasDefault: c.COLUMN_DEFAULT !== null || /auto_increment/i.test(c.EXTRA),
1662
+ // Nullable MySQL columns have an effective DEFAULT NULL even when the
1663
+ // catalog cannot distinguish an explicit NULL from an implicit default.
1664
+ hasDefault: nullable || c.COLUMN_DEFAULT !== null || /auto_increment/i.test(c.EXTRA) || computed,
1208
1665
  // The server numbers it, so a create's re-read can use the insert id.
1209
1666
  isGenerated: /auto_increment/i.test(c.EXTRA),
1667
+ // The existing flag protects BOTH virtual and stored computed values.
1668
+ ...(computed ? { isGeneratedStored: true } : {}),
1669
+ ...(computed && c.GENERATION_EXPRESSION ? { generationExpression: c.GENERATION_EXPRESSION } : {}),
1210
1670
  isArray: false,
1211
1671
  arrayType: undefined,
1212
1672
  pgArrayType: 'text[]',
1213
1673
  };
1214
1674
  if (maxLen !== undefined)
1215
1675
  col.maxLength = maxLen;
1676
+ if (enumLabels !== undefined) {
1677
+ // Exact unless suspect (see enumLabelsSuspect). A suspect list is
1678
+ // withheld, never recorded from the damaged text, so no consumer can type
1679
+ // or validate against a label the column does not have.
1680
+ const key = `${c.TABLE_NAME}.${c.COLUMN_NAME}`;
1681
+ if (!enumLabelsSuspect(enumLabels, c.CHARACTER_SET_NAME)) {
1682
+ enums[key] = enumLabels;
1683
+ }
1684
+ else {
1685
+ col.enumLabelsUnrecoverable = true;
1686
+ logTo(logger, 'warn', `MySQL introspection: the ENUM labels of "${key}" may hold characters outside the BMP, which the MySQL ` +
1687
+ 'catalog reports as "?" (a label that really contains "?" reads the same), so the column is typed as ' +
1688
+ 'string instead of a literal union. For exact literal types, declare its labels explicitly: with the ' +
1689
+ `CLI, a \`columnTypes\` entry in turbine.config.ts (\`columnTypes: { "${key}": "'a' | 'b'" }\`); in code, ` +
1690
+ `an \`enums\` entry on the introspected metadata before calling generate() (\`schema.enums["${key}"] = ` +
1691
+ "['a', 'b']`). The stored labels and row data are unaffected.", { code: 'introspect-enum-labels-unrecoverable', table: c.TABLE_NAME });
1692
+ }
1693
+ }
1216
1694
  if (!columnsByTable.has(c.TABLE_NAME))
1217
1695
  columnsByTable.set(c.TABLE_NAME, []);
1218
1696
  columnsByTable.get(c.TABLE_NAME).push(col);
@@ -1229,15 +1707,18 @@ export async function introspectMysqlWith(exec, schema, options = {}) {
1229
1707
  pkByTable.get(r.TABLE_NAME).push(r.COLUMN_NAME);
1230
1708
  }
1231
1709
  // ----- Foreign keys (grouped by constraint for composite FKs) -----
1232
- const fkRows = (await exec(`SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME, CONSTRAINT_NAME, ORDINAL_POSITION
1710
+ const fkRows = (await exec(`SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME, CONSTRAINT_NAME, ORDINAL_POSITION
1233
1711
  FROM information_schema.KEY_COLUMN_USAGE
1234
1712
  WHERE TABLE_SCHEMA = :p1 AND REFERENCED_TABLE_NAME IS NOT NULL
1713
+ AND REFERENCED_TABLE_SCHEMA = :p1
1235
1714
  ORDER BY CONSTRAINT_NAME, ORDINAL_POSITION`, [schema]));
1236
1715
  const fkByConstraint = new Map();
1237
1716
  for (const r of fkRows) {
1238
1717
  if (!tableSet.has(r.TABLE_NAME))
1239
1718
  continue;
1240
- const key = `${r.TABLE_NAME}.${r.CONSTRAINT_NAME}`;
1719
+ if (r.REFERENCED_TABLE_SCHEMA !== undefined && r.REFERENCED_TABLE_SCHEMA !== schema)
1720
+ continue;
1721
+ const key = JSON.stringify([r.TABLE_NAME, r.CONSTRAINT_NAME]);
1241
1722
  let entry = fkByConstraint.get(key);
1242
1723
  if (!entry) {
1243
1724
  entry = {
@@ -1254,44 +1735,70 @@ export async function introspectMysqlWith(exec, schema, options = {}) {
1254
1735
  }
1255
1736
  const foreignKeys = [...fkByConstraint.values()].filter((fk) => tableSet.has(fk.targetTable));
1256
1737
  // ----- Indexes + unique constraints -----
1257
- const idxRows = (await exec(`SELECT TABLE_NAME, INDEX_NAME, NON_UNIQUE, COLUMN_NAME, SEQ_IN_INDEX FROM information_schema.STATISTICS
1738
+ const idxRows = (await exec(`SELECT TABLE_NAME, INDEX_NAME, NON_UNIQUE, COLUMN_NAME, SEQ_IN_INDEX,
1739
+ SUB_PART, EXPRESSION, COLLATION, INDEX_TYPE, IS_VISIBLE, INDEX_COMMENT
1740
+ FROM information_schema.STATISTICS
1258
1741
  WHERE TABLE_SCHEMA = :p1 ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`, [schema]));
1259
1742
  const indexGroups = new Map();
1260
1743
  for (const r of idxRows) {
1261
1744
  if (!tableSet.has(r.TABLE_NAME))
1262
1745
  continue;
1263
- const key = `${r.TABLE_NAME}.${r.INDEX_NAME}`;
1264
- let g = indexGroups.get(key);
1265
- if (!g) {
1266
- g = { table: r.TABLE_NAME, name: r.INDEX_NAME, unique: num(r.NON_UNIQUE) === 0, columns: [] };
1267
- indexGroups.set(key, g);
1268
- }
1269
- g.columns.push(r.COLUMN_NAME);
1746
+ const key = JSON.stringify([r.TABLE_NAME, r.INDEX_NAME]);
1747
+ if (!indexGroups.has(key))
1748
+ indexGroups.set(key, []);
1749
+ indexGroups.get(key).push(r);
1270
1750
  }
1271
1751
  const indexesByTable = new Map();
1272
1752
  const uniqueByTable = new Map();
1273
- for (const g of indexGroups.values()) {
1274
- if (g.name === 'PRIMARY')
1753
+ for (const rows of indexGroups.values()) {
1754
+ rows.sort((a, b) => num(a.SEQ_IN_INDEX) - num(b.SEQ_IN_INDEX));
1755
+ const first = rows[0];
1756
+ if (first.INDEX_NAME === 'PRIMARY')
1275
1757
  continue; // PK is tracked separately
1276
- if (!indexesByTable.has(g.table))
1277
- indexesByTable.set(g.table, []);
1278
- indexesByTable.get(g.table).push({
1279
- name: g.name,
1280
- columns: g.columns,
1281
- unique: g.unique,
1282
- definition: `${g.unique ? 'UNIQUE ' : ''}INDEX ${g.name} ON ${g.table}(${g.columns.join(', ')})`,
1758
+ const plain = rows.every((r) => typeof r.COLUMN_NAME === 'string' && r.EXPRESSION == null && r.SUB_PART == null);
1759
+ // Never publish a subset of a functional/prefix key as a complete key.
1760
+ const columns = plain ? rows.map((r) => r.COLUMN_NAME) : [];
1761
+ const unique = num(first.NON_UNIQUE) === 0;
1762
+ if (!indexesByTable.has(first.TABLE_NAME))
1763
+ indexesByTable.set(first.TABLE_NAME, []);
1764
+ indexesByTable.get(first.TABLE_NAME).push({
1765
+ name: first.INDEX_NAME,
1766
+ columns,
1767
+ unique,
1768
+ // Opaque, non-executable catalog facts. In particular, expressions must
1769
+ // never be converted into guessed migration DDL. MySQL has no partial
1770
+ // indexes; SUB_PART is a key prefix length, not a WHERE predicate.
1771
+ definition: `MySQL index metadata: ${JSON.stringify({
1772
+ type: first.INDEX_TYPE ?? null,
1773
+ visible: first.IS_VISIBLE ?? null,
1774
+ comment: first.INDEX_COMMENT ?? null,
1775
+ keys: rows.map((r) => ({
1776
+ column: r.COLUMN_NAME,
1777
+ expression: r.EXPRESSION ?? null,
1778
+ prefixLength: r.SUB_PART == null ? null : num(r.SUB_PART),
1779
+ order: r.COLLATION ?? null,
1780
+ })),
1781
+ })}`,
1283
1782
  });
1284
- if (g.unique && g.columns.length > 0) {
1285
- if (!uniqueByTable.has(g.table))
1286
- uniqueByTable.set(g.table, []);
1287
- uniqueByTable.get(g.table).push(g.columns);
1783
+ if (unique && columns.length > 0) {
1784
+ if (!uniqueByTable.has(first.TABLE_NAME))
1785
+ uniqueByTable.set(first.TABLE_NAME, []);
1786
+ uniqueByTable.get(first.TABLE_NAME).push(columns);
1288
1787
  }
1289
1788
  }
1290
1789
  // ----- Relations -----
1291
1790
  // One field per column, as the PostgreSQL introspector requires.
1292
1791
  for (const [tableName, cols] of columnsByTable)
1293
1792
  assertDistinctColumnFields(tableName, cols);
1294
- const relationsByTable = buildRelationsFromForeignKeys(tableNames, foreignKeys, pkByTable, columnsByTable, options.logger);
1793
+ // A to-one is decided per foreign key BEFORE naming, so it is named as
1794
+ // PostgreSQL names it (`users.profile`): the child's columns are exactly its
1795
+ // primary key or a unique key, and each column pair compares the way the
1796
+ // enforced key does.
1797
+ const relationsByTable = buildRelationsFromForeignKeys(tableNames, foreignKeys, pkByTable, columnsByTable, options.logger, options.legacyToManyUniques
1798
+ ? undefined
1799
+ : (fk) => fk.sourceColumns.length === fk.targetColumns.length &&
1800
+ fk.sourceColumns.every((name, i) => mysqlSameKeyEquality(nativeColumns.get(JSON.stringify([fk.sourceTable, name])), nativeColumns.get(JSON.stringify([fk.targetTable, fk.targetColumns[i]])))) &&
1801
+ [pkByTable.get(fk.sourceTable) ?? [], ...(uniqueByTable.get(fk.sourceTable) ?? [])].some((key) => key.length === fk.sourceColumns.length && key.every((name) => fk.sourceColumns.includes(name))));
1295
1802
  // ----- Assemble TableMetadata -----
1296
1803
  const tables = nullRecord();
1297
1804
  for (const tableName of tableNames) {
@@ -1356,6 +1863,7 @@ export async function introspectMysql(options) {
1356
1863
  include: options.include,
1357
1864
  exclude: options.exclude,
1358
1865
  logger: options.logger,
1866
+ legacyToManyUniques: options.legacyToManyUniques,
1359
1867
  });
1360
1868
  }
1361
1869
  finally {
@@ -1506,8 +2014,8 @@ export async function turbineMysql(target, schema, options = {}) {
1506
2014
  // NOTE: even on a `mysql2/promise` pool, the 'connection' event yields the
1507
2015
  // *raw* (callback-style) connection, its `.query()` returns a non-thenable
1508
2016
  // `Query`, so `.catch()`/`await` on it throws "result of query that is not a
1509
- // promise". Use the callback form here (fire-and-forget): if the SET fails we
1510
- // fall back to MySQL's default escaping, harmless since every value is a param.
2017
+ // promise". Use the callback form here (fire-and-forget): if the SET fails,
2018
+ // MySQL keeps its default escaping, harmless since every value is a param.
1511
2019
  mysql2Pool.on?.('connection', (rawConn) => {
1512
2020
  rawConn.query("SET SESSION sql_mode = CONCAT(@@sql_mode, ',NO_BACKSLASH_ESCAPES')", () => { });
1513
2021
  });