viborm 1.5.1 → 1.7.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 (278) hide show
  1. package/README.md +4 -2
  2. package/dist/{adapter-internals-Dagucesf.mjs → adapter-internals-DNY4JWFC.mjs} +1 -1
  3. package/dist/{adapter-internals-Dagucesf.mjs.map → adapter-internals-DNY4JWFC.mjs.map} +1 -1
  4. package/dist/{adapter-namespace-DuugUuQa.mjs → adapter-namespace-BMss0hKo.mjs} +2 -2
  5. package/dist/{adapter-namespace-DuugUuQa.mjs.map → adapter-namespace-BMss0hKo.mjs.map} +1 -1
  6. package/dist/{adapter-result-parser-B63ouFIz.mjs → adapter-result-parser-Bz3WtMBa.mjs} +1 -1
  7. package/dist/{adapter-result-parser-B63ouFIz.mjs.map → adapter-result-parser-Bz3WtMBa.mjs.map} +1 -1
  8. package/dist/adapters.d.mts +1 -1
  9. package/dist/adapters.mjs +1 -1
  10. package/dist/{array-literal-BU1R9byi.mjs → array-literal-DfgmVxKI.mjs} +1 -1
  11. package/dist/{array-literal-BU1R9byi.mjs.map → array-literal-DfgmVxKI.mjs.map} +1 -1
  12. package/dist/{batch-refs-C3MTcVre.mjs → batch-refs-DWMYN0fw.mjs} +2 -2
  13. package/dist/{batch-refs-C3MTcVre.mjs.map → batch-refs-DWMYN0fw.mjs.map} +1 -1
  14. package/dist/bind-parameter-capacity-Bjgx1lMC.mjs +2 -0
  15. package/dist/{bind-parameter-capacity-faPOSaLz.mjs.map → bind-parameter-capacity-Bjgx1lMC.mjs.map} +1 -1
  16. package/dist/builder-B4n-7I7Q.mjs +2 -0
  17. package/dist/{builder-ClblW6Lj.mjs.map → builder-B4n-7I7Q.mjs.map} +1 -1
  18. package/dist/bun-sql.d.mts +1 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sqlite.d.mts +1 -1
  21. package/dist/bun-sqlite.mjs +1 -1
  22. package/dist/bun-sqlite.mjs.map +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/cache.d.mts +1 -1
  28. package/dist/cache.mjs +1 -1
  29. package/dist/cache.mjs.map +1 -1
  30. package/dist/{canonical-json-JLUMrnoq.mjs → canonical-json-B6J5VbLv.mjs} +1 -1
  31. package/dist/{canonical-json-JLUMrnoq.mjs.map → canonical-json-B6J5VbLv.mjs.map} +1 -1
  32. package/dist/chain-DVuRxjPO.mjs +2 -0
  33. package/dist/chain-DVuRxjPO.mjs.map +1 -0
  34. package/dist/cli.mjs +1 -1
  35. package/dist/{client-DyIsSin0.d.mts → client-7ApJka0M.d.mts} +3 -3
  36. package/dist/client-Yqn0LqmI.mjs +2 -0
  37. package/dist/client-Yqn0LqmI.mjs.map +1 -0
  38. package/dist/{client-C1MxqFtt.mjs → client-l7dSOul5.mjs} +13 -13
  39. package/dist/client-l7dSOul5.mjs.map +1 -0
  40. package/dist/client.d.mts +1 -1
  41. package/dist/client.mjs +1 -1
  42. package/dist/{clock-CK41KO7t.mjs → clock-DXbsDHLj.mjs} +1 -1
  43. package/dist/{clock-CK41KO7t.mjs.map → clock-DXbsDHLj.mjs.map} +1 -1
  44. package/dist/config.d.mts +2 -2
  45. package/dist/config.mjs +1 -1
  46. package/dist/{current-CKQ4EgeM.mjs → current-nScH-oH5.mjs} +1 -1
  47. package/dist/{current-CKQ4EgeM.mjs.map → current-nScH-oH5.mjs.map} +1 -1
  48. package/dist/d1.d.mts +1 -1
  49. package/dist/d1.mjs +1 -1
  50. package/dist/d1.mjs.map +1 -1
  51. package/dist/{datetime-physical-codec-DfVmz14E.mjs → datetime-physical-codec-DTdvABny.mjs} +2 -2
  52. package/dist/{datetime-physical-codec-DfVmz14E.mjs.map → datetime-physical-codec-DTdvABny.mjs.map} +1 -1
  53. package/dist/driver-CK_IKqDa.mjs +2 -0
  54. package/dist/{driver-aqfbJdZC.mjs.map → driver-CK_IKqDa.mjs.map} +1 -1
  55. package/dist/{driver-DpQbSOUD.mjs → driver-DaBNytbz.mjs} +2 -2
  56. package/dist/{driver-DpQbSOUD.mjs.map → driver-DaBNytbz.mjs.map} +1 -1
  57. package/dist/driver.d.mts +1 -1
  58. package/dist/driver.mjs +1 -1
  59. package/dist/error-mapping-D--MVRCY.mjs +2 -0
  60. package/dist/error-mapping-D--MVRCY.mjs.map +1 -0
  61. package/dist/every-6VrIclsx.mjs +2 -0
  62. package/dist/{every-BUf842ai.mjs.map → every-6VrIclsx.mjs.map} +1 -1
  63. package/dist/{fs-estate-BXNX7l62.mjs → fs-estate-CfvH8Fxa.mjs} +2 -2
  64. package/dist/{fs-estate-BXNX7l62.mjs.map → fs-estate-CfvH8Fxa.mjs.map} +1 -1
  65. package/dist/{geo-area-codec-DQpSEgSD.mjs → geo-area-codec-DvHcWF3g.mjs} +2 -2
  66. package/dist/{geo-area-codec-DQpSEgSD.mjs.map → geo-area-codec-DvHcWF3g.mjs.map} +1 -1
  67. package/dist/geo-point-codec-CIZxuIvE.mjs +2 -0
  68. package/dist/geo-point-codec-CIZxuIvE.mjs.map +1 -0
  69. package/dist/{hydration-BK6vRndL.mjs → hydration-BUBkHlCK.mjs} +2 -2
  70. package/dist/{hydration-BK6vRndL.mjs.map → hydration-BUBkHlCK.mjs.map} +1 -1
  71. package/dist/identifier-conversion-BXrBYgAq.mjs +2 -0
  72. package/dist/{identifier-conversion-8ldidfgu.mjs.map → identifier-conversion-BXrBYgAq.mjs.map} +1 -1
  73. package/dist/{identity-Bu6jbgym.mjs → identity-BtuwgqhS.mjs} +2 -2
  74. package/dist/{identity-Bu6jbgym.mjs.map → identity-BtuwgqhS.mjs.map} +1 -1
  75. package/dist/{index-Ci8b13Lm.d.mts → index-CsO6vG2h.d.mts} +71 -14
  76. package/dist/index.d.mts +2 -2
  77. package/dist/index.mjs +1 -1
  78. package/dist/index.mjs.map +1 -1
  79. package/dist/insert-value-Cbp_bNxj.mjs +2 -0
  80. package/dist/insert-value-Cbp_bNxj.mjs.map +1 -0
  81. package/dist/instrumentation.d.mts +1 -1
  82. package/dist/instrumentation.mjs +1 -1
  83. package/dist/{invariant-BnLYqsHO.mjs → invariant-Dw9UB49x.mjs} +1 -1
  84. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-Dw9UB49x.mjs.map} +1 -1
  85. package/dist/{json-number-CAfNAqDB.mjs → json-number-ChtP7ZeY.mjs} +1 -1
  86. package/dist/{json-number-CAfNAqDB.mjs.map → json-number-ChtP7ZeY.mjs.map} +1 -1
  87. package/dist/{key-DJXcPZR_.mjs → key-Cz83fdLO.mjs} +2 -2
  88. package/dist/{key-DJXcPZR_.mjs.map → key-Cz83fdLO.mjs.map} +1 -1
  89. package/dist/keys-EP1Eq2eD.mjs +2 -0
  90. package/dist/keys-EP1Eq2eD.mjs.map +1 -0
  91. package/dist/{libsql-Dmtj0O4E.mjs → libsql-ClGi2zY2.mjs} +3 -3
  92. package/dist/{libsql-Dmtj0O4E.mjs.map → libsql-ClGi2zY2.mjs.map} +1 -1
  93. package/dist/libsql.d.mts +1 -1
  94. package/dist/libsql.mjs +1 -1
  95. package/dist/libsql.mjs.map +1 -1
  96. package/dist/{memory-b-dafk9S.mjs → memory-B1GnzgZr.mjs} +2 -2
  97. package/dist/{memory-b-dafk9S.mjs.map → memory-B1GnzgZr.mjs.map} +1 -1
  98. package/dist/migrations/mysql.d.mts +5 -5
  99. package/dist/migrations/mysql.mjs +1 -1
  100. package/dist/migrations/postgres.d.mts +5 -5
  101. package/dist/migrations/postgres.mjs +1 -1
  102. package/dist/migrations/sqlite.d.mts +5 -5
  103. package/dist/migrations/sqlite.mjs +1 -1
  104. package/dist/migrations/storage/durable-object.d.mts +1 -1
  105. package/dist/migrations/storage/durable-object.mjs +1 -1
  106. package/dist/migrations/storage/fs.d.mts +1 -1
  107. package/dist/migrations/storage/fs.mjs +1 -1
  108. package/dist/migrations/storage/r2.d.mts +1 -1
  109. package/dist/migrations/storage/r2.mjs +1 -1
  110. package/dist/migrations/tenant.d.mts +3 -3
  111. package/dist/migrations/tenant.mjs +1 -1
  112. package/dist/migrations.d.mts +5 -5
  113. package/dist/migrations.mjs +1 -1
  114. package/dist/model-DsXZ_pHE.mjs +2 -0
  115. package/dist/model-DsXZ_pHE.mjs.map +1 -0
  116. package/dist/mysql-adapter-D-Dq2FN9.mjs +2 -0
  117. package/dist/mysql-adapter-D-Dq2FN9.mjs.map +1 -0
  118. package/dist/{mysql-DAaUSeBw.mjs → mysql-hoo290Dd.mjs} +6 -6
  119. package/dist/{mysql-DAaUSeBw.mjs.map → mysql-hoo290Dd.mjs.map} +1 -1
  120. package/dist/mysql2.d.mts +1 -1
  121. package/dist/mysql2.mjs +1 -1
  122. package/dist/mysql2.mjs.map +1 -1
  123. package/dist/{native-types-BbKWN3JV.mjs → native-types-CQH05hcr.mjs} +1 -1
  124. package/dist/{native-types-BbKWN3JV.mjs.map → native-types-CQH05hcr.mjs.map} +1 -1
  125. package/dist/neon-http.d.mts +1 -1
  126. package/dist/neon-http.mjs +1 -1
  127. package/dist/neon-http.mjs.map +1 -1
  128. package/dist/normalized-result-23DWxZVY.mjs +2 -0
  129. package/dist/{normalized-result-VunNi4ID.mjs.map → normalized-result-23DWxZVY.mjs.map} +1 -1
  130. package/dist/{object-store-BHyP-LEI.d.mts → object-store-9VfS-3sY.d.mts} +4 -4
  131. package/dist/{object-store-I1MyfM72.mjs → object-store-DdgcT8d9.mjs} +2 -2
  132. package/dist/{object-store-I1MyfM72.mjs.map → object-store-DdgcT8d9.mjs.map} +1 -1
  133. package/dist/on.d.mts +80 -0
  134. package/dist/on.mjs +2 -0
  135. package/dist/on.mjs.map +1 -0
  136. package/dist/ordering.d.mts +101 -0
  137. package/dist/ordering.mjs +11 -0
  138. package/dist/ordering.mjs.map +1 -0
  139. package/dist/permissions.d.mts +1 -1
  140. package/dist/permissions.mjs +1 -1
  141. package/dist/pg.d.mts +1 -1
  142. package/dist/pg.mjs +1 -1
  143. package/dist/pg.mjs.map +1 -1
  144. package/dist/pglite.d.mts +1 -1
  145. package/dist/pglite.mjs +1 -1
  146. package/dist/{physical-CAZ_LauY.mjs → physical-t_gDjUCD.mjs} +2 -2
  147. package/dist/{physical-CAZ_LauY.mjs.map → physical-t_gDjUCD.mjs.map} +1 -1
  148. package/dist/pinned-session-De2rDjdO.mjs +2 -0
  149. package/dist/{pinned-session-D8bM5obl.mjs.map → pinned-session-De2rDjdO.mjs.map} +1 -1
  150. package/dist/planetscale.d.mts +1 -1
  151. package/dist/planetscale.mjs +1 -1
  152. package/dist/planetscale.mjs.map +1 -1
  153. package/dist/{planner-BDLdDieE.d.mts → planner-Cc3ABIUU.d.mts} +22 -1
  154. package/dist/{postgres-HaFcFACt.mjs → postgres-CqcP_qv-.mjs} +44 -37
  155. package/dist/postgres-CqcP_qv-.mjs.map +1 -0
  156. package/dist/postgres-adapter-CYZAL2uo.mjs +2 -0
  157. package/dist/{postgres-adapter-CnZjhvG1.mjs.map → postgres-adapter-CYZAL2uo.mjs.map} +1 -1
  158. package/dist/postgres-adapter-_o6EWuxW.mjs +2 -0
  159. package/dist/postgres-adapter-_o6EWuxW.mjs.map +1 -0
  160. package/dist/postgres-result-D94PyZ78.mjs +2 -0
  161. package/dist/{postgres-result-D4_yZqO8.mjs.map → postgres-result-D94PyZ78.mjs.map} +1 -1
  162. package/dist/postgres.d.mts +1 -1
  163. package/dist/postgres.mjs +1 -1
  164. package/dist/postgres.mjs.map +1 -1
  165. package/dist/{provider-limits-CpitUqW6.mjs → provider-limits-kO9B3KCF.mjs} +2 -2
  166. package/dist/{provider-limits-CpitUqW6.mjs.map → provider-limits-kO9B3KCF.mjs.map} +1 -1
  167. package/dist/{validation-DN1N2OdK.mjs → query-CTna5P9o.mjs} +2 -2
  168. package/dist/query-CTna5P9o.mjs.map +1 -0
  169. package/dist/{relation-bound-5ChGF3n5.mjs → relation-bound-5hindjxU.mjs} +1 -1
  170. package/dist/{relation-bound-5ChGF3n5.mjs.map → relation-bound-5hindjxU.mjs.map} +1 -1
  171. package/dist/{result-parsing-BX3_3Q15.mjs → result-parsing-Dkgy-xcy.mjs} +1 -1
  172. package/dist/{result-parsing-BX3_3Q15.mjs.map → result-parsing-Dkgy-xcy.mjs.map} +1 -1
  173. package/dist/result-shape-uaCsF_SZ.mjs +2 -0
  174. package/dist/{result-shape-BuGfArOr.mjs.map → result-shape-uaCsF_SZ.mjs.map} +1 -1
  175. package/dist/rows-AtX0guAb.mjs +2 -0
  176. package/dist/rows-AtX0guAb.mjs.map +1 -0
  177. package/dist/scalar-CZ_q89Hc.mjs +4 -0
  178. package/dist/scalar-CZ_q89Hc.mjs.map +1 -0
  179. package/dist/schema/json.d.mts +1 -1
  180. package/dist/schema/json.mjs +1 -1
  181. package/dist/schema/json.mjs.map +1 -1
  182. package/dist/schema-CZTCxG2p.mjs +2 -0
  183. package/dist/{schema-B_Bc7TQ2.mjs.map → schema-CZTCxG2p.mjs.map} +1 -1
  184. package/dist/{schema-introspection-BqN7d_sA.mjs → schema-introspection-DoZHc1o7.mjs} +2 -2
  185. package/dist/{schema-introspection-BqN7d_sA.mjs.map → schema-introspection-DoZHc1o7.mjs.map} +1 -1
  186. package/dist/schema.d.mts +1 -1
  187. package/dist/schema.mjs +1 -1
  188. package/dist/{select-assembly-BP8c4O-0.mjs → select-assembly-BtNtBsUh.mjs} +2 -2
  189. package/dist/select-assembly-BtNtBsUh.mjs.map +1 -0
  190. package/dist/{settle-B9Vg1FnP.mjs → settle-v6QhvFkm.mjs} +2 -2
  191. package/dist/{settle-B9Vg1FnP.mjs.map → settle-v6QhvFkm.mjs.map} +1 -1
  192. package/dist/{sha256-DDEbgnTU.mjs → sha256-D_fCV62w.mjs} +1 -1
  193. package/dist/{sha256-DDEbgnTU.mjs.map → sha256-D_fCV62w.mjs.map} +1 -1
  194. package/dist/soft-delete.d.mts +1 -1
  195. package/dist/{sql-BR8ZzKn8.mjs → sql-DGtEeP8z.mjs} +1 -1
  196. package/dist/{sql-BR8ZzKn8.mjs.map → sql-DGtEeP8z.mjs.map} +1 -1
  197. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CV2qkIKN.mjs} +1 -1
  198. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CV2qkIKN.mjs.map} +1 -1
  199. package/dist/sql.d.mts +1 -1
  200. package/dist/sql.mjs +1 -1
  201. package/dist/sqlite-adapter-CnAwmszh.mjs +2 -0
  202. package/dist/sqlite-adapter-CnAwmszh.mjs.map +1 -0
  203. package/dist/{sqlite-utils-CFInz2yY.mjs → sqlite-utils-DztTzv08.mjs} +2 -2
  204. package/dist/{sqlite-utils-CFInz2yY.mjs.map → sqlite-utils-DztTzv08.mjs.map} +1 -1
  205. package/dist/sqlite3.d.mts +1 -1
  206. package/dist/sqlite3.mjs +1 -1
  207. package/dist/sqlite3.mjs.map +1 -1
  208. package/dist/{standard-sql-wRMNi-Yg.mjs → standard-sql-Ci8ROrql.mjs} +2 -2
  209. package/dist/{standard-sql-wRMNi-Yg.mjs.map → standard-sql-Ci8ROrql.mjs.map} +1 -1
  210. package/dist/{suppressed-failure-Bdo2aK81.mjs → suppressed-failure-DO0ej03b.mjs} +1 -1
  211. package/dist/{suppressed-failure-Bdo2aK81.mjs.map → suppressed-failure-DO0ej03b.mjs.map} +1 -1
  212. package/dist/to-many-BtLpp5cW.mjs +2 -0
  213. package/dist/{to-many-CUBK3CTd.mjs.map → to-many-BtLpp5cW.mjs.map} +1 -1
  214. package/dist/{transaction-operation-C3Jbblbl.mjs → transaction-operation-Km-Gr-a3.mjs} +1 -1
  215. package/dist/{transaction-operation-C3Jbblbl.mjs.map → transaction-operation-Km-Gr-a3.mjs.map} +1 -1
  216. package/dist/{types-BNR3u6hH.mjs → types-C4v6iAmY.mjs} +1 -1
  217. package/dist/{types-BNR3u6hH.mjs.map → types-C4v6iAmY.mjs.map} +1 -1
  218. package/dist/{utils-Be91XL14.mjs → utils-CAACs9Jw.mjs} +3 -3
  219. package/dist/utils-CAACs9Jw.mjs.map +1 -0
  220. package/dist/v-Pb_jJOjC.mjs +2 -0
  221. package/dist/{v-lthABIXD.mjs.map → v-Pb_jJOjC.mjs.map} +1 -1
  222. package/dist/validation-BSpO4DjI.mjs +2 -0
  223. package/dist/{validation-BfJaNYMf.mjs.map → validation-BSpO4DjI.mjs.map} +1 -1
  224. package/dist/validation-pfpKPPZ_.mjs +2 -0
  225. package/dist/validation-pfpKPPZ_.mjs.map +1 -0
  226. package/dist/validation.d.mts +1 -1
  227. package/dist/validation.mjs +1 -1
  228. package/dist/validator-Dthaj1Hz.mjs +2 -0
  229. package/dist/validator-Dthaj1Hz.mjs.map +1 -0
  230. package/dist/version-DvynkoaW.mjs +2 -0
  231. package/dist/{version-DAFcmokN.mjs.map → version-DvynkoaW.mjs.map} +1 -1
  232. package/dist/write-sinks-3IKCDF-S.mjs +2 -0
  233. package/dist/write-sinks-3IKCDF-S.mjs.map +1 -0
  234. package/dist/writes-BX5fLiw5.mjs +2 -0
  235. package/dist/writes-BX5fLiw5.mjs.map +1 -0
  236. package/package.json +55 -15
  237. package/dist/bind-parameter-capacity-faPOSaLz.mjs +0 -2
  238. package/dist/builder-ClblW6Lj.mjs +0 -2
  239. package/dist/chain-C1VPkUpC.mjs +0 -2
  240. package/dist/chain-C1VPkUpC.mjs.map +0 -1
  241. package/dist/client-C1MxqFtt.mjs.map +0 -1
  242. package/dist/client-DHf2ZfRe.mjs +0 -2
  243. package/dist/client-DHf2ZfRe.mjs.map +0 -1
  244. package/dist/driver-aqfbJdZC.mjs +0 -2
  245. package/dist/error-mapping-Zett_Pnt.mjs +0 -2
  246. package/dist/error-mapping-Zett_Pnt.mjs.map +0 -1
  247. package/dist/every-BUf842ai.mjs +0 -2
  248. package/dist/geo-point-codec-DcUTvoEg.mjs +0 -2
  249. package/dist/geo-point-codec-DcUTvoEg.mjs.map +0 -1
  250. package/dist/identifier-conversion-8ldidfgu.mjs +0 -2
  251. package/dist/mysql-adapter-BrkDrfin.mjs +0 -2
  252. package/dist/mysql-adapter-BrkDrfin.mjs.map +0 -1
  253. package/dist/normalized-result-VunNi4ID.mjs +0 -2
  254. package/dist/pinned-session-D8bM5obl.mjs +0 -2
  255. package/dist/postgres-HaFcFACt.mjs.map +0 -1
  256. package/dist/postgres-adapter-BhNE_3b-.mjs +0 -2
  257. package/dist/postgres-adapter-BhNE_3b-.mjs.map +0 -1
  258. package/dist/postgres-adapter-CnZjhvG1.mjs +0 -2
  259. package/dist/postgres-result-D4_yZqO8.mjs +0 -2
  260. package/dist/result-shape-BuGfArOr.mjs +0 -2
  261. package/dist/rows-BlONp14o.mjs +0 -2
  262. package/dist/rows-BlONp14o.mjs.map +0 -1
  263. package/dist/scalar-B3WLZzJj.mjs +0 -4
  264. package/dist/scalar-B3WLZzJj.mjs.map +0 -1
  265. package/dist/schema-B_Bc7TQ2.mjs +0 -2
  266. package/dist/select-assembly-BP8c4O-0.mjs.map +0 -1
  267. package/dist/sqlite-adapter-CF-m7LIP.mjs +0 -2
  268. package/dist/sqlite-adapter-CF-m7LIP.mjs.map +0 -1
  269. package/dist/to-many-CUBK3CTd.mjs +0 -2
  270. package/dist/utils-Be91XL14.mjs.map +0 -1
  271. package/dist/v-lthABIXD.mjs +0 -2
  272. package/dist/validation-BfJaNYMf.mjs +0 -2
  273. package/dist/validation-DN1N2OdK.mjs.map +0 -1
  274. package/dist/validator-BJhI364k.mjs +0 -2
  275. package/dist/validator-BJhI364k.mjs.map +0 -1
  276. package/dist/version-DAFcmokN.mjs +0 -2
  277. /package/dist/{contract-Dw0FR78e.d.mts → contract-CYl0OzhZ.d.mts} +0 -0
  278. /package/dist/{sql-Q_twK-wW.d.mts → sql-BnXk8adi.d.mts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-DsXZ_pHE.mjs","names":["#state","#internal","#state","#internal","#withForeignKeyAction","#localFields","v","#state","#internal","model","#names","#nameRegistry","#scalarFieldNames","#relationNames"],"sources":["../src/schema/record.ts","../src/schema/relation/polymorphic.ts","../src/schema/relation/to-one.ts","../src/schema/model/helper.ts","../src/schema/model/model.ts"],"sourcesContent":["// Records keyed by DATA.\n//\n// A schema is built from maps whose keys come from somewhere else: a model\n// shape's field key, a document's model/field/variant key, an enum reference, a\n// default's own object keys. `record[key] = value` is not a safe way to build\n// such a map, because `__proto__` is an accessor on `Object.prototype`:\n// assigning through it sets a prototype and creates NO own key. The entry\n// disappears, and what is left is a well-formed object, so nothing downstream\n// can notice the loss.\n//\n// Reading has the mirror problem: `record[key]` resolves inherited members, so\n// a data key of `__proto__`, `constructor` or `toString` answers something the\n// map never held.\n//\n// One owner for both, used everywhere a key comes from data — the JSON\n// document's maps and `s.model(...)`'s classified member maps alike. It carries\n// no refusal: whether a key is a legal identifier is `isValidSchemaIdentifier`'s\n// question, asked at hydration and by the document reader, and the answer is the\n// same whichever way the key was written. The document READER needs neither\n// helper, because it asks that question before anything is written.\n\n/** A map with no inherited members, so a data key can only find what was put. */\nexport function emptyRecord<T>(): Record<string, T> {\n return Object.create(null);\n}\n\n/** Write one own key, whatever it is called. */\nexport function put<T>(target: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Read one own key, or nothing. */\nexport function own<T>(\n source: Record<string, T> | undefined,\n key: string\n): T | undefined {\n if (source === undefined || !Object.hasOwn(source, key)) return;\n return source[key];\n}\n","// Variant target domains: the normalization owner and the two variant terminals.\n//\n// \"Polymorphic\" is not a relation family. It is the derived observation that a\n// declaration's TARGET DOMAIN holds named variants instead of one model, which\n// is why the two variant terminals are reached through the same `s.toOne` /\n// `s.toMany` factories as the model-target ones. What is irreducibly different\n// is the legal local configuration: a row-held variant to-one may be\n// `.optional()` and owns no public foreign key, and a member-junction variant\n// to-many names one junction per variant through an exact `.through(...)` map.\n\nimport type { Model } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport {\n createTargetSettlement,\n declaredKeys,\n hasExactKeys,\n isPlainRecord,\n normalizeRelationName,\n type RelationBuilder,\n readCallerProperty,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n Getter,\n RelationInternal,\n Replace,\n VariantEntry,\n VariantJunctionOverride,\n VariantManyEntry,\n VariantToManyState,\n VariantToOneState,\n} from \"./types\";\n\n/**\n * The stored-discriminator grammar. A stored value is written to a physical\n * column and read back by migrations and predicates, so it admits namespaced\n * and versioned spellings the public variant key does not.\n */\nconst STORED_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/;\n\nconst THROUGH_ENTRY_KEYS = [\"table\", \"source\", \"target\"] as const;\n\n// =============================================================================\n// FACTORY-LEVEL TYPES\n// =============================================================================\n\nexport type VariantGetterMap = Readonly<Record<string, Getter>>;\n\n/**\n * The map overload's phantom refusal.\n *\n * It is NOT redundant with {@link GetterOnly}. With the map overload first and\n * an unconstrained getter overload second, a structurally-map argument that\n * fails this guard would otherwise fall through to the getter overload, whose\n * conditional return answers `never` — and `never` is assignable to a model\n * shape, so the refusal would disappear entirely. This guard uniquely owns\n * \"structurally a map, but not a legal variant map\"; `GetterOnly` uniquely owns\n * \"not a map at all and not a getter\".\n */\nexport type VariantMapGuard<Entries> = string extends keyof Entries\n ? {\n readonly \"a variant map needs literal keys, not a string index signature\": never;\n }\n : [keyof Entries] extends [never]\n ? { readonly \"a variant map needs at least one variant\": never }\n : unknown;\n\nexport type VariantOptions<Entries> = {\n readonly values: { readonly [Key in keyof Entries]: string };\n};\n\n/**\n * The whole options bag is exact, not only `values`: a NON-FRESH bag with a\n * sibling key beside `values` sails through excess-property checking, so the\n * unknown keys are refused structurally.\n */\nexport type ExactVariantOptions<Options, Entries> = Options extends undefined\n ? unknown\n : Record<Exclude<keyof Options, \"values\">, never> & {\n readonly values: Record<\n Exclude<\n keyof (Options extends { readonly values: infer Values }\n ? Values\n : never),\n keyof Entries\n >,\n never\n >;\n };\n\n/**\n * Normalized entries carry the getter's exact type and a plain `string` stored\n * value: the stored discriminator is runtime storage, never a public result\n * discriminator, so carrying its literal would be a public type parameter no\n * consumer reads.\n */\nexport type NormalizedOneEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n };\n};\n\nexport type NormalizedManyEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n readonly junction?: VariantJunctionOverride;\n };\n};\n\ntype VariantEntriesOfState<State> = State extends {\n readonly target: { readonly entries: infer Entries };\n}\n ? Entries\n : never;\n\ntype VariantThroughMap<Entries> = {\n readonly [Key in keyof Entries]: VariantJunctionOverride;\n};\n\ntype ExactVariantThroughMap<Given, Entries> = Record<\n Exclude<keyof Given, keyof Entries>,\n never\n> & {\n readonly [Key in keyof Given]: Record<\n Exclude<keyof Given[Key], keyof VariantJunctionOverride>,\n never\n >;\n};\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACES\n// =============================================================================\n\n/** A slot that holds at most one membership across its variants. */\nexport type VariantToOneRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToOneRelation<Replace<State, { readonly name: Name }>>;\n optional(): VariantToOneRelation<Replace<State, { readonly optional: true }>>;\n};\n\n/**\n * A slot that holds a collection across its variants. No `.optional()`: an\n * empty collection is already the empty case.\n */\nexport type VariantToManyRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToManyRelation<Replace<State, { readonly name: Name }>>;\n through<\n const ThroughMap extends VariantThroughMap<VariantEntriesOfState<State>>,\n >(\n map: ThroughMap &\n ExactVariantThroughMap<ThroughMap, VariantEntriesOfState<State>>\n ): VariantToManyRelation<State>;\n};\n\n// =============================================================================\n// NORMALIZATION\n// =============================================================================\n\n/**\n * Read the target map and its options ONCE, judge every structurally knowable\n * fact, and build the single normalized entry map. There is no separately\n * stored `targets`, `values` or `through` map to keep in sync.\n *\n * Every own property at both map levels is read exactly once here and pinned as\n * a plain value: a live accessor could otherwise answer validation with one\n * value and the storage builder with another. Reading a property's value does\n * not invoke a target thunk; getters are stored as functions and stay lazy.\n */\nexport function normalizeVariantEntries(\n builder: RelationBuilder,\n variants: unknown,\n options: unknown\n): Readonly<Record<string, VariantEntry>> {\n if (!isPlainRecord(variants)) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A relation target is either `() => model` or a plain map of named `() => model` getters\"\n );\n }\n const variantKeys = declaredKeys(variants);\n if (variantKeys.length === 0) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A variant map needs at least one variant\"\n );\n }\n const storedValues = readStoredValues(builder, variantKeys, options);\n const entries: Record<string, VariantEntry> = {};\n for (const variantKey of variantKeys) {\n if (!isValidSchemaIdentifier(variantKey)) {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant key '${variantKey}' is not a valid schema identifier`\n );\n }\n const getter = readCallerProperty(\n builder,\n variants,\n variantKey,\n `target.${variantKey}`\n );\n if (typeof getter !== \"function\") {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant '${variantKey}' must be a lazy getter; write \\`() => model\\` rather than the model itself`\n );\n }\n entries[variantKey] = Object.freeze({\n getter,\n storedValue: storedValues[variantKey] ?? variantKey,\n });\n }\n return Object.freeze(entries);\n}\n\n/**\n * The stored discriminator per variant: each public key by default, or the\n * exact `values` bag when one is supplied. An explicit `undefined` is\n * equivalent to omission; `{}` is not, because it declares an options bag\n * without the one option it may carry.\n */\nfunction readStoredValues(\n builder: RelationBuilder,\n variantKeys: readonly string[],\n options: unknown\n): Record<string, string> {\n if (options === undefined) return {};\n if (!isPlainRecord(options)) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options must be a plain `{ values }` record; omit the argument to use each variant key as its stored value\"\n );\n }\n if (!hasExactKeys(declaredKeys(options), [\"values\"])) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options carry exactly one key, `values`; omit the argument to use each variant key as its stored value\"\n );\n }\n const values = readCallerProperty(\n builder,\n options,\n \"values\",\n \"options.values\"\n );\n if (!isPlainRecord(values)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n \"`values` must be a plain record keyed by every variant\"\n );\n }\n const valueKeys = declaredKeys(values);\n if (!hasExactKeys(valueKeys, variantKeys)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n `\\`values\\` must be exact over the variant keys ${renderKeys(variantKeys)}; it declares ${renderKeys(valueKeys)}`\n );\n }\n const storedValues: Record<string, string> = {};\n const claimed = new Set<string>();\n for (const variantKey of variantKeys) {\n const storedValue = readCallerProperty(\n builder,\n values,\n variantKey,\n `options.values.${variantKey}`\n );\n if (typeof storedValue !== \"string\" || !STORED_VALUE.test(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value for variant '${variantKey}' must match the stored-discriminator grammar`\n );\n }\n if (claimed.has(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value '${storedValue}' is declared for more than one variant`\n );\n }\n claimed.add(storedValue);\n storedValues[variantKey] = storedValue;\n }\n return storedValues;\n}\n\nfunction renderKeys(keys: readonly string[]): string {\n return `[${keys.map((key) => `'${key}'`).join(\", \")}]`;\n}\n\n/**\n * Fold one member-junction override into each normalized entry. The outer map\n * is exact over the variants and every inner value is exact — the runtime\n * mirror of the `.through()` type contract, and the reason there is no second\n * `through` map to keep in sync with the entries.\n */\nfunction foldMemberJunctions(\n entries: Readonly<Record<string, VariantEntry>>,\n through: unknown\n): Readonly<Record<string, VariantManyEntry>> {\n const variantKeys = Object.keys(entries);\n if (!isPlainRecord(through)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n \"`.through()` takes a plain map keyed by every variant\"\n );\n }\n if (!hasExactKeys(declaredKeys(through), variantKeys)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n `\\`.through()\\` must be exact over the variant keys ${renderKeys(variantKeys)}`\n );\n }\n const folded: Record<string, VariantManyEntry> = {};\n for (const [variantKey, entry] of Object.entries(entries)) {\n const override = readCallerProperty(\n \"s.toMany\",\n through,\n variantKey,\n `through.${variantKey}`\n );\n folded[variantKey] = Object.freeze({\n ...entry,\n junction: readJunctionOverride(variantKey, override),\n });\n }\n return Object.freeze(folded);\n}\n\nfunction readJunctionOverride(\n variantKey: string,\n override: unknown\n): VariantJunctionOverride {\n const path = `through.${variantKey}`;\n if (!isPlainRecord(override)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' must be a plain \\`{ table, source, target }\\` record`\n );\n }\n const table = readCallerProperty(\n \"s.toMany\",\n override,\n \"table\",\n `${path}.table`\n );\n const source = readCallerProperty(\n \"s.toMany\",\n override,\n \"source\",\n `${path}.source`\n );\n const target = readCallerProperty(\n \"s.toMany\",\n override,\n \"target\",\n `${path}.target`\n );\n if (\n !hasExactKeys(declaredKeys(override), THROUGH_ENTRY_KEYS) ||\n typeof table !== \"string\" ||\n typeof source !== \"string\" ||\n typeof target !== \"string\"\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' declares exactly \\`table\\`, \\`source\\` and \\`target\\`, all strings`\n );\n }\n return Object.freeze({ table, source, target });\n}\n\n// =============================================================================\n// TERMINALS\n// =============================================================================\n\n/**\n * Private terminal machinery. None of the four terminal classes is exported\n * from its module, let alone from the package: callers see only the\n * capabilities the two factories return. The two constructor helpers below are\n * the whole cross-module surface.\n */\nclass VariantToOne {\n readonly #state: VariantToOneState;\n readonly #internal: RelationInternal<VariantToOneState>;\n\n constructor(state: VariantToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToOne {\n return new VariantToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n optional(): VariantToOne {\n return new VariantToOne({ ...this.#state, optional: true });\n }\n\n get \"~\"(): RelationInternal<VariantToOneState> {\n return this.#internal;\n }\n}\n\nclass VariantToMany {\n readonly #state: VariantToManyState;\n readonly #internal: RelationInternal<VariantToManyState>;\n\n constructor(state: VariantToManyState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n name: normalizeRelationName(\"s.toMany\", name),\n });\n }\n\n through(map: unknown): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n target: {\n kind: \"variants\",\n entries: foldMemberJunctions(this.#state.target.entries, map),\n },\n });\n }\n\n get \"~\"(): RelationInternal<VariantToManyState> {\n return this.#internal;\n }\n}\n\n/** Construct the row-held variant terminal for `s.toOne`. */\nexport function variantToOneTerminal(state: VariantToOneState): AnyRelation {\n return new VariantToOne(state);\n}\n\n/** Construct the member-junction variant terminal for `s.toMany`. */\nexport function variantToManyTerminal(state: VariantToManyState): AnyRelation {\n return new VariantToMany(state);\n}\n\nfunction readVariantGetter(\n state: VariantToOneState | VariantToManyState,\n variantKey: string | undefined\n): unknown {\n if (variantKey === undefined) return undefined;\n const entry = state.target.entries[variantKey];\n return entry === undefined ? undefined : entry.getter;\n}\n\n// =============================================================================\n// RESOLVED VARIANT STORAGE COLUMN\n// =============================================================================\n// Resolution OUTPUT, not declaration state: one private column the variant\n// row-storage owner derives, carried on the resolved edge and read by the\n// serializer and the engine. The descriptors that used to sit beside it are\n// gone — the resolved edge IS the topology, and a second copy of it on the\n// model was a second answer to every question the edge already answers.\n\nexport interface PolymorphicStorageColumn {\n readonly name: string;\n readonly scalar: Scalar;\n readonly nullable: boolean;\n /**\n * The KEY this private column stands in for, when it stands in for one.\n *\n * A row carrier's id column holds every variant's primary key, and what\n * those keys hold — an identifier domain above all — may be DERIVED rather\n * than declared: the ordinary one-to-one child whose primary key IS its\n * parent foreign key declares nothing and still holds uuids. The scalar\n * alone cannot answer that (derivation is keyed by model and field, never by\n * a scalar instance two models may share), so the column carries the pair\n * the one lookup takes. Every variant's key agrees on the answer or the\n * carrier does not exist — that agreement is what the identifier-domain\n * derivation refuses when it fails — so the FIRST member's key is the\n * carrier's key.\n *\n * The type discriminator column stands in for no key and carries none.\n */\n readonly reference?: {\n readonly model: Model<any>;\n readonly field: string;\n };\n}\n","// `s.toOne` — one of the two relation factories.\n//\n// The factory states the SLOT CARDINALITY (one) and its argument states the\n// TARGET DOMAIN (one model, or named variants). Which endpoint owns a foreign\n// key, whether the pair is one-to-one or many-to-one, and whether a model-target\n// slot may be empty are DERIVED later by the full-schema topology owner.\n\nimport {\n type ExactVariantOptions,\n type NormalizedOneEntries,\n normalizeVariantEntries,\n type VariantGetterMap,\n type VariantMapGuard,\n type VariantOptions,\n type VariantToOneRelation,\n variantToOneTerminal,\n} from \"./polymorphic\";\nimport {\n createTargetSettlement,\n normalizeFieldTuple,\n normalizeReferentialAction,\n normalizeRelationName,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n ForeignKeyDeclaration,\n Getter,\n GetterOnly,\n ModelToOneState,\n NonEmptyFieldTuple,\n ReferentialAction,\n RelationInternal,\n Replace,\n} from \"./types\";\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACE\n// =============================================================================\n\n/**\n * Referential actions exist only once a complete reference exists — they act on\n * a foreign key, and there is no foreign key to act on before\n * `.references(...)` completes the pair.\n */\ntype ForeignKeyActions<State> = {\n onDelete<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onDelete: Action }> }\n >\n : State\n >;\n onUpdate<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onUpdate: Action }> }\n >\n : State\n >;\n};\n\ntype ModelToOneCapabilities<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): ModelToOneRelation<Replace<State, { readonly name: Name }>>;\n fields<const Fields extends NonEmptyFieldTuple>(\n ...fields: Fields\n ): ReferencesStage<State, Fields>;\n};\n\n/**\n * A model-target singular slot. It exposes no `.optional()`: emptiness follows\n * from the nullability of a complete local foreign-key tuple, and a non-owning\n * singular view is derived nullable.\n */\nexport type ModelToOneRelation<State> = ModelToOneCapabilities<State> &\n (State extends { readonly foreignKey: ForeignKeyDeclaration }\n ? ForeignKeyActions<State>\n : unknown);\n\n/**\n * The transient value `.fields(...)` returns.\n *\n * It carries NO relation brand, so neither `ModelShape` nor any downstream\n * relation consumer can mistake an incomplete foreign key for trusted schema\n * state, and `s.model(...)` refuses it outright. It exposes only\n * `.references(...)` and `.name(...)`: a name must not be able to turn an\n * incomplete pair into schema truth.\n */\nexport type ReferencesStage<State, Fields extends NonEmptyFieldTuple> = {\n references<\n const References extends NonEmptyFieldTuple & {\n readonly length: Fields[\"length\"];\n },\n >(\n ...references: References\n ): ModelToOneRelation<\n Replace<\n State,\n {\n readonly foreignKey: Replace<\n State extends { readonly foreignKey: infer FK } ? FK : unknown,\n { readonly fields: Fields; readonly references: References }\n >;\n }\n >\n >;\n name<const Name extends string>(\n name: Name\n ): ReferencesStage<Replace<State, { readonly name: Name }>, Fields>;\n};\n\n// =============================================================================\n// PRIVATE TERMINALS\n// =============================================================================\n\nclass ModelToOne {\n readonly #state: ModelToOneState;\n readonly #internal: RelationInternal<ModelToOneState>;\n\n constructor(state: ModelToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement(() => this.#state.target.getter),\n });\n }\n\n name(name: string): ModelToOne {\n return new ModelToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n fields(...fields: string[]): PendingReferences {\n return new PendingReferences(\n this.#state,\n normalizeFieldTuple(\"s.toOne\", \"fields\", fields)\n );\n }\n\n onDelete(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onDelete\", action);\n }\n\n onUpdate(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onUpdate\", action);\n }\n\n /**\n * The type surface hides both action setters until `.references(...)` has\n * completed a foreign key. This refusal covers the route a type pin cannot:\n * a JavaScript caller placing a referential action on a slot that owns no\n * foreign key, where the action would otherwise have nowhere to be stored and\n * would be silently dropped.\n */\n #withForeignKeyAction(\n action: \"onDelete\" | \"onUpdate\",\n value: ReferentialAction\n ): ModelToOne {\n const foreignKey = this.#state.foreignKey;\n if (foreignKey === undefined) {\n refuseRelationInput(\n \"s.toOne\",\n action,\n `'${action}' is available only after \\`.fields(...).references(...)\\` declares a foreign key`\n );\n }\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze({\n ...foreignKey,\n [action]: normalizeReferentialAction(action, value),\n }),\n });\n }\n\n get \"~\"(): RelationInternal<ModelToOneState> {\n return this.#internal;\n }\n}\n\n/**\n * The transient references stage. It has no `\"~\"` accessor by design: that\n * absence is what makes an incomplete chain unusable as a model member.\n */\nclass PendingReferences {\n readonly #state: ModelToOneState;\n readonly #localFields: NonEmptyFieldTuple;\n\n constructor(state: ModelToOneState, localFields: NonEmptyFieldTuple) {\n this.#state = state;\n this.#localFields = localFields;\n }\n\n name(name: string): PendingReferences {\n return new PendingReferences(\n { ...this.#state, name: normalizeRelationName(\"s.toOne\", name) },\n this.#localFields\n );\n }\n\n references(...references: string[]): ModelToOne {\n const referenced = normalizeFieldTuple(\"s.toOne\", \"references\", references);\n if (referenced.length !== this.#localFields.length)\n refuseReferenceArity(referenced.length, this.#localFields.length);\n // Completing a second stage replaces the pair atomically and preserves the\n // endpoint's name and referential actions; the prior terminal is untouched.\n const prior = this.#state.foreignKey;\n const foreignKey: ForeignKeyDeclaration = {\n fields: this.#localFields,\n references: referenced,\n ...(prior?.onDelete === undefined ? {} : { onDelete: prior.onDelete }),\n ...(prior?.onUpdate === undefined ? {} : { onUpdate: prior.onUpdate }),\n };\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze(foreignKey),\n });\n }\n}\n\n/**\n * Is this model member a transient references stage?\n *\n * Deliberately nominal: a stage is only ever produced by `.fields(...)`, so an\n * `instanceof` test cannot be spoofed by a look-alike record, and the\n * `s.model(...)` boundary can refuse the one member shape that would otherwise\n * be silently dropped.\n */\nexport function isReferencesStage(value: unknown): boolean {\n return value instanceof PendingReferences;\n}\n\n// =============================================================================\n// FACTORY\n// =============================================================================\n\n/**\n * Declare a slot that holds AT MOST ONE membership.\n *\n * The map overload is declared first so a variant map is never swallowed by the\n * broad getter overload. Dispatch examines only the argument representation and\n * never invokes a getter.\n */\nexport function toOne<\n const Entries extends VariantGetterMap,\n const Options extends VariantOptions<Entries> | undefined = undefined,\n>(\n variants: Entries & VariantMapGuard<Entries>,\n options?: Options & ExactVariantOptions<Options, Entries>\n): VariantToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: {\n readonly kind: \"variants\";\n readonly entries: NormalizedOneEntries<Entries>;\n };\n}>;\nexport function toOne<const G>(getter: G & GetterOnly<G>): G extends Getter\n ? ModelToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: { readonly kind: \"model\"; readonly getter: G };\n }>\n : never;\nexport function toOne(target: unknown, options?: unknown): AnyRelation {\n if (typeof target === \"function\") {\n // biome-ignore lint/complexity/noArguments: distinguishes omission from explicit undefined without changing the factory's public arity\n if (arguments.length > 1) {\n refuseRelationInput(\n \"s.toOne\",\n \"options\",\n \"A model-target relation takes exactly one argument\"\n );\n }\n return new ModelToOne({\n kind: \"relation\",\n cardinality: \"one\",\n target: { kind: \"model\", getter: target },\n });\n }\n return variantToOneTerminal({\n kind: \"relation\",\n cardinality: \"one\",\n target: {\n kind: \"variants\",\n entries: normalizeVariantEntries(\"s.toOne\", target, options),\n },\n });\n}\n\nfunction refuseReferenceArity(referenced: number, local: number): never {\n return refuseRelationInput(\n \"s.toOne\",\n \"references\",\n `\\`.references(...)\\` declares ${referenced} field(s) against ${local} local field(s); a foreign key pairs them positionally`\n );\n}\n","import { emptyRecord } from \"@schema/record\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport { refuseRelationInput } from \"@schema/relation/terminal\";\n// Deep import: the references-stage predicate is the `s.model(...)` boundary's\n// own instrument and is deliberately not part of the relation package surface.\nimport { isReferencesStage } from \"@schema/relation/to-one\";\nimport type { Scalar } from \"@schema/scalars/base\";\n\n/**\n * Record of model fields - the canonical type for scalar and relation definitions.\n * A model field is either a scalar or a relation; ONE relation map holds both\n * target domains.\n */\nexport type AnyModelField = Scalar | AnyRelation;\nexport type ModelShape = Record<string, AnyModelField>;\n\n/**\n * The shape `s.model(...)` and `.extends(...)` accept: a model shape with no\n * member named `_count` or `_distance`, the names a selection's own outputs\n * reserve (relation counts, a distance). This is the compile-time spelling of\n * rule F010 for TypeScript callers; F010 (`memberNamesAreNotReserved`) stays\n * the contract for every caller. It constrains keys only and never reads a\n * member's type, so it cannot change what a shape infers. Each key's type is\n * its reason spelled as a string literal, so the diagnostic a caller reads\n * names it: no model member is a string, so nothing a shape can hold\n * satisfies it.\n */\nexport type DeclaredModelShape = ModelShape & {\n readonly _count?: \"`_count` is reserved for relation counts (F010)\";\n readonly _distance?: \"`_distance` is reserved for distance results (F010)\";\n};\n\nexport type NameFromKeys<\n TFields extends string[],\n TName extends string = \"\",\n> = TFields extends readonly [\n infer F extends string,\n ...infer R extends string[],\n]\n ? R extends []\n ? `${TName}_${F}`\n : NameFromKeys<R, TName extends \"\" ? F : `${TName}_${F}`>\n : never;\n\nexport interface CompoundConstraint<\n TFields extends string[],\n TName extends string | undefined = undefined,\n> {\n fields: TFields;\n name: TName extends undefined ? NameFromKeys<TFields> : TName;\n}\n\n/** Any compound constraint (for loose typing) */\nexport type AnyCompoundConstraint = CompoundConstraint<string[]>;\n\nexport type ToString<T> = T extends\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n ? `${T}`\n : never;\n\nexport type StringKeyOf<T extends Record<string, any>> = {\n [K in keyof T]: K extends string ? K : never;\n}[keyof T];\n\nexport type ScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar ? ToString<K> : never;\n}[keyof T];\n\n/** Fixed-decimal list keys, which have value semantics but no key semantics. */\nexport type DecimalListScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"] extends { type: \"decimal\"; array: true }\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** GeoPoint keys have value semantics but no portable key/order semantics. */\nexport type PointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonNullablePointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? T[K][\"~\"][\"state\"][\"nullable\"] extends true\n ? never\n : ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonPointScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Scalar keys except fixed-decimal lists, which cannot be physical keys. */\nexport type NonDecimalListScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : DecimalListScalarKeys<T>\n>;\n\n/** Scalar keys admitted in IDs, unique constraints, and foreign-key identity. */\nexport type PortableKeyScalarKeys<T extends ModelShape> = Exclude<\n NonDecimalListScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Extract relation keys from ModelState */\nexport type RelationKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends AnyRelation ? ToString<K> : never;\n}[keyof T];\n\nexport type RequiredScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"optional\"] extends true\n ? never\n : ToString<K>\n : never;\n}[keyof T];\n\nexport type UniqueScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"isId\"] extends true\n ? ToString<K>\n : T[K][\"~\"][\"state\"][\"isUnique\"] extends true\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** Numeric scalar types for aggregations (avg, sum) */\nexport type NumericScalarType = \"int\" | \"number\" | \"decimal\" | \"bigint\";\n\n/** Extract keys of numeric scalars from a ModelShape */\nexport type NumericScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"array\"] extends true\n ? never\n : T[K][\"~\"][\"state\"][\"type\"] extends NumericScalarType\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type ScalarMap<T extends ModelShape> = {\n [K in ScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\nexport type RelationMap<T extends ModelShape> = {\n [K in RelationKeys<T>]: T[K] extends AnyRelation ? T[K] : never;\n};\n\nexport type UniqueScalarMap<T extends ModelShape> = {\n [K in UniqueScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\n/**\n * ONE relation boundary, keyed on the internal brand.\n *\n * Trusted relation state originates only in `s.toOne` / `s.toMany`, and both\n * target domains carry `kind: \"relation\"` — so a model has one relation map and\n * no consumer has to ask which family a member belongs to. Scalars keep\n * `state.type`, so the two brands cannot collide.\n */\nfunction isRelation(value: unknown): value is AnyRelation {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n return (\n typeof state === \"object\" &&\n state !== null &&\n Reflect.get(state, \"kind\") === \"relation\"\n );\n}\n\nconst SCALAR_TYPES = new Set<string>([\n \"string\",\n \"int\",\n \"number\",\n \"decimal\",\n \"boolean\",\n \"datetime\",\n \"date\",\n \"time\",\n \"bigint\",\n \"json\",\n \"blob\",\n \"vector\",\n \"point\",\n \"enum\",\n]);\n\nfunction isScalar(value: unknown): value is Scalar {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n if (typeof state !== \"object\" || state === null) return false;\n const type = Reflect.get(state, \"type\");\n return typeof type === \"string\" && SCALAR_TYPES.has(type);\n}\n\n/**\n * The classified member maps are a PROJECTION of the shape: every member an\n * extractor recognizes appears in the map that claims it, under the key the\n * shape gave it. A shape key comes from the caller — a hand-written literal, a\n * generated schema, a JSON document's field name — so it can be any string, and\n * assigning into an ordinary object would lose a `__proto__` member to\n * `Object.prototype`'s setter. These maps come from `emptyRecord` and stay\n * private until complete: their null prototype makes every assignment an own\n * data entry, including `__proto__`, without defining a descriptor per member.\n *\n * Whether such a key is a LEGAL identifier is a separate question with a\n * separate owner (`isValidSchemaIdentifier`, enforced at hydration and by the\n * document reader). Keeping the member is what lets that owner name it.\n */\nexport const extractScalarMap = <T extends ModelShape>(fields: T) => {\n const scalars = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (isScalar(value)) {\n scalars[key] = value;\n }\n }\n return scalars as ScalarMap<T>;\n};\n\n/**\n * The `s.model(...)` member-classification boundary for relations.\n *\n * It gains exactly ONE refusal: a transient references stage — a chain that\n * started `.fields(...)` and never received `.references(...)` — is rejected\n * loudly rather than silently dropped, because that member declares a foreign\n * key the schema would then never have. Every other unrecognized member keeps\n * its existing silent-drop behavior; widening that is a separate decision.\n */\nexport const extractRelationMap = <T extends ModelShape>(fields: T) => {\n const relations = emptyRecord<AnyRelation>();\n for (const [key, value] of Object.entries(fields)) {\n if (isRelation(value)) {\n relations[key] = value;\n } else if (isReferencesStage(value)) {\n refuseRelationInput(\n \"s.model\",\n key,\n `Relation '${key}' started \\`.fields(...)\\` without \\`.references(...)\\`; complete the foreign key before using it as a model field`\n );\n }\n }\n return relations as RelationMap<T>;\n};\n\nexport const extractUniqueScalarMap = <T extends ModelShape>(fields: T) => {\n const uniques = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (\n isScalar(value) &&\n (value[\"~\"].state.isUnique || value[\"~\"].state.isId)\n ) {\n uniques[key] = value;\n }\n }\n return uniques as UniqueScalarMap<T>;\n};\n\nexport const getNameFromKeys = <\n Name extends string | undefined,\n TFields extends any[],\n>(\n name: Name,\n fields: TFields\n) => {\n return (\n name ??\n (fields.join(\"_\") as Name extends undefined ? NameFromKeys<TFields> : Name)\n );\n};\n","// Model Class Implementation\n// Defines database models with scalars and relations\n\nimport type { ObjectSchema, VibSchema } from \"@validation\";\nimport v from \"@validation/primitives/v\";\nimport { emptyRecord, put } from \"../record\";\nimport type { AnyRelation } from \"../relation\";\nimport type { Scalar } from \"../scalars/base\";\nimport type { HydratedSchemaNames, SchemaNames } from \"../scalars/common\";\nimport {\n type DeclaredModelShape,\n extractRelationMap,\n extractScalarMap,\n extractUniqueScalarMap,\n getNameFromKeys,\n type ModelShape,\n type NameFromKeys,\n type NonNullablePointScalarKeys,\n type PortableKeyScalarKeys,\n type RelationMap,\n type ScalarMap,\n type StringKeyOf,\n type UniqueScalarMap,\n} from \"./helper\";\n// Re-export types from helpers for external use\n\n// =============================================================================\n// TYPE INFERENCE HELPER\n// =============================================================================\n\nexport interface ModelState {\n shape: ModelShape;\n compoundId:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n compoundUniques:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n tableName: string | undefined;\n indexes: IndexDefinition[];\n omit: Record<string, true> | undefined;\n scalars: Record<string, Scalar>;\n /** ONE canonical relation map, holding both target domains in shape order. */\n relations: Record<string, AnyRelation>;\n uniques: Record<string, Scalar>;\n}\n\n/** Initial model projections stay named when a consumer emits recursive graphs. */\nexport interface InitialModelState<Shape extends ModelShape>\n extends ModelState {\n shape: Shape;\n scalars: ScalarMap<Shape>;\n relations: RelationMap<Shape>;\n uniques: UniqueScalarMap<Shape>;\n omit: undefined;\n}\n\n/**\n * Internal accessor return type for Model[\"~\"]\n * Explicit type annotation to avoid TS7056 (type too complex to serialize)\n */\nexport interface ModelInternal<T extends ModelState> {\n state: T;\n names: SchemaNames;\n nameRegistry: {\n fields: Map<string, SchemaNames>;\n };\n getFieldName: (key: string) => HydratedSchemaNames;\n /** Cached scalar field names (computed once on first access) */\n scalarFieldNames: string[];\n /** Cached relation names (computed once on first access) */\n relationNames: string[];\n}\n\n/**\n * The index kinds a schema may declare. The union is the whole of what any\n * dialect accepts, not what all of them accept — `validateIndexType` in\n * `migrations/drivers/base.ts` refuses each one on the dialects whose\n * `supportsIndexTypes` does not list it, by name, at push time.\n *\n * `fulltext` and `spatial` are here because MySQL's whole round trip already\n * exists and only this union could not spell it: the emitter writes the\n * `FULLTEXT`/`SPATIAL` prefix and refuses to combine either with `UNIQUE`\n * (`mysql/index.ts`), the introspection reads them back and normalizes MySQL's\n * `RTREE` to `spatial` (`mysql/introspect.ts`), the migration snapshot's\n * `IndexDef` already carries both (`migrations/types.ts`), and the capability\n * list already declares them. See Phase 10 item 6 in\n * `docs/architecture/query-performance-plan.md`.\n */\nexport type IndexType =\n | \"btree\"\n | \"hash\"\n | \"gin\"\n | \"gist\"\n | \"fulltext\"\n | \"spatial\";\n\nexport interface IndexOptions {\n name?: string;\n unique?: boolean;\n type?: IndexType;\n where?: string; // For partial indexes (PostgreSQL)\n}\n\ntype OrdinaryIndexOptions = Omit<IndexOptions, \"type\"> & {\n type?: Exclude<IndexType, \"spatial\">;\n};\n\ntype GeoPointSpatialIndexOptions = {\n name?: string;\n type: \"spatial\";\n unique?: never;\n where?: never;\n};\n\nexport interface IndexDefinition<\n Keys extends string[] = string[],\n O extends IndexOptions = IndexOptions,\n> {\n fields: Keys;\n options: O;\n}\n\n/** A partial index cannot constrain rows excluded by its predicate. */\nexport function isTotalIndex(options: Pick<IndexOptions, \"where\">): boolean {\n return !options.where;\n}\n\nexport type UpdateIndexDefinition<\n State extends ModelState,\n Index extends IndexDefinition,\n> = [...State[\"indexes\"], Index];\n\n/** The name a compound `.id()` / `.unique()` constraint may be given. */\nexport interface CompoundKeyOptions {\n name?: string;\n}\n\n/**\n * An options bag that carries the surface's own keys and NOTHING else.\n *\n * A generic `O extends Options` is no guard on its own: when inference produces\n * a bag the constraint would reject, TypeScript CLAMPS `O` to the constraint and\n * only excess-property checking is left to catch the stray key — and that needs\n * a fresh object literal, so `.index([\"a\"], sharedIndexOptions)` sails through\n * with `uniqu: true` recorded as nothing at all. Demanding `never` for the\n * unknown keys refuses structurally instead, whatever the argument's freshness.\n * Same instrument as `UnknownOmitKeys` below.\n */\ntype ExactOptions<Given, Allowed> = Given &\n Record<Exclude<keyof Given, keyof Allowed>, never>;\n\n/**\n * The constraint name: the caller's `name` when they gave one, otherwise the\n * underscore-joined field names. Read off the options bag rather than a separate\n * inferred parameter so that ONE type parameter carries the whole literal — the\n * parameter `ExactOptions` needs in order to see the unknown keys.\n */\ntype CompoundKeyName<\n Keys extends string[],\n O extends CompoundKeyOptions,\n> = O extends { name: infer N extends string } ? N : NameFromKeys<Keys>;\n\nexport const mergeIndexDefinitions = <\n State extends ModelState,\n Index extends IndexDefinition,\n>(\n state: State,\n index: Index\n): UpdateIndexDefinition<State, Index> => {\n return [...state.indexes, index] as UpdateIndexDefinition<State, Index>;\n};\n\n// Publish the same completed state as fluent returns so a legacy explicit\n// Model<UpdateState<...>> annotation retains exact relation-link identity.\nexport type UpdateState<\n State extends ModelState,\n Update extends Partial<ModelState>,\n> = {\n [P in keyof (Omit<State, keyof Update> & Update)]: (Omit<\n State,\n keyof Update\n > &\n Update)[P];\n};\n\n/**\n * The keys a proposed `.omit()` names that this model does NOT have as a\n * scalar: the typos and the relation names.\n *\n * `Hidden` is inferred from the argument's own keys and is deliberately NOT\n * constrained to the scalar names. A constrained type parameter is no guard\n * here: when inference produces something the constraint rejects, TypeScript\n * silently CLAMPS the parameter to the constraint and only excess-property\n * checking — which needs a fresh object literal — is left to catch the bad\n * key. Anything non-fresh (`as const`, a spread, an annotated variable, a\n * widened `Record<string, true>`) then sails through and records a\n * hidden-column claim nobody wrote. Excluding the unknown keys and demanding\n * `never` for them refuses structurally instead, whatever the argument's\n * freshness, and a `never` the caller cannot produce is a compile error at the\n * offending key.\n *\n * Relations are absent from the accepted set because `State[\"scalars\"]` is the\n * scalar half of the shape (`ScalarMap`), the same source `.index()` /\n * `.id()` / `.unique()` key off. Reading it never touches a relation's\n * `getter`, the member that must not be resolved while two model consts still\n * refer to each other (see `RelationState.getter`).\n */\ntype UnknownOmitKeys<Hidden extends string, State extends ModelState> = Exclude<\n Hidden,\n StringKeyOf<State[\"scalars\"]>\n>;\n\n/**\n * This model's scalar names, each optionally flagged `true`.\n *\n * It carries NO refusal — `UnknownOmitKeys` does that — and it adds no\n * requirement, every key being optional. It is in the parameter for one\n * reason: an editor offers the keys of a CONCRETE contextual type, and\n * `Record<Hidden, true>` is not concrete until `Hidden` has been inferred from\n * the very literal being typed. Without this member `.omit({ ` autocompletes\n * the global scope; with it, the model's scalars.\n */\nexport type ModelOmitInput<State extends ModelState> = Partial<\n Record<StringKeyOf<State[\"scalars\"]>, true>\n>;\n\n/**\n * Merge a new compound constraint into the existing record so repeated\n * .id()/.unique() calls accumulate instead of replacing each other.\n * Resolves to just `Added` when nothing was set yet.\n */\ntype MergeCompound<Existing, Added> = Added &\n (Existing extends Record<string, ObjectSchema<Record<string, VibSchema>>>\n ? Existing\n : unknown);\n\n/**\n * Resolve compound-key members to their base schemas, refusing any name that\n * is not a scalar of the model AT THE DECLARING SITE. The typed surface\n * already refuses these names; this throw is the runtime backstop for\n * untyped callers and JSON documents (the document interpreter relocates it\n * onto the `ids[]`/`uniques[]` node that wrote it), and it must fire on the\n * rule-free paths (`serializeModels`, `generate`,\n * `push({ skipValidation: true })`) that never run the advisory rules. I003\n * keeps its own coverage: post-construction shape drift (`.extends()`\n * shadowing a key member) is invisible to this constructor.\n *\n * A module function rather than a `Model` method: adding members to the class\n * perturbs how TS compares mutually-recursive model instantiations.\n */\nfunction compoundMembers(\n state: ModelState,\n fields: readonly string[],\n label: string\n): Record<string, VibSchema> {\n refuseDuplicateModelKeyMembers(fields, label);\n const members = emptyRecord<VibSchema>();\n for (const fieldName of fields) {\n // `in` is exact here: both maps come from the extractors, which build\n // prototype-free records, so no key can resolve an inherited member.\n const scalar =\n fieldName in state.scalars ? state.scalars[fieldName] : undefined;\n if (!scalar) {\n throw new Error(\n fieldName in state.relations\n ? `${label} field '${fieldName}' is a relation and cannot be a key member`\n : `${label} field '${fieldName}' does not exist`\n );\n }\n put(members, fieldName, scalar[\"~\"].state.base);\n }\n return members;\n}\n\n/**\n * One compound ID or unique, written into its own slot. The first tuple of a\n * name is preserved before Record storage could overwrite it.\n */\nfunction withCompound(\n state: ModelState,\n slot: \"compoundId\" | \"compoundUniques\",\n label: \"Compound ID\" | \"Compound unique\",\n fields: readonly string[],\n options: CompoundKeyOptions | undefined\n): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, label);\n const name = getNameFromKeys(options?.name, storedFields);\n if (Object.hasOwn(state[slot] ?? {}, name)) {\n throw new Error(\n `${label} name '${name}' is already used by another compound key; give this tuple a distinct name`\n );\n }\n const fieldsRecord = compoundMembers(state, storedFields, label);\n return new Model({\n ...state,\n [slot]: {\n ...state[slot],\n [name]: v.object(fieldsRecord, { partial: false }),\n },\n });\n}\n\n/** Snapshot one declaration tuple without consulting caller iteration hooks. */\nfunction snapshotModelKeyMembers(fields: unknown, label: string): string[] {\n if (!Array.isArray(fields)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const memberCount = fields.length;\n const members = new Array<string>(memberCount);\n for (let position = 0; position < memberCount; position++) {\n if (!Object.hasOwn(fields, position)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const member: unknown = fields[position];\n if (typeof member !== \"string\") {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n members[position] = member;\n }\n return members;\n}\n\n/** Snapshot the four public index options, including inherited accessors. */\nfunction snapshotIndexOptions(options: IndexOptions): IndexOptions {\n const name = options.name;\n const unique = options.unique;\n const type = options.type;\n const where = options.where;\n return {\n ...(name === undefined ? {} : { name }),\n ...(unique === undefined ? {} : { unique }),\n ...(type === undefined ? {} : { type }),\n ...(where === undefined ? {} : { where }),\n };\n}\n\n/** One physical key/index tuple cannot name the same column twice. */\nfunction refuseDuplicateModelKeyMembers(\n fields: readonly string[],\n label: string\n): void {\n if (new Set(fields).size !== fields.length) {\n throw new Error(`${label} cannot repeat a field in one tuple`);\n }\n}\n\n/**\n * Name registry for scalars and relations.\n * Maps scalar/relation keys to their resolved names (ts and sql).\n * This is populated during hydration.\n */\nexport interface NameRegistry {\n /** Scalar names: key -> {ts, sql} */\n fields: Map<string, SchemaNames>;\n}\n\nexport class Model<State extends ModelState> {\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #names: SchemaNames = {};\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #nameRegistry: NameRegistry = {\n fields: new Map(),\n };\n readonly #state: State;\n\n // Cached field metadata (lazily computed on first access)\n #scalarFieldNames: string[] | undefined;\n #relationNames: string[] | undefined;\n #internal: ModelInternal<State> | undefined;\n\n constructor(state: State) {\n this.#state = state;\n }\n\n // Materialize each completed modifier state inline before a recursive getter\n // captures it. A helper alias retains the whole prior modifier chain.\n /**\n * Maps the model to a specific database table name\n */\n map<Name extends string>(tableName: Name) {\n return new Model({ ...this.#state, tableName }) as unknown as Model<{\n [KState in keyof UpdateState<State, { tableName: Name }>]: UpdateState<\n State,\n { tableName: Name }\n >[KState];\n }>;\n }\n\n /**\n * Hide scalars from every result of this model — the schema-level exclusion.\n *\n * Keyed to the model's own SCALARS, so a typo or a relation name is a\n * compile error instead of an `omit` that quietly hides nothing. That\n * matters more here than anywhere else the builder takes field names: this\n * is the spelling used for secrets, and a silently-ignored key is a leaked\n * column. The refusal is per KEY, not per call: `{ secret: true, tokne:\n * true }` fails on `tokne` even though `secret` is real — two secrets with\n * one misspelled is the realistic case, and it is exactly the case an\n * excess-property-only refusal would wave through (see `UnknownOmitKeys`).\n *\n * Every value must be `true`. `false` has no meaning here (model-level omit\n * only ever hides) and a flag that may be `undefined` hides nothing at\n * runtime — `projectableScalarNames` compares against `true` — so\n * `Record<Hidden, true>` refuses both rather than recording a claim the\n * runtime would not honor.\n *\n * The literal survives the round trip — `.omit({ secret: true })` carries\n * exactly `{ secret: true }` into the state, not a widened record — which is\n * what every downstream `keyof State[\"omit\"]` reads. `Hidden` defaults to\n * `never` for the one call with nothing to infer from, `.omit({})`: a bare\n * `extends string` would fall back to `string` there and hand the state a\n * record keyed by every conceivable name.\n */\n omit<Hidden extends string = never>(\n items: Record<Hidden, true> &\n Record<UnknownOmitKeys<Hidden, State>, never> &\n ModelOmitInput<State>\n ) {\n return new Model({\n ...this.#state,\n omit: items,\n }) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n { omit: Record<Hidden, true> }\n >]: UpdateState<State, { omit: Record<Hidden, true> }>[KState];\n }>;\n }\n\n index<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n O extends OrdinaryIndexOptions = OrdinaryIndexOptions,\n >(\n fields: Keys,\n options?: ExactOptions<O, OrdinaryIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >[KState];\n }>;\n index<\n const Key extends NonNullablePointScalarKeys<State[\"scalars\"]>,\n const O extends GeoPointSpatialIndexOptions,\n >(\n fields: [Key],\n options: ExactOptions<O, GeoPointSpatialIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >[KState];\n }>;\n index(fields: string[], options: IndexOptions = {}): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, \"Index\");\n refuseDuplicateModelKeyMembers(storedFields, \"Index\");\n const storedOptions = snapshotIndexOptions(options);\n return new Model({\n ...this.#state,\n indexes: mergeIndexDefinitions(this.#state, {\n fields: storedFields,\n options: storedOptions,\n }),\n });\n }\n\n id<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundId\",\n \"Compound ID\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n unique<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundUniques\",\n \"Compound unique\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n extends<ETShape extends DeclaredModelShape>(shape: ETShape) {\n const newShape = { ...this.#state.shape, ...shape } as State[\"shape\"] &\n ETShape;\n return new Model({\n ...this.#state,\n shape: newShape,\n scalars: extractScalarMap(newShape),\n relations: extractRelationMap(newShape),\n uniques: extractUniqueScalarMap(newShape),\n }) as unknown as Model<\n UpdateState<\n State,\n {\n shape: State[\"shape\"] & ETShape;\n scalars: ScalarMap<State[\"shape\"] & ETShape>;\n relations: RelationMap<State[\"shape\"] & ETShape>;\n uniques: UniqueScalarMap<State[\"shape\"] & ETShape>;\n }\n >\n >;\n }\n\n get \"~\"(): ModelInternal<State> {\n if (this.#internal) {\n return this.#internal;\n }\n // Capture model instance for use in getters\n const model = this;\n\n this.#internal = {\n state: this.#state,\n // getters so hydration after first access is still observed\n get names() {\n return model.#names;\n },\n get nameRegistry() {\n return model.#nameRegistry;\n },\n /**\n * Get the resolved names for a field.\n * Throws if the schema has not been hydrated.\n */\n getFieldName: (key: string): HydratedSchemaNames => {\n const registered = model.#nameRegistry.fields.get(key);\n if (registered) {\n return registered as HydratedSchemaNames;\n }\n throw new Error(`Scalar \"${key}\" not found in nameRegistry`);\n },\n /** Cached scalar field names (computed once on first access) */\n get scalarFieldNames(): string[] {\n return (model.#scalarFieldNames ??= Object.keys(model.#state.scalars));\n },\n /** Cached relation names (computed once on first access) */\n get relationNames(): string[] {\n return (model.#relationNames ??= Object.keys(model.#state.relations));\n },\n };\n return this.#internal;\n }\n}\n\nexport const model = <TShape extends DeclaredModelShape>(\n shape: TShape\n): Model<InitialModelState<TShape>> =>\n new Model({\n compoundId: undefined,\n compoundUniques: undefined,\n tableName: undefined,\n indexes: [],\n omit: undefined,\n shape,\n scalars: extractScalarMap(shape),\n relations: extractRelationMap(shape),\n uniques: extractUniqueScalarMap(shape),\n });\n\nexport type AnyModel = Model<any>;\n\n/**\n * SQL table name for a model: hydrated name, then .map() tableName, then\n * the given fallback.\n */\nexport function getTableName(model: AnyModel, fallback = \"unknown\"): string {\n return model[\"~\"].names.sql ?? model[\"~\"].state.tableName ?? fallback;\n}\n\n/**\n * SQL column name for a field, resolved through the model's nameRegistry\n * (supports field reuse across models) with .map() and field-name fallbacks.\n */\nexport function getColumnName(model: AnyModel, fieldName: string): string {\n return model[\"~\"].getFieldName(fieldName).sql;\n}\n"],"mappings":"iMAsBA,SAAgB,aAAoC,CAClD,OAAO,OAAO,OAAO,KAAK,CAI5B,SAAgB,IAAO,EAA2B,EAAa,EAAgB,CAC7E,OAAO,eAAe,EAAQ,EAAK,CACjC,QACA,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAIJ,SAAgB,IACd,EACA,EACe,CACX,SAAW,IAAA,IAAa,CAAC,OAAO,OAAO,EAAQ,EAAI,EACvD,OAAO,EAAO,GCFhB,MAAM,EAAe,sCAEf,EAAqB,CAAC,QAAS,SAAU,SAAS,CAuIxD,SAAgB,wBACd,EACA,EACA,EACwC,CACnC,EAAc,EAAS,EAC1B,EACE,EACA,SACA,0FACD,CAEH,IAAM,EAAc,EAAa,EAAS,CACtC,EAAY,SAAW,GACzB,EACE,EACA,SACA,2CACD,CAEH,IAAM,EAAe,iBAAiB,EAAS,EAAa,EAAQ,CAC9D,EAAwC,EAAE,CAChD,IAAK,IAAM,KAAc,EAAa,CAC/B,EAAwB,EAAW,EACtC,EACE,EACA,UAAU,IACV,gBAAgB,EAAW,oCAC5B,CAEH,IAAM,EAAS,EACb,EACA,EACA,EACA,UAAU,IACX,CACG,OAAO,GAAW,YACpB,EACE,EACA,UAAU,IACV,YAAY,EAAW,6EACxB,CAEH,EAAQ,GAAc,OA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QJ,SAAgB,aAAa,EAAiB,EAAW,UAAmB,CAC1E,OAAOA,EAAM,KAAK,MAAM,KAAOA,EAAM,KAAK,MAAM,WAAa,EAO/D,SAAgB,cAAc,EAAiB,EAA2B,CACxE,OAAOA,EAAM,KAAK,aAAa,EAAU,CAAC"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{v as t}from"./query-CTna5P9o.mjs";import{O as n,v as r}from"./geo-point-codec-CIZxuIvE.mjs";import{o as i}from"./sql-DGtEeP8z.mjs";import{a}from"./physical-t_gDjUCD.mjs";import{t as o}from"./geo-area-codec-DvHcWF3g.mjs";import{t as s}from"./adapter-result-parser-Bz3WtMBa.mjs";import{r as ee}from"./adapter-internals-DNY4JWFC.mjs";import{n as c}from"./result-parsing-Dkgy-xcy.mjs";import{r as l}from"./datetime-physical-codec-DTdvABny.mjs";import{A as u,C as d,D as f,E as te,M as p,N as m,S as h,T as g,_,a as v,c as y,d as b,f as x,g as S,h as C,i as w,l as T,m as E,n as D,o as O,p as k,r as A,s as j,t as M,u as N,v as ne,w as P,x as F,y as I}from"./standard-sql-Ci8ROrql.mjs";import{n as L}from"./batch-refs-DWMYN0fw.mjs";import{t as R}from"./adapter-namespace-BMss0hKo.mjs";import{a as z,d as B,f as V,i as H,m as U,n as W,o as G,p as K,r as q,t as J,u as Y}from"./select-assembly-BtNtBsUh.mjs";const X=m("`"),Z=U(()=>`PRIMARY`),Q={quotient:(e,t)=>i`CAST((${e} - MOD(${e}, ${t})) / ${t} AS DECIMAL(65,0))`,remainder:(e,t)=>i`MOD(${e}, ${t})`},mysqlMaximumCoefficient=e=>i.raw(`9`.repeat(e)),re=i`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`,$=i`JSON_EXTRACT('x', '$')`,decimalCast=(e,t,n)=>i`CAST(${e} AS ${i.raw(`DECIMAL(${t},${n})`)})`,mysqlCoefficient=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`TRUNCATE(${e}, 0)`;return i`(${a} * ${r} + ${decimalCast(i`(${decimalCast(i`(${e} - ${a})`,n+1,n)} * ${r})`,n,0)})`},mysqlLogical=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`MOD(${e}, ${r})`;return i`((${e} - ${a}) / ${r} + ${decimalCast(a,n,0)} * ${B(n)})`},mysqlGuardedDecimalAssignment=(e,t,n,r)=>{let a=mysqlMaximumCoefficient(n.precision),o=mysqlLogical(t,n);return i`${e} = CASE WHEN ${re} THEN ${o} WHEN ${e} IS NULL THEN NULL WHEN ${r} THEN CASE WHEN ${t} BETWEEN -${a} AND ${a} THEN ${o} ELSE ${$} END ELSE ${$} END`},mysqlDecimalIncrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} <= ${o} - ${a} WHEN ${a} < 0 THEN ${r} >= -${o} - ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} + ${a})`,n,s)},mysqlDecimalDecrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} >= -${o} + ${a} WHEN ${a} < 0 THEN ${r} <= ${o} + ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} - ${a})`,n,s)},mysqlDecimalMultiply=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(65);return mysqlGuardedDecimalAssignment(e,G(Q,i`(${r} * ${a})`,Y(n.scale)),n,i`CASE WHEN ${a} = 0 THEN TRUE ELSE ABS(${r}) <= ${Q.quotient(o,i`ABS(${a})`)} END`)},mysqlDecimalDivide=(e,t,n)=>{let r=mysqlCoefficient(t,n);return mysqlGuardedDecimalAssignment(e,G(Q,V(i`(${mysqlCoefficient(e,n)} * ${Y(n.scale)})`,r),i`ABS(${r})`),n,i.raw`TRUE`)},mysqlDecimalAverage=(e,t)=>mysqlLogical(G(Q,i`SUM(${mysqlCoefficient(e,t)})`,i`COUNT(${e})`),t),caseFold=e=>i`LOWER(${e})`,ie=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?$/,naiveDateTimeToIso=e=>{let t=ie.exec(e);if(!t)return;let n=t[3]?t[3].padEnd(4,`0`).slice(0,4):`.000`;return`${t[1]}T${t[2]}${n}Z`},inlineIntegerLiteral=e=>{let t=e.values.length===1?e.values[0]:void 0;return typeof t==`number`&&Number.isInteger(t)?i.raw(String(t)):e},mysqlJsonObject=e=>{if(e.length===0)return i.raw`JSON_OBJECT()`;let t=e.flatMap(([e,t])=>[i`${e}`,t]);return i`JSON_OBJECT(${i.join(t,`, `)})`},mysqlJsonListValue=e=>i`CAST(${p(e)} AS JSON)`;var MySQLAdapter=class{constructor(e){R(this,e,`mysql`),this.identifiers=x(X,this.namespace,!0),K(this,this.geoPoint),ee(this,{batchRefs:this.#t,constraints:Z,select:this.#e.select})}raw=h();identifiers;literals={...te(),true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t,n)=>i`${n||e.length===10?e:l(e)}`,decimal:(e,t)=>i`CAST(${n(e,t,`text`)} AS ${i.raw(r(`mysql`,t))})`,id:(e,t)=>i`${e}`};operators={...v(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\\\'`,ilike:(e,t)=>i`BINARY ${caseFold(e)} LIKE BINARY ${caseFold(t)} ESCAPE '\\\\'`,notIlike:(e,t)=>i`BINARY ${caseFold(e)} NOT LIKE BINARY ${caseFold(t)} ESCAPE '\\\\'`,containsText:(e,t)=>i`LOCATE(BINARY ${t}, BINARY ${e}) > 0`,startsWithText:(e,t)=>i`LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,endsWithText:(e,t)=>i`RIGHT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,insensitiveText:(e,t,n)=>this.operators[`${e}Text`](caseFold(t),caseFold(n)),startsWithPrefix:(e,t)=>i`(${e} LIKE ${`${u(t)}%`} ESCAPE '\\\\' AND LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t})`,exactTextEq:(e,t)=>i`(${e} = ${t} AND BINARY ${e} = ${t})`,exactTextIn:(e,t)=>i`(${e} IN ${t} AND BINARY ${e} IN ${t})`,...S(),...ne(),...F(),...C(this.literals.true,this.literals.false),...b()};expressions={...w(),caseFold,caseSensitiveText:e=>i`BINARY ${e}`,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`CONCAT(${i.join(e,`, `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`TRUNCATE(${e} / ${t}, 0)`,decimalCast:(e,t)=>decimalCast(e,t.precision,t.scale),idCast:(e,t)=>t===`bytes`?i`UNHEX(${e})`:i`CAST(${e} AS CHAR)`,cast:A({text:`CHAR`,integer:`SIGNED`,bigint:`SIGNED`,boolean:`UNSIGNED`,numeric:`DECIMAL`}),blobToHex:e=>i`LOWER(HEX(${e}))`};aggregates={...D(),decimalAvg:(e,t)=>mysqlDecimalAverage(e,t),decimalSumOperandPrecision:y(65)};json={equals:(e,t)=>i`${e} = ${t}`,number:e=>e,boolean:e=>i`JSON_EXTRACT(CASE WHEN ${e} THEN 'true' ELSE 'false' END, '$')`,document:e=>e,object:mysqlJsonObject,array:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,emptyArray:()=>i.raw`JSON_ARRAY()`,agg:e=>i`COALESCE(JSON_ARRAYAGG(${e}), JSON_ARRAY())`,objectFromColumns:mysqlJsonObject,extract:(e,t)=>i`JSON_EXTRACT(${e}, ${M(t)})`,extractText:(e,t)=>i`JSON_UNQUOTE(JSON_EXTRACT(${e}, ${M(t)}))`,numberAtPath:(e,t)=>{let n=M(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS DOUBLE) END)`},stringAtPath:(e,t)=>{let n=M(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS BINARY) END)`},foldableStringAtPath:(e,t)=>{let n=M(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) = 'STRING' THEN JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) END)`},contains:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,lastElement:e=>i`JSON_EXTRACT(${e}, '$[last]')`,value:e=>i`CAST(${p(e)} AS JSON)`};arrays={literal:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,value:mysqlJsonListValue,enumValue:mysqlJsonListValue,has:(e,t)=>i`JSON_CONTAINS(${e}, JSON_ARRAY(${t}))`,hasEvery:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,hasSome:(e,t)=>i`JSON_OVERLAPS(${e}, ${t})`,isEmpty:e=>i`(JSON_LENGTH(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS CHAR)`,length:e=>i`JSON_LENGTH(${e})`,get:(e,t)=>i`JSON_EXTRACT(${e}, CONCAT('$[', ${t}, ']'))`,push:(e,t)=>i`JSON_ARRAY_APPEND(${e}, '$', ${t})`,set:(e,t,n)=>i`JSON_SET(${e}, CONCAT('$[', ${t}, ']'), ${n})`};orderBy={...T(),...N()};clauses={...g(),limit:e=>i`LIMIT ${inlineIntegerLiteral(e)}`,offset:e=>i`OFFSET ${inlineIntegerLiteral(e)}`};set={...I(),increment:(e,t,n)=>n?.decimal?mysqlDecimalIncrement(e,t,n.decimal):i`${e} = ${e} + ${t}`,decrement:(e,t,n)=>n?.decimal?mysqlDecimalDecrement(e,t,n.decimal):i`${e} = ${e} - ${t}`,multiply:(e,t,n)=>n?.decimal?mysqlDecimalMultiply(e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?mysqlDecimalDivide(e,t,n.decimal):n?.integer?i`${e} = TRUNCATE(${e} / ${t}, 0)`:i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(COALESCE(${e}, JSON_ARRAY()), ${t})`,unshift:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(${t}, COALESCE(${e}, JSON_ARRAY()))`};filters=d();subqueries=f(X);noLimitValue=i.raw`18446744073709551615`;#e={select:e=>{let t={...e,limit:e.limit&&inlineIntegerLiteral(e.limit),offset:e.offset&&inlineIntegerLiteral(e.offset)};return t.distinct?J(t,t.distinct,this.identifiers.escape,this.noLimitValue):W(i`SELECT ${t.columns}`,t,{forUpdate:`append`,noLimitValue:this.noLimitValue})}};cte=j(X);mutations={skipDuplicatesStrategy:`recoverableUniqueError`,insert:k(X),insertDefault:e=>i`INSERT INTO ${e} () VALUES ()`,..._(),returning:e=>i.empty,onConflict:(e,t,n)=>i`ON DUPLICATE KEY UPDATE ${t}`,onConflictUpdate:(e,t)=>e,skipDuplicates:e=>{let t=i.raw(X(e));return{prefix:i.empty,suffix:i`ON DUPLICATE KEY UPDATE ${t} = ${t}`}}};assertions={exists:e=>i`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,notExists:e=>i`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,holds:(e,t)=>i`SELECT CASE WHEN ${e} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \`__viborm_judged__\`${t?i` FROM ${t}`:i``}`};joins={...O(),full:(e,t)=>{throw Error(`MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},...E(X)};setOperations=P(X);capabilities={supportsReturning:!1,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!1,supportsTargetedUpsert:!1,supportsMutationTargetInSubquery:!1,supportsMutationRowLimit:!0,supportsRowLocks:!0,locksMissingKeys:!0,boundsRecursionIterations:!0};lastInsertId=()=>i.raw`LAST_INSERT_ID()`;#t=L({table:i.raw`\`__viborm_batch_refs\``,batchIdColumn:i.raw`\`batch_id\``,keyColumn:i.raw`\`ref_key\``,valueColumn:i.raw`\`ref_value\``,duplicateValue:i.raw`VALUES(\`ref_value\`)`,createTable:i.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \`__viborm_batch_refs\` (\`batch_id\` VARCHAR(191) NOT NULL, \`ref_key\` VARCHAR(191) NOT NULL, \`ref_value\` TEXT, PRIMARY KEY (\`batch_id\`, \`ref_key\`))`,castValue:e=>i`CAST((${e}) AS CHAR)`,lastInsertId:()=>this.lastInsertId()});vector=t;geoPoint=(()=>{let longitude=e=>i`ST_Longitude(${e})`,latitude=e=>i`ST_Latitude(${e})`;return{value:(e,t)=>i`ST_GeomFromText(CONCAT('POINT(', ${e}, ' ', ${t}, ')'), 4326, 'axis-order=long-lat')`,longitude,latitude,...q(longitude,latitude,this.operators,(e,t)=>{let n=H(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`MBRIntersects(${e}, ST_GeomFromGeoJSON(${t}, 1, 4326))`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_GeomFromGeoJSON(${z(t)}, 1, 4326)`}, ${e})`,distance:(e,t)=>i`ST_Distance_Sphere(${e}, ${t}, ${o})`}})();result={decimalListRepresentation:`coefficient`,idRepresentation:(e,t)=>a(e,t,`mysql`)?.representation??`text`,parseResult:s,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>{if(t===`boolean`){let t=c(e===`0`?0:e===`1`?1:e);if(t!==void 0)return n(t)}if(t===`datetime`&&typeof e==`string`){let t=naiveDateTimeToIso(e);if(t!==void 0)return n(t)}return n()}}};export{MySQLAdapter as t};
2
+ //# sourceMappingURL=mysql-adapter-D-Dq2FN9.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mysql-adapter-D-Dq2FN9.mjs","names":["sql","#batchRefs","#assemble"],"sources":["../src/adapters/databases/mysql/mysql-adapter.ts"],"sourcesContent":["import { unsupportedVector } from \"@errors\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type { ArithmeticTarget } from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n type TextMatch,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter(\"`\");\nconst MYSQL_CONSTRAINTS = createNamedConstraintIdentities(() => \"PRIMARY\");\n\n/**\n * MySQL has `MOD()` but no exact integer-quotient function for decimals: `DIV`\n * converts both sides to BIGINT (so it overflows and truncates a wide\n * `DECIMAL`), and `TRUNCATE(n / d, 0)` computes `n / d` to\n * `div_precision_increment` extra digits and ROUNDS there first, which can turn\n * a value just below a half into an exact-looking tie.\n *\n * `(n - MOD(n, d)) / d` avoids both: the numerator is exactly divisible by `d`,\n * so the division's true result has no fractional digits and the extra digits\n * MySQL computes are all zero.\n */\nconst MYSQL_INTEGERS: ExactIntegerArithmetic = {\n // The CAST is not decoration. MySQL's `/` ALWAYS returns\n // `div_precision_increment` (four, by default) fractional digits, so an exact\n // integer quotient arrives typed `DECIMAL(w, 4)` — four digits of the 65-digit\n // exact domain spent on zeros, and any product taking that value as an operand\n // would carry them into ITS width. Casting back to the widest exact integer\n // domain is exact here (the value has no fraction to lose) and is what keeps\n // every downstream term integer-typed.\n quotient: (n: Sql, d: Sql): Sql =>\n sql`CAST((${n} - MOD(${n}, ${d})) / ${d} AS DECIMAL(65,0))`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * MySQL's exact decimal domain, in digits — the ceiling every expression below\n * is written to stay under (plan 5.3: \"MySQL expressions avoid an intermediate\n * wider than its 65-digit exact domain\").\n */\nconst MYSQL_EXACT_DIGITS = 65;\n\nconst mysqlMaximumCoefficient = (digits: number): Sql =>\n sql.raw(\"9\".repeat(digits));\n\nconst mysqlStrictMode = sql`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`;\n\nconst mysqlArithmeticFailure = sql`JSON_EXTRACT('x', '$')`;\n\n/** `CAST(<expr> AS DECIMAL(precision,scale))`, the width-declaring device. */\nconst decimalCast = (expr: Sql, precision: number, scale: number): Sql =>\n sql`CAST(${expr} AS ${sql.raw(`DECIMAL(${precision},${scale})`)})`;\n\n/**\n * The signed unscaled COEFFICIENT of a logical `DECIMAL(p,s)` expression, as an\n * exact integer — WITHOUT ever multiplying the whole value by `10^s`.\n *\n * `column * 10^s` is the obvious spelling and it is the unsafe one. MySQL types\n * a product as `DECIMAL(p1+p2, s1+s2)` capped at `(65, 30)`, so multiplying a\n * `DECIMAL(65,30)` column by a `DECIMAL(31,0)` factor asks for a 96-digit type,\n * gets a 65-digit one whose 30 fractional digits leave 35 for an integer that\n * needs 65 — and MySQL answers ZERO, with no warning and no error (measured on\n * 8.4: `SELECT CAST(REPEAT('9',50) AS DECIMAL(65,0)) * 0.<29 zeros>1` is\n * `0.000…0`). Splitting the value first is what keeps every factor small:\n *\n * whole = TRUNCATE(v, 0) |whole| < 10^(p-s), scale 0\n * fraction = v - whole |fraction| < 1, scale s\n * coefficient = whole * 10^s + fraction * 10^s\n *\n * Widths, by construction, for every descriptor MySQL admits (`p <= 65`,\n * `s <= 30`, `p + s <= 65`): `whole * 10^s` is typed\n * `DECIMAL(min(p+2,65), 0)` and valued\n * below `10^p`; `fraction * 10^s` is typed `DECIMAL(2s+2, s)` — at most 62\n * digits — and valued below `10^s`, so its cast to `DECIMAL(s,0)` is exact.\n * Neither product's operands sum past the exact domain, so neither can take the\n * silent arm above.\n */\nconst mysqlCoefficient = (value: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return value;\n const factor = scaleFactorSql(scale);\n const whole = sql`TRUNCATE(${value}, 0)`;\n const fraction = decimalCast(sql`(${value} - ${whole})`, scale + 1, scale);\n return sql`(${whole} * ${factor} + ${decimalCast(sql`(${fraction} * ${factor})`, scale, 0)})`;\n};\n\n/**\n * The logical `DECIMAL(p,s)` value of an exact integer COEFFICIENT — the\n * inverse of {@link mysqlCoefficient}, and unsafe for the same reason in the\n * same place.\n *\n * `coefficient * 10^-s` would multiply a `p`-digit integer by a\n * `DECIMAL(s+1,s)` literal: `p + s + 1` digits of type for a value that needs\n * `p`, which is the silent-zero arm again for a wide descriptor. So the\n * coefficient is split by `10^s` FIRST — an integer part that is already the\n * answer's integer part, and a remainder below `10^s` that is the only thing\n * the tiny `10^-s` literal ever multiplies:\n *\n * integer part = (coefficient - MOD(coefficient, 10^s)) / 10^s\n * fraction = MOD(coefficient, 10^s) * 10^-s\n *\n * Widths: the division is typed `DECIMAL(w, 4)` over a value below `10^(p-s)`,\n * and the fractional product's operands sum to `2s + 1` — at most 61 digits.\n */\nconst mysqlLogical = (coefficient: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return coefficient;\n const factor = scaleFactorSql(scale);\n const remainder = sql`MOD(${coefficient}, ${factor})`;\n return sql`((${coefficient} - ${remainder}) / ${factor} + ${decimalCast(remainder, scale, 0)} * ${scaleUnitSql(scale)})`;\n};\n\n/**\n * Assign one coefficient-space answer without letting a non-strict MySQL\n * session turn overflow into a clipped value. Strict sessions retain their\n * native error. A non-strict session reaches the answer only after the caller's\n * operation-specific precondition proves its intermediate is exact and the\n * target-domain check proves the final coefficient fits.\n *\n * The session-mode arm is deliberately first. `CASE` is the same lazy error\n * primitive used by this adapter's assertion queries, so a safe or NULL arm\n * never evaluates the invalid JSON expression that raises the provider error.\n */\nconst mysqlGuardedDecimalAssignment = (\n column: Sql,\n coefficient: Sql,\n descriptor: DecimalDescriptor,\n intermediateFits: Sql\n): Sql => {\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const logical = mysqlLogical(coefficient, descriptor);\n return sql`${column} = CASE WHEN ${mysqlStrictMode} THEN ${logical} WHEN ${column} IS NULL THEN NULL WHEN ${intermediateFits} THEN CASE WHEN ${coefficient} BETWEEN -${maximum} AND ${maximum} THEN ${logical} ELSE ${mysqlArithmeticFailure} END ELSE ${mysqlArithmeticFailure} END`;\n};\n\nconst mysqlDecimalIncrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} <= ${maximum} - ${operand} WHEN ${operand} < 0 THEN ${current} >= -${maximum} - ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} + ${operand})`,\n descriptor,\n fits\n );\n};\n\nconst mysqlDecimalDecrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} >= -${maximum} + ${operand} WHEN ${operand} < 0 THEN ${current} <= ${maximum} + ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} - ${operand})`,\n descriptor,\n fits\n );\n};\n\n/**\n * `column = halfEven(column x by)`, computed on COEFFICIENTS.\n *\n * This is plan 5.3's rule verbatim — `multiply = halfEven((x * y) / F)` — and\n * it is stated on integers because MySQL cannot state it on logical values: the\n * exact product of two `DECIMAL(p,s)` values carries `2s` fractional digits,\n * and MySQL caps an expression's scale at 30, ROUNDING anything finer away\n * before the tie this rule exists to decide is ever visible (measured: `1e-30 *\n * 1e-30` is `0.000…0` at `DECIMAL(65,30)`, no warning). Coefficients have no\n * fractional digits at all, so nothing can be rounded away underneath the rule.\n *\n * WIDTH, BY CONSTRUCTION. `|x|, |y| < 10^p`, and the answer is in the field's\n * domain exactly when `|x * y| < 10^(p+s)`, so the product needs at most\n * `p + s` digits: within the 65-digit exact domain for every descriptor with\n * `precision + scale <= 65`. The quotient is `< 10^p`, the remainder `< 10^s`,\n * and the tie test compares `|r|` against `10^s - |r|` — the non-doubling form,\n * so nothing widens there either.\n *\n * Outside that bound the operation is loud on every session. A strict session\n * reaches MySQL's native overflow error. A non-strict session first proves the\n * product can be formed inside 65 digits and that the rounded coefficient fits\n * the field; a failed proof evaluates the adapter's lazy error expression\n * instead of letting MySQL clip the assignment. Both leave the row unchanged.\n */\nconst mysqlDecimalMultiply = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const left = mysqlCoefficient(column, descriptor);\n const right = mysqlCoefficient(by, descriptor);\n const maximumIntermediate = mysqlMaximumCoefficient(MYSQL_EXACT_DIGITS);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`(${left} * ${right})`,\n scaleFactorSql(descriptor.scale)\n );\n const intermediateFits = sql`CASE WHEN ${right} = 0 THEN TRUE ELSE ABS(${left}) <= ${MYSQL_INTEGERS.quotient(maximumIntermediate, sql`ABS(${right})`)} END`;\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n intermediateFits\n );\n};\n\n/**\n * `column = halfEven(column / by)`, computed on COEFFICIENTS — plan 5.3's\n * `divide = halfEven((x * F) / y)`.\n *\n * The divisor is the operand's COEFFICIENT rather than its logical value: an\n * exact quotient is spelled `(n - MOD(n, d)) / d`, and with a fractional `d`\n * the numerator `n - MOD(n, d)` is `q * d` — a `p`-digit magnitude carrying `s`\n * fractional digits, `p + s` digits for a value the integer form states in `p`.\n * Integers on both sides keep every term at its own width.\n *\n * WIDTH, BY CONSTRUCTION: `|x * F| < 10^(p+s)` — inside the exact domain for\n * every descriptor with `precision + scale <= 65`, and unconditionally, not\n * only when the answer fits. The quotient is the answer's coefficient\n * (`< 10^p` when it fits the field), the remainder is below `|y| < 10^p`, and\n * the tie compares `|r|` against `|y| - |r|`, which is why the doubled form was\n * dropped: `2|r|` at `p = 65` needs 66.\n *\n * `by` is never zero — division by canonical zero is refused before I/O.\n */\nconst mysqlDecimalDivide = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const divisor = mysqlCoefficient(by, descriptor);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n signedNumerator(\n sql`(${mysqlCoefficient(column, descriptor)} * ${scaleFactorSql(descriptor.scale)})`,\n divisor\n ),\n sql`ABS(${divisor})`\n );\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n sql.raw`TRUE`\n );\n};\n\n/**\n * The exact decimal average, on coefficients: `SUM` of the column's\n * coefficients over `COUNT(column)`, quantized half to even.\n *\n * Summing the COEFFICIENTS rather than scaling the sum is what removes the last\n * `x 10^s` from this expression: `SUM(column) * 10^s` multiplies a value MySQL\n * already types up to 65 digits by a 31-digit factor, which is the silent-zero\n * arm {@link mysqlCoefficient} exists to avoid. Every row's coefficient is\n * below `10^p`, so the only way the sum leaves the exact domain is by genuinely\n * exceeding it, and MySQL raises there.\n *\n * `COUNT(column)` counts non-nulls, so an empty or all-null group answers NULL\n * through the null-strict operators instead of dividing by zero.\n */\nconst mysqlDecimalAverage = (\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`SUM(${mysqlCoefficient(column, descriptor)})`,\n sql`COUNT(${column})`\n );\n return mysqlLogical(coefficient, descriptor);\n};\n// MySQL's own case folding: `LOWER` maps every letter by the string's\n// character set (Unicode for utf8mb4). It must see the raw text — on a\n// `BINARY` string it does nothing — and its result is compared as bytes, so a\n// case- AND accent-insensitive collation (`utf8mb4_0900_ai_ci`) never decides.\nconst caseFold = (expr: Sql): Sql => sql`LOWER(${expr})`;\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst mysqlJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw`JSON_OBJECT()`;\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`JSON_OBJECT(${sql.join(args, \", \")})`;\n};\n\n/** The one JSON list container every MySQL list value crosses as. */\nconst mysqlJsonListValue = (values: unknown[]): Sql =>\n sql`CAST(${stringifyJson(values)} AS JSON)`;\n\nexport class MySQLAdapter implements DatabaseAdapter {\n /**\n * The bound database, or `undefined` for the unqualified mode a\n * provider-configured MySQL2 client and every PlanetScale client keep. Under\n * Vitess the value is the keyspace qualifier submitted before routing rules\n * apply, not a proof of the routed backend.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n installAdapterNamespace(this, namespace, \"mysql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace, true);\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // MySQL requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n dateTime: (\n iso: string,\n _nativeType?: NativeTypeDeclaration,\n member?: boolean\n ): Sql =>\n sql`${member || iso.length === 10 ? iso : encodeMySqlDateTime(iso)}`,\n\n // The cast is load-bearing, not decoration. MySQL's comparison rules say\n // that when one side is a number and the other a string, BOTH are converted\n // to double and compared as floating point — so `amount = '0.1'` against a\n // `DECIMAL` column would silently answer at float precision on an otherwise\n // exact column. Casting the operand into the SAME `DECIMAL(p,s)` the DDL\n // emits keeps the whole comparison in MySQL's exact decimal domain, and\n // names one domain for the operand and the column instead of two.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"mysql\", descriptor))})`,\n\n // MySQL has no `uuid` type: every compact domain is a `BINARY(n)` column\n // and takes the payload's bytes as an ordinary binary parameter, which is\n // the same parameter a blob scalar already binds. A text-stored domain\n // takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n _representation: IdRepresentation\n ): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder.\n // The literal is doubled ('\\\\') because MySQL's default mode treats\n // backslash as a string-literal escape; under NO_BACKSLASH_ESCAPES it\n // fails loudly rather than silently matching wildcards.\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`BINARY ${caseFold(column)} LIKE BINARY ${caseFold(pattern)} ESCAPE '\\\\\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`BINARY ${caseFold(column)} NOT LIKE BINARY ${caseFold(pattern)} ESCAPE '\\\\\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`LOCATE(BINARY ${value}, BINARY ${column}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`RIGHT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n insensitiveText: (kind: TextMatch, column: Sql, value: Sql): Sql =>\n this.operators[`${kind}Text`](caseFold(column), caseFold(value)),\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (expression: Sql): Sql => expression,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: (expression: Sql): Sql => expression,\n\n object: mysqlJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`JSON_ARRAY()`,\n\n agg: (expr: Sql): Sql =>\n sql`COALESCE(JSON_ARRAYAGG(${expr}), JSON_ARRAY())`,\n\n objectFromColumns: mysqlJsonObject,\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(JSON_EXTRACT(${column}, ${buildJsonPath(path)}))`,\n\n // JSON_TYPE spells numbers three ways depending on how the literal was\n // stored; anything else (including an absent path, where JSON_TYPE is\n // NULL) falls through the CASE to NULL\n numberAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS DOUBLE) END)`;\n },\n\n // CAST(... AS BINARY) yields VARBINARY, so < / > compare bytes instead of\n // the column's (case- and accent-insensitive by default) collation\n stringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS BINARY) END)`;\n },\n foldableStringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) END)`;\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${target}, ${value})`,\n\n lastElement: (target: Sql): Sql => sql`JSON_EXTRACT(${target}, '$[last]')`,\n\n // Comparing a JSON column to a plain string coerces the string to a JSON\n // string scalar (always-false for documents); CAST parses it as JSON\n value: (v: unknown): Sql => sql`CAST(${stringifyJson(v)} AS JSON)`,\n };\n\n arrays = {\n // MySQL uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n value: mysqlJsonListValue,\n\n // Deliberately the same container, by identity: MySQL stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The inline `ENUM(...)` describes\n // one member.\n enumValue: mysqlJsonListValue,\n\n // JSON_CONTAINS requires a JSON document as candidate; a bare string\n // parameter throws ER_INVALID_JSON_TEXT. JSON_ARRAY keeps the parameter's\n // type (strings quoted, numbers not): [x] ⊆ column ⟺ x ∈ column\n has: (column: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, JSON_ARRAY(${value}))`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, ${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`JSON_OVERLAPS(${column}, ${values})`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(JSON_LENGTH(${column}) = 0 OR ${column} IS NULL)`,\n\n // The container as TEXT, so it reaches the decode as the exact bytes the\n // codec wrote: uncast, mysql2 parses a JSON column into a JavaScript\n // document and JSON_OBJECT nests it as a live array, and the coefficient\n // grammar would then be read off values a JSON parser already interpreted.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS CHAR)`,\n\n length: (column: Sql): Sql => sql`JSON_LENGTH(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`JSON_EXTRACT(${column}, CONCAT('$[', ${index}, ']'))`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`JSON_ARRAY_APPEND(${column}, '$', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`JSON_SET(${column}, CONCAT('$[', ${index}, ']'), ${value})`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // mysql2's binary protocol binds JS numbers as DOUBLE, which MySQL rejects\n // in integer-only positions (\"Incorrect arguments to mysqld_stmt_execute\").\n // Inline integer LIMIT/OFFSET values instead of parameterizing them.\n clauses = {\n ...createStandardClauses(),\n limit: (count: Sql): Sql => sql`LIMIT ${inlineIntegerLiteral(count)}`,\n offset: (count: Sql): Sql => sql`OFFSET ${inlineIntegerLiteral(count)}`,\n };\n\n // JSON_MERGE_PRESERVE concatenates arrays element-wise; JSON_ARRAY_APPEND\n // would append the whole param as a single (stringified) element.\n set = {\n ...createNumericSetOperations(),\n\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalIncrement(column, by, target.decimal)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDecrement(column, by, target.decimal)\n : sql`${column} = ${column} - ${by}`,\n\n // A decimal target rounds the product back to the field's scale; every\n // other numeric column keeps MySQL's native multiplication.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalMultiply(column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n // MySQL `/` yields DECIMAL and rounds when assigned to an integer column.\n // Truncate explicitly so integer division matches PostgreSQL and SQLite.\n // A decimal target takes neither: `/` would round at\n // `div_precision_increment` digits, so the exact half-even quotient rule\n // decides the last digit instead.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n if (target?.decimal) {\n return mysqlDecimalDivide(column, by, target.decimal);\n }\n return target?.integer\n ? sql`${column} = TRUNCATE(${column} / ${by}, 0)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(COALESCE(${column}, JSON_ARRAY()), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(${values}, COALESCE(${column}, JSON_ARRAY()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n // MySQL has no bare OFFSET; per the manual, use an all-ones LIMIT sentinel\n noLimitValue = sql.raw`18446744073709551615`;\n\n readonly #assemble = {\n select: (rawParts: QueryParts): Sql => {\n // Inline integer LIMIT/OFFSET (see clauses above for why)\n const parts: QueryParts = {\n ...rawParts,\n limit: rawParts.limit && inlineIntegerLiteral(rawParts.limit),\n offset: rawParts.offset && inlineIntegerLiteral(rawParts.offset),\n };\n\n // MySQL doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // MySQL 8.0+ common table expressions\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\n\n // MySQL doesn't support RETURNING - returns empty\n // Use LAST_INSERT_ID() or SELECT after mutation\n returning: (_columns: Sql): Sql => sql.empty,\n\n // This low-level MySQL primitive ignores `_target`: ON DUPLICATE KEY UPDATE\n // fires on any unique collision. Public non-returning upserts therefore do\n // not execute this primitive; the query engine uses a locked, target-aware\n // branch so an unrelated unique collision still throws on every database.\n onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql): Sql => {\n return sql`ON DUPLICATE KEY UPDATE ${action}`;\n },\n\n // MySQL doesn't need UPDATE SET prefix - onConflict already includes UPDATE\n onConflictUpdate: (sets: Sql, _setWhere?: Sql): Sql => sets,\n\n // A self-assignment reacts only to duplicate-key conflicts. Unlike\n // INSERT IGNORE, unrelated constraint and conversion failures still abort.\n //\n // It stays the JUNCTION insert's clause on MySQL as well, because\n // `ON DUPLICATE KEY UPDATE` cannot name a target (`onConflict` above says\n // so) — correct for every junction whose PK is its sole unique constraint,\n // which is every ordinary pair table. A polymorphic member table with a\n // SINGULAR inverse also carries a target-side UNIQUE that this clause would\n // swallow; the seam for that case is documented at `junctionDuplicateSkip`\n // in `query-engine/builders/many-to-many-utils.ts`.\n skipDuplicates: (duplicateNoopColumn: string) => {\n const column = sql.raw(quoteIdent(duplicateNoopColumn));\n return {\n prefix: sql.empty,\n suffix: sql`ON DUPLICATE KEY UPDATE ${column} = ${column}`,\n };\n },\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n // The refusal is an invalid path (3143), never the invalid text (3141)\n // a premise fails with.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \\`__viborm_judged__\\`${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n // MySQL doesn't support FULL OUTER JOIN (would need a UNION of LEFT and\n // RIGHT joins). Never silently downgrade to LEFT JOIN: that drops rows.\n // The query engine never calls this today.\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations(quoteIdent);\n\n capabilities = {\n supportsReturning: false,\n supportsCteWithMutations: false, // MySQL CTEs are read-only\n supportsFullOuterJoin: false,\n supportsLateralJoins: true, // MySQL 8.0.14+\n supportsVector: false,\n supportsUpsertWhere: false, // ON DUPLICATE KEY UPDATE doesn't support WHERE clauses\n // ON DUPLICATE KEY UPDATE carries no conflict target and fires on ANY unique\n // collision — see the `onConflict` note above. A targeted upsert cannot be\n // spelled here, so the ON CONFLICT fold never opens on MySQL.\n supportsTargetedUpsert: false,\n // ERROR 1093: UPDATE/DELETE can't select from the mutated table in a\n // subquery. The engine wraps relation-filter subqueries in a derived\n // table when this is false (requires MySQL 8.0.14+ for outer references\n // in derived tables).\n supportsMutationTargetInSubquery: false,\n // MySQL's single-table UPDATE/DELETE take a native LIMIT, which is also the\n // only portable spelling here: the PK-subquery form would re-read the\n // mutated table and trip the same ERROR 1093 as above.\n supportsMutationRowLimit: true,\n supportsRowLocks: true,\n // InnoDB answers a locking miss on a unique index with a gap lock that\n // concurrent misses share and their INSERTs wait on (`ER_LOCK_DEADLOCK`).\n locksMissingKeys: true,\n boundsRecursionIterations: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n return {\n // EPSG:4326 is latitude-longitude in MySQL's SRS catalog. The explicit\n // WKT option makes the two bound coordinates longitude-latitude instead.\n value: (pointLongitude, pointLatitude) =>\n sql`ST_GeomFromText(CONCAT('POINT(', ${pointLongitude}, ' ', ${pointLatitude}, ')'), 4326, 'axis-order=long-lat')`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`MBRIntersects(${point}, ST_GeomFromGeoJSON(${polygon}, 1, 4326))`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}, 1, 4326)`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\n })();\n\n // RESULT PARSING\n // MySQL: booleans and naive UTC datetimes - both ROW VALUES.\n // This adapter says nothing about a RESULT: the engine's decoder asks for\n // the alias `_count` and reads it back, and mysql2 preserves that alias\n // (Arnaud's D-40, measured live).\n // Relation carriers decode at the query-engine boundary that knows their\n // value is JSON, so the adapter never sniffs ordinary strings.\n result: AdapterResultParser = {\n // A MySQL SCALAR decimal is `DECIMAL(p,s)` and answers with exact text, so\n // `decimalRepresentation` stays at its default. A decimal LIST is JSON,\n // which has no exact decimal at all, so its members are stored and returned\n // as unscaled coefficient strings (plan 6.1). This adapter is the reason\n // the two are separate declarations.\n decimalListRepresentation: \"coefficient\",\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"mysql\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing on all 20 asks D-40 measured over\n // seven operations and both routes on live MySQL - the `count`/`exist` arm\n // was entered on 10 of them and answered `undefined` every time\n // (`g4/rulings/o2/receipts/leg-probe-mysql.log`). A RESULT is the\n // decoder's, and D-28's chain ends there.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // MySQL stores booleans as TINYINT(1) - 0/1\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(\n value === \"0\" ? 0 : value === \"1\" ? 1 : value\n );\n if (parsed !== undefined) {\n return next(parsed);\n }\n }\n // Datetime strings are naive UTC wall-clock; without this, the default\n // parser's new Date(str) would shift them by the process timezone\n if (scalarType === \"datetime\" && typeof value === \"string\") {\n const iso = naiveDateTimeToIso(value);\n if (iso !== undefined) {\n return next(iso);\n }\n }\n return next();\n },\n };\n}\n"],"mappings":"q7BA6EA,MAAM,EAAa,EAAuB,IAAI,CACxC,EAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAAW,EAAQ,IACjB,CAAG,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,oBAC1C,WAAY,EAAQ,IAAgB,CAAG,OAAO,EAAE,IAAI,EAAE,GACvD,CASK,wBAA2B,GAC/BA,EAAI,IAAI,IAAI,OAAO,EAAO,CAAC,CAEvB,GAAkB,CAAG,2HAErB,EAAyB,CAAG,yBAG5B,aAAe,EAAW,EAAmB,IACjD,CAAG,QAAQ,EAAK,MAAMA,EAAI,IAAI,WAAW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CACjB,IAAM,EAAW,EAAuB,EAAO,CAC3C,KAAS,SAAW,EACxB,OAAO,KAAK,UAAU,GACpB,GAAG,EAAS,IACT,GACC,CAAG,iBAAiB,EAAM,uBAAuB,EAAQ,aAC5D,CACF,EAEJ,CACD,eAAgB,EAAO,IAId,CAAG,iBAHQ,CAAG,sBAAsB,EACzC,EACD,CAAC,YACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IACf,CAAG,sBAAsB,EAAK,IAAI,EAAM,IAAI,EAA8B,GAC7E,IACC,CASJ,OAA8B,CAM5B,0BAA2B,cAI3B,kBAAmB,EAAQ,IACzB,EAAY,EAAQ,EAAY,QAAQ,EAAE,gBAAkB,OAO9D,YAAa,EAEb,eACE,EACA,IACY,GAAM,CAEpB,YACE,EACA,EACA,IACY,CAEZ,GAAI,IAAe,UAAW,CAC5B,IAAM,EAAS,EACb,IAAU,IAAM,EAAI,IAAU,IAAM,EAAI,EACzC,CACD,GAAI,IAAW,IAAA,GACb,OAAO,EAAK,EAAO,CAKvB,GAAI,IAAe,YAAc,OAAO,GAAU,SAAU,CAC1D,IAAM,EAAM,mBAAmB,EAAM,CACrC,GAAI,IAAQ,IAAA,GACV,OAAO,EAAK,EAAI,CAGpB,OAAO,GAAM,EAEhB"}
@@ -1,9 +1,9 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{j as r,w as i}from"./geo-point-codec-DcUTvoEg.mjs";import{o as a}from"./native-types-BbKWN3JV.mjs";import{a as o}from"./physical-CAZ_LauY.mjs";import{r as s}from"./datetime-physical-codec-DfVmz14E.mjs";import{A as c,B as l,G as u,H as d,I as f,K as p,L as m,N as h,R as g,U as _,V as v,W as y,Y as b,j as x,m as S,q as C,z as w}from"./client-C1MxqFtt.mjs";import{r as T}from"./identity-Bu6jbgym.mjs";import{P as E}from"./standard-sql-wRMNi-Yg.mjs";import{a as D,i as O,o as k}from"./identifier-conversion-8ldidfgu.mjs";const namespaceMeta=e=>({dialect:`mysql`,namespace:e});async function resolveCatalogNamespace(e,r){if(r===void 0)throw new n(`This MySQL client's adapter declares no database, so there is no catalog to read. MySQL migration artifacts are database-relative on purpose: supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});let{rows:i}=await e(`
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{E as r,N as i}from"./geo-point-codec-CIZxuIvE.mjs";import{o as a}from"./native-types-CQH05hcr.mjs";import{a as o}from"./physical-t_gDjUCD.mjs";import{r as s}from"./datetime-physical-codec-DTdvABny.mjs";import{A as c,B as l,G as u,H as d,I as f,K as p,L as m,N as h,R as g,U as _,V as v,W as y,Y as b,j as x,m as S,q as C,z as w}from"./client-l7dSOul5.mjs";import{r as T}from"./identity-BtuwgqhS.mjs";import{P as E}from"./standard-sql-Ci8ROrql.mjs";import{a as D,i as O,o as k}from"./identifier-conversion-BXrBYgAq.mjs";const namespaceMeta=e=>({dialect:`mysql`,namespace:e});async function resolveCatalogNamespace(e,r){if(r===void 0)throw new n(`This MySQL client's adapter declares no database, so there is no catalog to read. MySQL migration artifacts are database-relative on purpose: supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});let{rows:i}=await e(`
2
2
  SELECT SCHEMA_NAME
3
3
  FROM information_schema.SCHEMATA
4
4
  WHERE LOWER(SCHEMA_NAME) = LOWER(?)
5
5
  ORDER BY SCHEMA_NAME
6
- `,[r]),a=i.map(e=>e.SCHEMA_NAME).filter(e=>typeof e==`string`);if(a.length===0)throw new n(`The MySQL database "${r}" does not exist or is not visible to this connection. VibORM never creates or drops a database: create it, or grant this user access to it, before running migration work against it.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`missing-database`}});let o=a.find(e=>e===r);if(o!==void 0)return o;let[s]=a;if(a.length===1&&s!==void 0)return s;throw new n(`The MySQL database "${r}" matches ${a.length} existing databases that differ only by case (${a.join(`, `)}). Configure the exact name this server reports so migration work cannot land in the wrong one.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`ambiguous-database`,candidates:a}})}const A=/^viborm_decimal_([sl])_(\d+)_(\d+)$/,j=/^_[a-zA-Z0-9]+(?=')/,M=/\s/;function refuseReservedConstraint(e,r,i){throw new n(`The MySQL CHECK constraint "${e}" on table "${r}" uses VibORM's reserved decimal-conversion namespace but ${i}. Migration work is refused before any cleanup or schema effect; rename the user-owned constraint, or restore the exact interrupted VibORM conversion proof and run the command again.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`decimal-conversion-constraint-collision`,table:r,constraint:e}})}function readString(e,t,n,r){if(typeof e==`string`)return e;refuseReservedConstraint(t,n,`its catalog ${r} is not a string`)}function normalizeCheckClause(e){let t=e.replaceAll(`\\'`,`'`),n=``,r=0;for(;r<t.length;){let i=t[r];if(i===`'`){let e=r;for(r++;r<t.length;){if(t[r]===`\\`&&r+1<t.length){r+=2;continue}if(t[r]===`'`&&t[r+1]===`'`){r+=2;continue}if(t[r]===`'`){r++;break}r++}n+=t.slice(e,r);continue}if(i==="`"){let i=t.indexOf("`",r+1);if(i<0)return e;n+=t.slice(r,i+1),r=i+1;continue}if(M.test(i??``)){r++;continue}if(i===`_`){let e=j.exec(t.slice(r));if(e!==null){r+=e[0].length;continue}}n+=i?.toLowerCase()??``,r++}return n}function expectedConstraint(e,t,n){let r=`\`${e.name}\``;return t===`s`?d(r,`DECIMAL(${n.precision},${n.scale})`):y(r,n)}function readDescriptor(e,t,n){let i=r(e[2],e[3],`mysql`);return i===void 0&&refuseReservedConstraint(t,n,`its name declares a decimal domain this provider does not admit`),w(e[1]===`s`?`scalar`:`list`,i)!==t&&refuseReservedConstraint(t,n,`its name is not the canonical spelling of its decimal proof`),i}function proveConstraint(e,t){let n=typeof e.CONSTRAINT_NAME==`string`?e.CONSTRAINT_NAME:`<unreported>`,r=typeof e.TABLE_NAME==`string`?e.TABLE_NAME:`<unreported>`,i=readString(e.CONSTRAINT_NAME,n,r,`CONSTRAINT_NAME`),a=readString(e.TABLE_NAME,i,r,`TABLE_NAME`),o=readString(e.CHECK_CLAUSE,i,a,`CHECK_CLAUSE`);readString(e.ENFORCED,i,a,`ENFORCED`)!==`YES`&&refuseReservedConstraint(i,a,`its CHECK is not enforced`);let s=A.exec(i);s===null&&refuseReservedConstraint(i,a,`its name does not match the complete reserved proof identity`);let c=s[1]===`s`?`s`:`l`,l=readDescriptor(s,i,a),u=t.get(a)??[],d=normalizeCheckClause(o);for(let e of u){if(normalizeCheckClause(expectedConstraint(e,c,l))!==d)continue;if(c===`s`){if(e.dataType===`decimal`||e.dataType===`int`||e.dataType===`bigint`)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its scalar proof is attached to impossible ${e.dataType} storage`)}e.dataType!==`json`&&refuseReservedConstraint(i,a,`its list proof is attached to impossible ${e.dataType} storage`);let t;try{t=b(e.comment)}catch{refuseReservedConstraint(i,a,`its JSON column carries an invalid decimal-list marker`)}if(t!==void 0&&t.scale===l.scale&&t.precision>=l.precision)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its JSON column does not carry a compatible source or target decimal-list marker`)}refuseReservedConstraint(i,a,`its concrete CHECK predicate does not match that proof identity`)}function groupColumns(e){let t=new Map;for(let n of e){let e=typeof n.TABLE_NAME==`string`?n.TABLE_NAME:``,r=typeof n.COLUMN_NAME==`string`?n.COLUMN_NAME:``,i=typeof n.DATA_TYPE==`string`?n.DATA_TYPE:``,a=typeof n.COLUMN_COMMENT==`string`?n.COLUMN_COMMENT:``;if(e===``||r===``||i===``)continue;let o=t.get(e)??[];o.push({name:r,dataType:i.toLowerCase(),comment:a}),t.set(e,o)}return t}async function planInterruptedMySQLDecimalRecovery(e,t,n){let{rows:r}=await e(`
6
+ `,[r]),a=i.map(e=>e.SCHEMA_NAME).filter(e=>typeof e==`string`);if(a.length===0)throw new n(`The MySQL database "${r}" does not exist or is not visible to this connection. VibORM never creates or drops a database: create it, or grant this user access to it, before running migration work against it.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`missing-database`}});let o=a.find(e=>e===r);if(o!==void 0)return o;let[s]=a;if(a.length===1&&s!==void 0)return s;throw new n(`The MySQL database "${r}" matches ${a.length} existing databases that differ only by case (${a.join(`, `)}). Configure the exact name this server reports so migration work cannot land in the wrong one.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`ambiguous-database`,candidates:a}})}const A=/^viborm_decimal_([sl])_(\d+)_(\d+)$/,j=/^_[a-zA-Z0-9]+(?=')/,M=/\s/;function refuseReservedConstraint(e,r,i){throw new n(`The MySQL CHECK constraint "${e}" on table "${r}" uses VibORM's reserved decimal-conversion namespace but ${i}. Migration work is refused before any cleanup or schema effect; rename the user-owned constraint, or restore the exact interrupted VibORM conversion proof and run the command again.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`decimal-conversion-constraint-collision`,table:r,constraint:e}})}function readString(e,t,n,r){if(typeof e==`string`)return e;refuseReservedConstraint(t,n,`its catalog ${r} is not a string`)}function normalizeCheckClause(e){let t=e.replaceAll(`\\'`,`'`),n=``,r=0;for(;r<t.length;){let i=t[r];if(i===`'`){let e=r;for(r++;r<t.length;){if(t[r]===`\\`&&r+1<t.length){r+=2;continue}if(t[r]===`'`&&t[r+1]===`'`){r+=2;continue}if(t[r]===`'`){r++;break}r++}n+=t.slice(e,r);continue}if(i==="`"){let i=t.indexOf("`",r+1);if(i<0)return e;n+=t.slice(r,i+1),r=i+1;continue}if(M.test(i??``)){r++;continue}if(i===`_`){let e=j.exec(t.slice(r));if(e!==null){r+=e[0].length;continue}}n+=i?.toLowerCase()??``,r++}return n}function expectedConstraint(e,t,n){let r=`\`${e.name}\``;return t===`s`?d(r,`DECIMAL(${n.precision},${n.scale})`):y(r,n)}function readDescriptor(e,t,n){let r=i(e[2],e[3],`mysql`);return r===void 0&&refuseReservedConstraint(t,n,`its name declares a decimal domain this provider does not admit`),w(e[1]===`s`?`scalar`:`list`,r)!==t&&refuseReservedConstraint(t,n,`its name is not the canonical spelling of its decimal proof`),r}function proveConstraint(e,t){let n=typeof e.CONSTRAINT_NAME==`string`?e.CONSTRAINT_NAME:`<unreported>`,r=typeof e.TABLE_NAME==`string`?e.TABLE_NAME:`<unreported>`,i=readString(e.CONSTRAINT_NAME,n,r,`CONSTRAINT_NAME`),a=readString(e.TABLE_NAME,i,r,`TABLE_NAME`),o=readString(e.CHECK_CLAUSE,i,a,`CHECK_CLAUSE`);readString(e.ENFORCED,i,a,`ENFORCED`)!==`YES`&&refuseReservedConstraint(i,a,`its CHECK is not enforced`);let s=A.exec(i);s===null&&refuseReservedConstraint(i,a,`its name does not match the complete reserved proof identity`);let c=s[1]===`s`?`s`:`l`,l=readDescriptor(s,i,a),u=t.get(a)??[],d=normalizeCheckClause(o);for(let e of u){if(normalizeCheckClause(expectedConstraint(e,c,l))!==d)continue;if(c===`s`){if(e.dataType===`decimal`||e.dataType===`int`||e.dataType===`bigint`)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its scalar proof is attached to impossible ${e.dataType} storage`)}e.dataType!==`json`&&refuseReservedConstraint(i,a,`its list proof is attached to impossible ${e.dataType} storage`);let t;try{t=b(e.comment)}catch{refuseReservedConstraint(i,a,`its JSON column carries an invalid decimal-list marker`)}if(t!==void 0&&t.scale===l.scale&&t.precision>=l.precision)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its JSON column does not carry a compatible source or target decimal-list marker`)}refuseReservedConstraint(i,a,`its concrete CHECK predicate does not match that proof identity`)}function groupColumns(e){let t=new Map;for(let n of e){let e=typeof n.TABLE_NAME==`string`?n.TABLE_NAME:``,r=typeof n.COLUMN_NAME==`string`?n.COLUMN_NAME:``,i=typeof n.DATA_TYPE==`string`?n.DATA_TYPE:``,a=typeof n.COLUMN_COMMENT==`string`?n.COLUMN_COMMENT:``;if(e===``||r===``||i===``)continue;let o=t.get(e)??[];o.push({name:r,dataType:i.toLowerCase(),comment:a}),t.set(e,o)}return t}async function planInterruptedMySQLDecimalRecovery(e,t,n){let{rows:r}=await e(`
7
7
  SELECT
8
8
  tc.TABLE_NAME,
9
9
  tc.CONSTRAINT_NAME,
@@ -22,7 +22,7 @@ SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT
22
22
  FROM information_schema.COLUMNS
23
23
  WHERE TABLE_SCHEMA = ?
24
24
  ORDER BY TABLE_NAME, ORDINAL_POSITION
25
- `,[t])).rows);return r.map(e=>proveConstraint(e,i)).map(e=>`ALTER TABLE ${n(t)}.${n(e.tableName)} DROP CHECK ${n(e.constraintName)}`)}const N=new Set([`bigint`,`bit`,`decimal`,`double`,`float`,`int`,`integer`,`mediumint`,`numeric`,`real`,`smallint`,`tinyint`]);function formatColumnType(e){if(e.DATA_TYPE.toLowerCase()===`point`){let t=readSrid(e);return t===void 0?`POINT`:`POINT SRID ${t}`}if(e.DATA_TYPE===`enum`){let t=g(e.COLUMN_TYPE);return t?f(t):e.COLUMN_TYPE}let t=e.COLUMN_TYPE.toLowerCase();return t.includes(`unsigned`)||t.includes(`zerofill`)||t.includes(`(`)&&e.DATA_TYPE!==`enum`?e.COLUMN_TYPE:e.DATA_TYPE===`varchar`&&e.CHARACTER_MAXIMUM_LENGTH?`VARCHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`char`&&e.CHARACTER_MAXIMUM_LENGTH?`CHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION?e.NUMERIC_SCALE!==null&&e.NUMERIC_SCALE!==void 0?`DECIMAL(${e.NUMERIC_PRECISION},${e.NUMERIC_SCALE})`:`DECIMAL(${e.NUMERIC_PRECISION})`:e.DATA_TYPE.toUpperCase()}function readSrid(e){if(e.SRS_ID===null||e.SRS_ID===void 0)return;let r=Number(e.SRS_ID);if(Number.isSafeInteger(r)&&r>=0&&r<=4294967295)return r;throw new n(`MySQL reported an invalid SRID for column "${e.TABLE_NAME}"."${e.COLUMN_NAME}". Migration introspection is refused rather than publishing an unprovable spatial type.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-srid`}})}function isAutoIncrement(e){return e.toLowerCase().includes(`auto_increment`)}function readDecimalDomain(e){if(e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION!==null){let i=r(e.NUMERIC_PRECISION,e.NUMERIC_SCALE??0,`mysql`);if(i!==void 0)return i;throw new n(`MySQL reported column "${e.TABLE_NAME}"."${e.COLUMN_NAME}" as DECIMAL(${String(e.NUMERIC_PRECISION)},${String(e.NUMERIC_SCALE??0)}), outside VibORM's complete exact-decimal domain for this provider. Migration introspection is refused rather than publishing an invalid descriptor.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-decimal-domain`}})}if(e.DATA_TYPE===`json`)return b(e.COLUMN_COMMENT)}const P=/^_([A-Za-z0-9_]+)\\'([\s\S]*)\\'$/,F=/\\([\s\S]?)/g;function decodeSingleByte(e){return Array.from(e,e=>String.fromCharCode(e)).join(``)}const I=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376];function decodeLatin1(e){return Array.from(e,e=>String.fromCharCode(e>=128&&e<=159?I[e-128]??e:e)).join(``)}const L=new Map([[`utf8`,T],[`utf8mb3`,T],[`utf8mb4`,T],[`latin1`,decodeLatin1],[`ascii`,decodeSingleByte],[`binary`,decodeSingleByte]]);function decodeIntroducedLiteral(e,t){let n=L.get(e.toLowerCase());if(n===void 0)return;let r=[...t].map(e=>e.codePointAt(0)??0);if(!r.some(e=>e>255))try{return n(Uint8Array.from(r))}catch{return}}function unescapeOneLayer(e){let t=!0,n=e.replace(F,(e,n)=>{let r=c.get(n);return r===void 0?(t=!1,n):r});return t?n:void 0}function deparsedStringValue(e){let t=P.exec(e),n=t?.[1],r=t?.[2],i=n===void 0||r===void 0?void 0:decodeIntroducedLiteral(n,r),a=i===void 0?void 0:unescapeOneLayer(i);return a===void 0?void 0:unescapeOneLayer(a)}function cleanDefault(e){let t=e.COLUMN_DEFAULT;if(t!==null){if(e.EXTRA.toUpperCase().includes(`DEFAULT_GENERATED`)){let e=deparsedStringValue(t);return e===void 0?t:`(${m(e)})`}return N.has(e.DATA_TYPE.toLowerCase())?t:m(t)}}function admitContainedForeignKeys(e,r,i){for(let a of e)if(!(i!==void 0&&!(a.TABLE_SCHEMA===r&&i.includes(a.TABLE_NAME))&&!(a.REFERENCED_TABLE_SCHEMA===r&&i.includes(a.REFERENCED_TABLE_NAME)))&&!(a.TABLE_SCHEMA===r&&a.REFERENCED_TABLE_SCHEMA===r))throw new n(`Foreign key "${a.CONSTRAINT_NAME}" crosses a database boundary: \`${a.TABLE_SCHEMA}\`.\`${a.TABLE_NAME}\` references \`${a.REFERENCED_TABLE_SCHEMA}\`.\`${a.REFERENCED_TABLE_NAME}\`, and this client manages only "${r}". Migration work is refused before any snapshot, plan or DDL: VibORM cannot recreate or drop a constraint whose other half lives in a database it does not own.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`cross-database-foreign-key`,constraint:a.CONSTRAINT_NAME,namespace:r,table:`${a.TABLE_SCHEMA}.${a.TABLE_NAME}`,referencedTable:`${a.REFERENCED_TABLE_SCHEMA}.${a.REFERENCED_TABLE_NAME}`}})}async function introspect(e,r,i){let a=await resolveCatalogNamespace(e,r),o=[a],s=await e(`
25
+ `,[t])).rows);return r.map(e=>proveConstraint(e,i)).map(e=>`ALTER TABLE ${n(t)}.${n(e.tableName)} DROP CHECK ${n(e.constraintName)}`)}const N=new Set([`bigint`,`bit`,`decimal`,`double`,`float`,`int`,`integer`,`mediumint`,`numeric`,`real`,`smallint`,`tinyint`]);function formatColumnType(e){if(e.DATA_TYPE.toLowerCase()===`point`){let t=readSrid(e);return t===void 0?`POINT`:`POINT SRID ${t}`}if(e.DATA_TYPE===`enum`){let t=g(e.COLUMN_TYPE);return t?f(t):e.COLUMN_TYPE}let t=e.COLUMN_TYPE.toLowerCase();return t.includes(`unsigned`)||t.includes(`zerofill`)||t.includes(`(`)&&e.DATA_TYPE!==`enum`?e.COLUMN_TYPE:e.DATA_TYPE===`varchar`&&e.CHARACTER_MAXIMUM_LENGTH?`VARCHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`char`&&e.CHARACTER_MAXIMUM_LENGTH?`CHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION?e.NUMERIC_SCALE!==null&&e.NUMERIC_SCALE!==void 0?`DECIMAL(${e.NUMERIC_PRECISION},${e.NUMERIC_SCALE})`:`DECIMAL(${e.NUMERIC_PRECISION})`:e.DATA_TYPE.toUpperCase()}function readSrid(e){if(e.SRS_ID===null||e.SRS_ID===void 0)return;let r=Number(e.SRS_ID);if(Number.isSafeInteger(r)&&r>=0&&r<=4294967295)return r;throw new n(`MySQL reported an invalid SRID for column "${e.TABLE_NAME}"."${e.COLUMN_NAME}". Migration introspection is refused rather than publishing an unprovable spatial type.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-srid`}})}function isAutoIncrement(e){return e.toLowerCase().includes(`auto_increment`)}function readDecimalDomain(e){if(e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION!==null){let r=i(e.NUMERIC_PRECISION,e.NUMERIC_SCALE??0,`mysql`);if(r!==void 0)return r;throw new n(`MySQL reported column "${e.TABLE_NAME}"."${e.COLUMN_NAME}" as DECIMAL(${String(e.NUMERIC_PRECISION)},${String(e.NUMERIC_SCALE??0)}), outside VibORM's complete exact-decimal domain for this provider. Migration introspection is refused rather than publishing an invalid descriptor.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-decimal-domain`}})}if(e.DATA_TYPE===`json`)return b(e.COLUMN_COMMENT)}const P=/^_([A-Za-z0-9_]+)\\'([\s\S]*)\\'$/,F=/\\([\s\S]?)/g;function decodeSingleByte(e){return Array.from(e,e=>String.fromCharCode(e)).join(``)}const I=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376];function decodeLatin1(e){return Array.from(e,e=>String.fromCharCode(e>=128&&e<=159?I[e-128]??e:e)).join(``)}const L=new Map([[`utf8`,T],[`utf8mb3`,T],[`utf8mb4`,T],[`latin1`,decodeLatin1],[`ascii`,decodeSingleByte],[`binary`,decodeSingleByte]]);function decodeIntroducedLiteral(e,t){let n=L.get(e.toLowerCase());if(n===void 0)return;let r=[...t].map(e=>e.codePointAt(0)??0);if(!r.some(e=>e>255))try{return n(Uint8Array.from(r))}catch{return}}function unescapeOneLayer(e){let t=!0,n=e.replace(F,(e,n)=>{let r=c.get(n);return r===void 0?(t=!1,n):r});return t?n:void 0}function deparsedStringValue(e){let t=P.exec(e),n=t?.[1],r=t?.[2],i=n===void 0||r===void 0?void 0:decodeIntroducedLiteral(n,r),a=i===void 0?void 0:unescapeOneLayer(i);return a===void 0?void 0:unescapeOneLayer(a)}function cleanDefault(e){let t=e.COLUMN_DEFAULT;if(t!==null){if(e.EXTRA.toUpperCase().includes(`DEFAULT_GENERATED`)){let e=deparsedStringValue(t);return e===void 0?t:`(${m(e)})`}return N.has(e.DATA_TYPE.toLowerCase())?t:m(t)}}function admitContainedForeignKeys(e,r,i){for(let a of e)if(!(i!==void 0&&!(a.TABLE_SCHEMA===r&&i.includes(a.TABLE_NAME))&&!(a.REFERENCED_TABLE_SCHEMA===r&&i.includes(a.REFERENCED_TABLE_NAME)))&&!(a.TABLE_SCHEMA===r&&a.REFERENCED_TABLE_SCHEMA===r))throw new n(`Foreign key "${a.CONSTRAINT_NAME}" crosses a database boundary: \`${a.TABLE_SCHEMA}\`.\`${a.TABLE_NAME}\` references \`${a.REFERENCED_TABLE_SCHEMA}\`.\`${a.REFERENCED_TABLE_NAME}\`, and this client manages only "${r}". Migration work is refused before any snapshot, plan or DDL: VibORM cannot recreate or drop a constraint whose other half lives in a database it does not own.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`cross-database-foreign-key`,constraint:a.CONSTRAINT_NAME,namespace:r,table:`${a.TABLE_SCHEMA}.${a.TABLE_NAME}`,referencedTable:`${a.REFERENCED_TABLE_SCHEMA}.${a.REFERENCED_TABLE_NAME}`}})}async function introspect(e,r,i){let a=await resolveCatalogNamespace(e,r),o=[a],s=await e(`
26
26
  SELECT TABLE_NAME
27
27
  FROM information_schema.TABLES
28
28
  WHERE TABLE_SCHEMA = ?
@@ -94,6 +94,6 @@ JOIN information_schema.REFERENTIAL_CONSTRAINTS rc
94
94
  WHERE tc.CONSTRAINT_TYPE = 'FOREIGN KEY'
95
95
  AND (tc.TABLE_SCHEMA = ? OR kcu.REFERENCED_TABLE_SCHEMA = ?)
96
96
  ORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION
97
- `,[a,a]);admitContainedForeignKeys(d.rows,a,i);let p=O(c.rows,e=>e.TABLE_NAME),m=O(l.rows,e=>e.TABLE_NAME),h=D(u.rows,e=>e.TABLE_NAME,e=>e.INDEX_NAME),_=D(d.rows.filter(e=>e.TABLE_SCHEMA===a),e=>e.TABLE_NAME,e=>e.CONSTRAINT_NAME),v=[],y=new Set,b=[];for(let e of s.rows){let r=e.TABLE_NAME,a=[];for(let e of p.get(r)||[]){if((i===void 0||i.includes(r))&&(e.EXTRA.toUpperCase().includes(`VIRTUAL GENERATED`)||e.EXTRA.toUpperCase().includes(`STORED GENERATED`)))throw new n(`MySQL column "${r}.${e.COLUMN_NAME}" is generated. Synchronization refuses before effects because its expression cannot be represented.`,t.MIGRATION_INVALID_STATE,{meta:{table:r,column:e.COLUMN_NAME,feature:`generated column`}});if(e.DATA_TYPE===`enum`){let t=g(e.COLUMN_TYPE),n=t&&f(t);t&&n&&!y.has(n)&&(v.push({name:n,values:t}),y.add(n))}let o=i===void 0||i.includes(r),s=o?readDecimalDomain(e):void 0;a.push({name:e.COLUMN_NAME,type:o?formatColumnType(e):e.COLUMN_TYPE,nullable:e.IS_NULLABLE===`YES`,default:o?cleanDefault(e):void 0,autoIncrement:isAutoIncrement(e.EXTRA),decimal:s})}let o,s=m.get(r);if(s&&s.length>0){s.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let e=s[0];e&&(o={columns:s.map(e=>e.COLUMN_NAME),name:e.CONSTRAINT_NAME})}let c=[],l=h.get(r),u=new Set(_.get(r)?.keys()??[]);if(l)for(let[e,t]of l){if(u.has(e))continue;t.sort((e,t)=>e.SEQ_IN_INDEX-t.SEQ_IN_INDEX);let n=t[0];if(n){let r=n.INDEX_TYPE.toLowerCase(),i=r===`rtree`?`spatial`:r;c.push({name:e,columns:t.map(e=>e.COLUMN_NAME),unique:n.NON_UNIQUE===0,type:i===`btree`||i===`hash`||i===`fulltext`||i===`spatial`?i:void 0})}}let d=[],x=_.get(r);if(x)for(let[e,t]of x){t.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let n=t[0];n&&d.push({name:e,columns:t.map(e=>e.COLUMN_NAME),referencedTable:n.REFERENCED_TABLE_NAME,referencedColumns:t.map(e=>e.REFERENCED_COLUMN_NAME),onDelete:k(n.DELETE_RULE),onUpdate:k(n.UPDATE_RULE)})}b.push({name:r,columns:a,primaryKey:o,indexes:c,foreignKeys:d,uniqueConstraints:[]})}return{tables:b,enums:v.length>0?v:void 0}}const R=/[^a-z0-9_]/g;function hashLockScope(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function mysqlMigrationLockName(e){let t=e.toLowerCase();return`viborm_migration_${t.replace(R,`_`).slice(0,38)}_${hashLockScope(t)}`}function mysqlAcquireLockStatement(e,t,n){return`SELECT GET_LOCK(${n(mysqlMigrationLockName(e))}, ${t}) AS acquired`}function mysqlReleaseLockStatement(e,t){return`SELECT RELEASE_LOCK(${t(mysqlMigrationLockName(e))}) AS released`}function mysqlLockAnswer(e,t){if(e.length!==1)return!1;let n=e[0];if(typeof n!=`object`||!n)return!1;let r=Reflect.get(n,t);return typeof r==`number`?r===1:typeof r==`string`?Number(r)===1:!1}function mysqlSelectTargetStatement(e,t){return`USE ${t(e)}`}const z=/^(\d+)\.(\d+)\.(\d+)/;async function proveMySQLExactValueSession(e,r){let{rows:i}=await e(`SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS server_version`),a=i[0],o=typeof a==`object`&&a?Reflect.get(a,`sql_mode`):void 0,s=typeof o==`string`?o:``,c=typeof a==`object`&&a?Reflect.get(a,`server_version`):void 0,l=typeof c==`string`?c:`<unreported>`;if(!supportsEnforcedMySQLChecks(l))throw new n(`This MySQL migration session reports version "${l}". Fixed-decimal conversions require MySQL 8.0.16 or later, where CHECK constraints are enforced; the command is refused before any migration effect.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`unenforced-check-constraints`,target:r}});if(!s.split(`,`).some(e=>{let t=e.trim();return t===`STRICT_TRANS_TABLES`||t===`STRICT_ALL_TABLES`}))throw new n(`This MySQL session runs in sql_mode "${s}", which has neither STRICT_TRANS_TABLES nor STRICT_ALL_TABLES. Effectful migration work is refused: without a strict mode MySQL answers an out-of-range DECIMAL with a warning and stores the clamped value, so an exact fixed-decimal column would silently stop holding what it was given. Enable a strict mode on the server or on this connection and run the command again.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`non-strict-sql-mode`,target:r}})}function supportsEnforcedMySQLChecks(e){if(e.toLowerCase().includes(`mariadb`))return!1;let t=z.exec(e);if(t===null)return!1;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]);return n>8||n===8&&(r>0||i>=16)}const B=[/^GEOMETRY\b/,/^POINT\b/,/^LINESTRING\b/,/^POLYGON\b/,/^MULTIPOINT\b/,/^MULTILINESTRING\b/,/^MULTIPOLYGON\b/,/^GEOMETRYCOLLECTION\b/],V=/^(?:(?:TINY|MEDIUM|LONG)?(?:TEXT|BLOB)|JSON|GEOMETRY|POINT|LINESTRING|POLYGON|MULTI(?:POINT|LINESTRING|POLYGON)|GEOMETRYCOLLECTION)\b/i,H=/[\s(]/;function classifyDecimalListDescriptorChange(e,t){return e.scale===t.scale?e.precision<t.precision?`widening`:e.precision>t.precision?`narrowing`:`same`:`rescaling`}const U=x.point.indexOf(` `),W=x.point.slice(0,U),G=x.point.slice(U+1);function mysqlRefusesLiteralDefault(e){let t=e.toUpperCase();return t.includes(`TEXT`)||t.includes(`BLOB`)||t.includes(`JSON`)||B.some(e=>e.test(t))}const K=/^(?:DATETIME|TIMESTAMP)\s*(?:\((\d+)\))?$/i;function mysqlNowExpression(e){let t=K.exec(e.trim());if(t!==null)return t[1]===void 0?`CURRENT_TIMESTAMP`:`CURRENT_TIMESTAMP(${t[1]})`}function finalizeMySQLColumn(e,t){let n=e.type.toUpperCase()===`TEXT`&&t?`VARCHAR(191)`:e.type,r=e.default!==void 0&&mysqlRefusesLiteralDefault(n)?`(${e.default})`:e.default;return n===e.type&&r===e.default?e:{...e,type:n,default:r}}function isMySQLExactIntegerType(e){let t=e.trim().toUpperCase().split(H,1)[0];return t===`INT`||t===`INTEGER`||t===`BIGINT`}const q=new class MySQLMigrationDriver extends S{dialect=`mysql`;driverName=`mysql`;capabilities={supportsNativeEnums:!0,supportsAddEnumValueInTransaction:!1,supportsIndexTypes:[`btree`,`fulltext`,`spatial`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!0,introspectionReadsConstraintNames:!0};getIrreversibleRollbackReason(e){if(e.type!==`alterColumn`)return;let t=e.from.decimal,n=e.to.decimal;if(!(t===void 0||n===void 0||C(e.from)!==`list`||C(e.to)!==`list`||classifyDecimalListDescriptorChange(t,n)!==`narrowing`))return`MySQL cannot automatically roll back the decimal-list widening of "${e.tableName}"."${e.columnName}": the inverse narrows ${i(t)} to ${i(n)}, and its implicit DDL commits cannot make the stricter proof, descriptor-marker change, and cleanup indivisible.`}async preflightSchemaRequirements(e,r){let i=new Set(e.flatMap(e=>e.tables.map(e=>e.name)));if(i.size===0)return!1;let a=await resolveCatalogNamespace(r,this.namespace),o=(await r(`SELECT TABLE_NAME FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ?`,[a])).rows.find(e=>i.has(e.TABLE_NAME));if(o)throw new n(`MySQL relation "${o.TABLE_NAME}" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,t.MIGRATION_INVALID_STATE,{meta:{table:o.TABLE_NAME,feature:`view`,namespace:a}});return!1}introspect(e){return introspect(e,this.namespace,this.target?.tables)}escapeValue(e){return e==null?`NULL`:m(String(e))}escapeIdentifier(e){if(e==null)throw new n(`Cannot escape null or undefined identifier`,t.INVALID_INPUT);return`\`${String(e).replace(/`/g,"``")}\``}tableRef(e,t){return E(e=>this.escapeIdentifier(e),t===`live`?this.namespace:void 0,e)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0||t.array===!0?void 0:o(n,r,`mysql`);if(i)return i.columnType;let s=a(r,`mysql`);return s&&!t.array?s.type:h({type:t.type,array:t.array,decimal:t.decimal})}getDefaultExpression(e,t){let n=t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate?this.literalDefaultValue(t):void 0;if(t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate&&typeof n==`string`)return this.escapeValue(s(n));if(!(t.hasDefault&&t.default===null))return t.autoGenerate?.kind===`now`?mysqlNowExpression(this.mapScalarType(e,t)):super.getDefaultExpression(e,t)}finalizeTable(e){let r=new Set([...e.primaryKey?.columns??[],...e.uniqueConstraints.flatMap(e=>e.columns),...e.indexes.flatMap(e=>e.columns),...e.foreignKeys.flatMap(e=>e.columns)]),i=new Set(e.indexes.map(e=>e.name)),a=e.uniqueConstraints.filter(e=>!i.has(e.name)).map(e=>({name:e.name,columns:e.columns,unique:!0})),o={...e,primaryKey:e.primaryKey?{...e.primaryKey,name:`PRIMARY`}:void 0,columns:e.columns.map(e=>finalizeMySQLColumn(e,r.has(e.name))),indexes:[...e.indexes,...a],uniqueConstraints:[]},s=o.indexes.filter(e=>!e.type||e.type===`btree`),c=[{name:`PRIMARY`,columns:o.primaryKey?.columns??[]},...s.map(e=>({name:e.name,columns:e.columns})),...o.foreignKeys.map(e=>({name:e.name,columns:e.columns}))];for(let{name:r,columns:i}of c)for(let a of i){let i=o.columns.find(e=>e.name===a);if(i&&V.test(i.type))throw new n(`MySQL key "${e.name}.${r}" cannot directly index ${i.type} column "${i.name}". Use an indexable native type such as VARCHAR, or manage a reviewed prefix/expression index outside this declaration.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.name,column:i.name}})}let l=o.columns.filter(e=>e.autoIncrement);if(l.length>1||l.some(e=>o.primaryKey?.columns[0]!==e.name&&!s.some(t=>t.columns[0]===e.name&&!t.where)&&!o.foreignKeys.some(t=>t.columns[0]===e.name)))throw new n(`MySQL table "${e.name}" requires at most one AUTO_INCREMENT column, first in an ordinary key. Declare its primary key or leading index explicitly.`,t.INVALID_INPUT,{meta:{table:e.name}});return o}formatBooleanDefault(e){return e?`1`:`0`}getEnumColumnType(e,t,n){return f(n)}static AUTO_INCREMENT_TYPES=new Set([`tinyint`,`smallint`,`mediumint`,`int`,`integer`,`bigint`]);validateAutoIncrementType(e){let r=e.type.toLowerCase().split(H)[0];if(!MySQLMigrationDriver.AUTO_INCREMENT_TYPES.has(r))throw new n(`MySQL AUTO_INCREMENT requires an integer type (TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT). Column "${e.name}" has type "${e.type}" which is not compatible with AUTO_INCREMENT.`,t.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}})}generateColumnDef(e,t){let n=[this.escapeIdentifier(e.name)],r=e.type.toUpperCase()===x.point;return e.autoIncrement?(this.validateAutoIncrementType(e),n.push(e.type),n.push(`AUTO_INCREMENT`)):n.push(r?W:e.type),e.nullable||n.push(`NOT NULL`),r&&n.push(G),e.default!==void 0&&!e.autoIncrement&&n.push(`DEFAULT ${e.default}`),e.decimal&&C(e)===`list`&&n.push(`COMMENT ${this.escapeValue(p(e.decimal))}`),n.join(` `)}generateCreateTable(e,t){let{table:n}=e,r=n.columns.map(e=>this.generateColumnDef(e,t)),i=n.columns.find(e=>e.autoIncrement),a=i&&n.primaryKey?.columns[0]!==i.name?n.indexes.find(e=>(!e.type||e.type===`btree`)&&!e.where&&e.columns[0]===i.name):void 0;if(a&&r.push(`${a.unique?`UNIQUE `:``}KEY ${this.escapeIdentifier(a.name)} (${a.columns.map(e=>this.escapeIdentifier(e)).join(`, `)})`),n.primaryKey){let e=n.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`PRIMARY KEY (${e})`)}for(let e of n.uniqueConstraints){let t=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`CONSTRAINT ${this.escapeIdentifier(e.name)} UNIQUE (${t})`)}for(let e of n.foreignKeys)r.push(this.foreignKeyClause(e,t));let o=[`CREATE TABLE ${this.tableRef(n.name,t.destination)} (\n ${r.join(`,
98
- `)}\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`];for(let e of n.indexes)e!==a&&o.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));return o}generateDropTable(e,t){return`DROP TABLE IF EXISTS ${this.tableRef(e.tableName,t.destination)}`}generateRenameTable(e,t){return`RENAME TABLE ${this.tableRef(e.from,t.destination)} TO ${this.tableRef(e.to,t.destination)}`}renameDerivedNames(e,t,n,r){let i=[...t].map(([e,{to:t}])=>{let i=n.foreignKeys.find(t=>t.name===e);return i?`DROP FOREIGN KEY ${this.escapeIdentifier(e)}, ADD ${this.foreignKeyClause({...i,name:t},r)}`:`RENAME INDEX ${this.escapeIdentifier(e)} TO ${this.escapeIdentifier(t)}`});return[`ALTER TABLE ${this.tableRef(e,r.destination)} ${i.join(`, `)}`]}generateAddColumn(e,t){let n=this.generateColumnDef(e.column,t);return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD COLUMN ${n}`}generateDropColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`}generateAlterColumn(e,t){let{tableName:n,columnName:r,to:i}=e,a=this.tableRef(n,t.destination),o=this.generateColumnDef(i,t),s=r===i.name?`ALTER TABLE ${a} MODIFY COLUMN ${o}`:`ALTER TABLE ${a} CHANGE COLUMN ${this.escapeIdentifier(r)} ${o}`,c=this.decimalConversionBracket(e,a,t);return c===null?[s]:[c.validate,s,c.release]}decimalConversionBracket(e,r,a){let{from:o,to:s}=e,c=o.decimal,u=s.decimal;if(u===void 0||!l(o,s))return null;if(e.columnName!==s.name)throw new n(`The MySQL decimal conversion for "${e.tableName}"."${e.columnName}" also renames the column to "${s.name}". Run the rename as a separate migration step before changing the decimal descriptor; an interrupted CHECK proof must keep one stable column identity across MySQL's implicit DDL commits.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.tableName,column:e.columnName,type:`decimal-conversion-with-rename`}});let d=C(s);if(c===void 0)return(d!==`scalar`||!isMySQLExactIntegerType(o.type))&&this.refuseDecimalAdoption(e,a,d),this.decimalScalarConversionBracket(e,r,s.type,u);let f=C(o);if((d===void 0||f!==d)&&this.refuseDecimalConversion(e,a,`moves it from ${v(f)} to ${v(d)} storage, which`),d===`list`){let t=classifyDecimalListDescriptorChange(c,u);return t===`rescaling`&&this.refuseDecimalConversion(e,a,`moves its JSON list from ${i(c)} to ${i(u)}, which rescales every member and so`),t===`narrowing`&&this.refuseDecimalConversion(e,a,`narrows its JSON list from ${i(c)} to ${i(u)}, which`),this.decimalListConversionBracket(e,r,c)}return this.decimalScalarConversionBracket(e,r,s.type,u)}decimalListConversionBracket(e,t,n){let r=this.escapeIdentifier(w(`list`,n));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${r} CHECK (${u(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${r}`}}decimalScalarConversionBracket(e,t,n,r){let i=this.escapeIdentifier(w(`scalar`,r));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${i} CHECK (${_(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${i}`}}refuseDecimalAdoption(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" would adopt unmarked ${e.from.type} storage as a fixed-decimal ${v(i)}. Only INT and BIGINT have one exact descriptor-free meaning that a transient target-domain CHECK can prove. Approximate, text, native-decimal-without-descriptor, and unmarked JSON storage could already contain rounded values or members at an unknown scale. The change is refused before any statement runs, so MySQL cannot implicitly round or reinterpret the stored data. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal storage adoption`,dialect:`mysql`,target:r.destination}})}refuseDecimalConversion(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" ${i} would rewrite every stored value, and MySQL commits each DDL statement implicitly. There is no boundary that could make the member rewrite and its descriptor-marker change indivisible. The change is refused before any statement runs, so the schema and its data are unchanged. Only same-scale precision widening is applied automatically; narrowing or a scale change needs an explicit migration that validates and moves the values itself.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal descriptor conversion`,dialect:`mysql`,target:r.destination}})}generateCreateIndex(e,r){let{tableName:i,index:a}=e;if(this.validateIndexType(a.type,a.name),a.where)throw new n(`Index "${a.name}" declares a partial index predicate (where: "${a.where}"). MySQL does not support partial indexes. Either remove 'where' from the index definition, or move the predicate into a generated column and index that.`,t.FEATURE_NOT_SUPPORTED,{meta:{indexName:a.name,indexWhere:a.where}});let o=a.columns.map(e=>this.escapeIdentifier(e)).join(`, `),s=``;if(a.type===`fulltext`?s=`FULLTEXT `:a.type===`spatial`&&(s=`SPATIAL `),a.unique&&s)throw new n(`Cannot combine UNIQUE with ${a.type?.toUpperCase()} index "${a.name}". MySQL does not support UNIQUE ${a.type?.toUpperCase()} indexes. Either remove 'unique: true' from the index definition, or create a separate unique index.`,t.MIGRATION_FAILED,{meta:{indexName:a.name,indexType:a.type}});return`CREATE ${a.unique?`UNIQUE `:``}${s}INDEX ${this.escapeIdentifier(a.name)} ON ${this.tableRef(i,r.destination)} (${o})`}generateDropIndex(e,t){return`DROP INDEX ${this.escapeIdentifier(e.indexName)} ON ${this.tableRef(e.tableName,t.destination)}`}generateAddForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD ${this.foreignKeyClause(e.fk,t)}`}foreignKeyClause(e,t){let n=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `),r=e.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),i=`CONSTRAINT ${this.escapeIdentifier(e.name)} `;return i+=`FOREIGN KEY (${n}) `,i+=`REFERENCES ${this.tableRef(e.referencedTable,t.destination)} (${r})`,e.onDelete&&e.onDelete!==`noAction`&&(i+=` ON DELETE ${this.formatReferentialAction(e.onDelete)}`),e.onUpdate&&e.onUpdate!==`noAction`&&(i+=` ON UPDATE ${this.formatReferentialAction(e.onUpdate)}`),i}generateDropForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP FOREIGN KEY ${this.escapeIdentifier(e.fkName)}`}generateAddUniqueConstraint(e,t){let{tableName:n,constraint:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} UNIQUE (${i})`}generateDropUniqueConstraint(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP INDEX ${this.escapeIdentifier(e.constraintName)}`}generateAddPrimaryKey(e,t){let{tableName:n,primaryKey:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD PRIMARY KEY (${i})`}generateDropPrimaryKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP PRIMARY KEY`}generateCreateEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateDropEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateAlterEnum(e,t){let{enumName:n,newValues:r,dependentColumns:i}=e;if(!r||r.length===0)return[`-- MySQL: no new values provided for enum "${n}"`];if(!i||i.length===0)return[`-- MySQL: no dependent columns found for enum "${n}"`];let a=[],o=this.getEnumColumnType(``,``,r);a.push(...this.buildEnumReplacementUpdates(e,t));for(let e of i){let n=(t.currentSchema?.tables.find(t=>t.name===e.tableName))?.columns.find(t=>t.name===e.columnName);if(!n){a.push(`-- MySQL: column "${e.columnName}" not found in table "${e.tableName}"`);continue}let r=this.tableRef(e.tableName,t.destination),i=this.escapeIdentifier(e.columnName),s=n.nullable?``:` NOT NULL`,c=n.default===void 0?``:` DEFAULT ${n.default}`;a.push(`ALTER TABLE ${r} MODIFY COLUMN ${i} ${o}${s}${c}`)}return a}async proveNamespaceExists(e){await this.resolveCommandNamespace(e)}async resolveCommandNamespace(e){return await resolveCatalogNamespace(e,this.namespace)}generateAcquireLock(e){return mysqlAcquireLockStatement(this.requireLockScope(),30,e=>this.escapeValue(e))}generateReleaseLock(e){return mysqlReleaseLockStatement(this.requireLockScope(),e=>this.escapeValue(e))}provesLockAcquired(e){return mysqlLockAnswer(e,`acquired`)}provesLockReleased(e){return mysqlLockAnswer(e,`released`)}generateSelectTarget(){return this.namespace===void 0?null:mysqlSelectTargetStatement(this.namespace,e=>this.escapeIdentifier(e))}async proveSession(e){await proveMySQLExactValueSession(e,`database "${this.namespace??`(unbound)`}"`);let t=this.requireLockScope(),n=!1,r,i=Object.create(this);return Object.defineProperty(i,`programPreamble`,{value:async e=>{if(n)return[];if(r!==void 0)return await r,[];r=planInterruptedMySQLDecimalRecovery((t,n)=>e._executeRaw(t,n),t,e=>this.escapeIdentifier(e));try{let e=await r;return n=!0,e}catch(e){throw r=void 0,e}}}),Object.freeze(i),i}programPreamble(){return Promise.reject(new n(`This MySQL sequential migration program is not bound to its locked command's decimal-recovery scope.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-migration-command`}}))}requireLockScope(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no lock scope to name. A MySQL named lock is server-wide, and VibORM will not take one that covers every database on the instance. Supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return this.namespace}generateInventoryTables(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no table inventory to read. VibORM will not fall back to the connection's ambient default database here: a reset inventory decides what gets DROPPED. Supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return{sql:`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME`,params:[this.namespace]}}generateInventoryEnums(){return null}};export{q as t};
99
- //# sourceMappingURL=mysql-DAaUSeBw.mjs.map
97
+ `,[a,a]);admitContainedForeignKeys(d.rows,a,i);let p=O(c.rows,e=>e.TABLE_NAME),m=O(l.rows,e=>e.TABLE_NAME),h=D(u.rows,e=>e.TABLE_NAME,e=>e.INDEX_NAME),_=D(d.rows.filter(e=>e.TABLE_SCHEMA===a),e=>e.TABLE_NAME,e=>e.CONSTRAINT_NAME),v=[],y=new Set,b=[];for(let e of s.rows){let r=e.TABLE_NAME,a=[];for(let e of p.get(r)||[]){if((i===void 0||i.includes(r))&&(e.EXTRA.toUpperCase().includes(`VIRTUAL GENERATED`)||e.EXTRA.toUpperCase().includes(`STORED GENERATED`)))throw new n(`MySQL column "${r}.${e.COLUMN_NAME}" is generated. Synchronization refuses before effects because its expression cannot be represented.`,t.MIGRATION_INVALID_STATE,{meta:{table:r,column:e.COLUMN_NAME,feature:`generated column`}});if(e.DATA_TYPE===`enum`){let t=g(e.COLUMN_TYPE),n=t&&f(t);t&&n&&!y.has(n)&&(v.push({name:n,values:t}),y.add(n))}let o=i===void 0||i.includes(r),s=o?readDecimalDomain(e):void 0;a.push({name:e.COLUMN_NAME,type:o?formatColumnType(e):e.COLUMN_TYPE,nullable:e.IS_NULLABLE===`YES`,default:o?cleanDefault(e):void 0,autoIncrement:isAutoIncrement(e.EXTRA),decimal:s})}let o,s=m.get(r);if(s&&s.length>0){s.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let e=s[0];e&&(o={columns:s.map(e=>e.COLUMN_NAME),name:e.CONSTRAINT_NAME})}let c=[],l=h.get(r),u=new Set(_.get(r)?.keys()??[]);if(l)for(let[e,t]of l){if(u.has(e))continue;t.sort((e,t)=>e.SEQ_IN_INDEX-t.SEQ_IN_INDEX);let n=t[0];if(n){let r=n.INDEX_TYPE.toLowerCase(),i=r===`rtree`?`spatial`:r;c.push({name:e,columns:t.map(e=>e.COLUMN_NAME),unique:n.NON_UNIQUE===0,type:i===`btree`||i===`hash`||i===`fulltext`||i===`spatial`?i:void 0})}}let d=[],x=_.get(r);if(x)for(let[e,t]of x){t.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let n=t[0];n&&d.push({name:e,columns:t.map(e=>e.COLUMN_NAME),referencedTable:n.REFERENCED_TABLE_NAME,referencedColumns:t.map(e=>e.REFERENCED_COLUMN_NAME),onDelete:k(n.DELETE_RULE),onUpdate:k(n.UPDATE_RULE)})}b.push({name:r,columns:a,primaryKey:o,indexes:c,foreignKeys:d,uniqueConstraints:[]})}return{tables:b,enums:v.length>0?v:void 0}}const R=/[^a-z0-9_]/g;function hashLockScope(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function mysqlMigrationLockName(e){let t=e.toLowerCase();return`viborm_migration_${t.replace(R,`_`).slice(0,38)}_${hashLockScope(t)}`}function mysqlAcquireLockStatement(e,t,n){return`SELECT GET_LOCK(${n(mysqlMigrationLockName(e))}, ${t}) AS acquired`}function mysqlReleaseLockStatement(e,t){return`SELECT RELEASE_LOCK(${t(mysqlMigrationLockName(e))}) AS released`}function mysqlLockAnswer(e,t){if(e.length!==1)return!1;let n=e[0];if(typeof n!=`object`||!n)return!1;let r=Reflect.get(n,t);return typeof r==`number`?r===1:typeof r==`string`?Number(r)===1:!1}function mysqlSelectTargetStatement(e,t){return`USE ${t(e)}`}const z=/^(\d+)\.(\d+)\.(\d+)/;async function proveMySQLExactValueSession(e,r){let{rows:i}=await e(`SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS server_version`),a=i[0],o=typeof a==`object`&&a?Reflect.get(a,`sql_mode`):void 0,s=typeof o==`string`?o:``,c=typeof a==`object`&&a?Reflect.get(a,`server_version`):void 0,l=typeof c==`string`?c:`<unreported>`;if(!supportsEnforcedMySQLChecks(l))throw new n(`This MySQL migration session reports version "${l}". Fixed-decimal conversions require MySQL 8.0.16 or later, where CHECK constraints are enforced; the command is refused before any migration effect.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`unenforced-check-constraints`,target:r}});if(!s.split(`,`).some(e=>{let t=e.trim();return t===`STRICT_TRANS_TABLES`||t===`STRICT_ALL_TABLES`}))throw new n(`This MySQL session runs in sql_mode "${s}", which has neither STRICT_TRANS_TABLES nor STRICT_ALL_TABLES. Effectful migration work is refused: without a strict mode MySQL answers an out-of-range DECIMAL with a warning and stores the clamped value, so an exact fixed-decimal column would silently stop holding what it was given. Enable a strict mode on the server or on this connection and run the command again.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`non-strict-sql-mode`,target:r}})}function supportsEnforcedMySQLChecks(e){if(e.toLowerCase().includes(`mariadb`))return!1;let t=z.exec(e);if(t===null)return!1;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]);return n>8||n===8&&(r>0||i>=16)}const B=[/^GEOMETRY\b/,/^POINT\b/,/^LINESTRING\b/,/^POLYGON\b/,/^MULTIPOINT\b/,/^MULTILINESTRING\b/,/^MULTIPOLYGON\b/,/^GEOMETRYCOLLECTION\b/],V=/^(?:(?:TINY|MEDIUM|LONG)?(?:TEXT|BLOB)|JSON|GEOMETRY|POINT|LINESTRING|POLYGON|MULTI(?:POINT|LINESTRING|POLYGON)|GEOMETRYCOLLECTION)\b/i,H=/[\s(]/;function classifyDecimalListDescriptorChange(e,t){return e.scale===t.scale?e.precision<t.precision?`widening`:e.precision>t.precision?`narrowing`:`same`:`rescaling`}const U=x.point.indexOf(` `),W=x.point.slice(0,U),G=x.point.slice(U+1);function mysqlRefusesLiteralDefault(e){let t=e.toUpperCase();return t.includes(`TEXT`)||t.includes(`BLOB`)||t.includes(`JSON`)||B.some(e=>e.test(t))}const K=/^(?:DATETIME|TIMESTAMP)\s*(?:\((\d+)\))?$/i;function mysqlNowExpression(e){let t=K.exec(e.trim());if(t!==null)return t[1]===void 0?`CURRENT_TIMESTAMP`:`CURRENT_TIMESTAMP(${t[1]})`}function finalizeMySQLColumn(e,t){let n=e.type.toUpperCase()===`TEXT`&&t?`VARCHAR(191)`:e.type,r=e.default!==void 0&&mysqlRefusesLiteralDefault(n)?`(${e.default})`:e.default;return n===e.type&&r===e.default?e:{...e,type:n,default:r}}function isMySQLExactIntegerType(e){let t=e.trim().toUpperCase().split(H,1)[0];return t===`INT`||t===`INTEGER`||t===`BIGINT`}const q=new class MySQLMigrationDriver extends S{dialect=`mysql`;driverName=`mysql`;capabilities={supportsNativeEnums:!0,supportsAddEnumValueInTransaction:!1,supportsIndexTypes:[`btree`,`fulltext`,`spatial`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!0,introspectionReadsConstraintNames:!0};getIrreversibleRollbackReason(e){if(e.type!==`alterColumn`)return;let t=e.from.decimal,n=e.to.decimal;if(!(t===void 0||n===void 0||C(e.from)!==`list`||C(e.to)!==`list`||classifyDecimalListDescriptorChange(t,n)!==`narrowing`))return`MySQL cannot automatically roll back the decimal-list widening of "${e.tableName}"."${e.columnName}": the inverse narrows ${r(t)} to ${r(n)}, and its implicit DDL commits cannot make the stricter proof, descriptor-marker change, and cleanup indivisible.`}async preflightSchemaRequirements(e,r){let i=new Set(e.flatMap(e=>e.tables.map(e=>e.name)));if(i.size===0)return!1;let a=await resolveCatalogNamespace(r,this.namespace),o=(await r(`SELECT TABLE_NAME FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ?`,[a])).rows.find(e=>i.has(e.TABLE_NAME));if(o)throw new n(`MySQL relation "${o.TABLE_NAME}" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,t.MIGRATION_INVALID_STATE,{meta:{table:o.TABLE_NAME,feature:`view`,namespace:a}});return!1}introspect(e){return introspect(e,this.namespace,this.target?.tables)}escapeValue(e){return e==null?`NULL`:m(String(e))}escapeIdentifier(e){if(e==null)throw new n(`Cannot escape null or undefined identifier`,t.INVALID_INPUT);return`\`${String(e).replace(/`/g,"``")}\``}tableRef(e,t){return E(e=>this.escapeIdentifier(e),t===`live`?this.namespace:void 0,e)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0||t.array===!0?void 0:o(n,r,`mysql`);if(i)return i.columnType;let s=a(r,`mysql`);return s&&!t.array?s.type:h({type:t.type,array:t.array,decimal:t.decimal})}getDefaultExpression(e,t){let n=t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate?this.literalDefaultValue(t):void 0;if(t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate&&typeof n==`string`)return this.escapeValue(s(n));if(!(t.hasDefault&&t.default===null))return t.autoGenerate?.kind===`now`?mysqlNowExpression(this.mapScalarType(e,t)):super.getDefaultExpression(e,t)}finalizeTable(e){let r=new Set([...e.primaryKey?.columns??[],...e.uniqueConstraints.flatMap(e=>e.columns),...e.indexes.flatMap(e=>e.columns),...e.foreignKeys.flatMap(e=>e.columns)]),i=new Set(e.indexes.map(e=>e.name)),a=e.uniqueConstraints.filter(e=>!i.has(e.name)).map(e=>({name:e.name,columns:e.columns,unique:!0})),o={...e,primaryKey:e.primaryKey?{...e.primaryKey,name:`PRIMARY`}:void 0,columns:e.columns.map(e=>finalizeMySQLColumn(e,r.has(e.name))),indexes:[...e.indexes,...a],uniqueConstraints:[]},s=o.indexes.filter(e=>!e.type||e.type===`btree`),c=[{name:`PRIMARY`,columns:o.primaryKey?.columns??[]},...s.map(e=>({name:e.name,columns:e.columns})),...o.foreignKeys.map(e=>({name:e.name,columns:e.columns}))];for(let{name:r,columns:i}of c)for(let a of i){let i=o.columns.find(e=>e.name===a);if(i&&V.test(i.type))throw new n(`MySQL key "${e.name}.${r}" cannot directly index ${i.type} column "${i.name}". Use an indexable native type such as VARCHAR, or manage a reviewed prefix/expression index outside this declaration.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.name,column:i.name}})}let l=o.columns.filter(e=>e.autoIncrement);if(l.length>1||l.some(e=>o.primaryKey?.columns[0]!==e.name&&!s.some(t=>t.columns[0]===e.name&&!t.where)&&!o.foreignKeys.some(t=>t.columns[0]===e.name)))throw new n(`MySQL table "${e.name}" requires at most one AUTO_INCREMENT column, first in an ordinary key. Declare its primary key or leading index explicitly.`,t.INVALID_INPUT,{meta:{table:e.name}});return o}formatBooleanDefault(e){return e?`1`:`0`}getEnumColumnType(e,t,n){return f(n)}static AUTO_INCREMENT_TYPES=new Set([`tinyint`,`smallint`,`mediumint`,`int`,`integer`,`bigint`]);validateAutoIncrementType(e){let r=e.type.toLowerCase().split(H)[0];if(!MySQLMigrationDriver.AUTO_INCREMENT_TYPES.has(r))throw new n(`MySQL AUTO_INCREMENT requires an integer type (TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT). Column "${e.name}" has type "${e.type}" which is not compatible with AUTO_INCREMENT.`,t.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}})}generateColumnDef(e,t){let n=[this.escapeIdentifier(e.name)],r=e.type.toUpperCase()===x.point;return e.autoIncrement?(this.validateAutoIncrementType(e),n.push(e.type),n.push(`AUTO_INCREMENT`)):n.push(r?W:e.type),e.nullable||n.push(`NOT NULL`),r&&n.push(G),e.default!==void 0&&!e.autoIncrement&&n.push(`DEFAULT ${e.default}`),e.decimal&&C(e)===`list`&&n.push(`COMMENT ${this.escapeValue(p(e.decimal))}`),n.join(` `)}generateCreateTable(e,t){let{table:n}=e,r=n.columns.map(e=>this.generateColumnDef(e,t)),i=n.columns.find(e=>e.autoIncrement),a=i&&n.primaryKey?.columns[0]!==i.name?n.indexes.find(e=>(!e.type||e.type===`btree`)&&!e.where&&e.columns[0]===i.name):void 0;if(a&&r.push(`${a.unique?`UNIQUE `:``}KEY ${this.escapeIdentifier(a.name)} (${a.columns.map(e=>this.escapeIdentifier(e)).join(`, `)})`),n.primaryKey){let e=n.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`PRIMARY KEY (${e})`)}for(let e of n.uniqueConstraints){let t=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`CONSTRAINT ${this.escapeIdentifier(e.name)} UNIQUE (${t})`)}for(let e of n.foreignKeys)r.push(this.foreignKeyClause(e,t));let o=[`CREATE TABLE ${this.tableRef(n.name,t.destination)} (\n ${r.join(`,
98
+ `)}\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`];for(let e of n.indexes)e!==a&&o.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));return o}generateDropTable(e,t){return`DROP TABLE IF EXISTS ${this.tableRef(e.tableName,t.destination)}`}generateRenameTable(e,t){return`RENAME TABLE ${this.tableRef(e.from,t.destination)} TO ${this.tableRef(e.to,t.destination)}`}renameDerivedNames(e,t,n,r){let i=[...t].map(([e,{to:t}])=>{let i=n.foreignKeys.find(t=>t.name===e);return i?`DROP FOREIGN KEY ${this.escapeIdentifier(e)}, ADD ${this.foreignKeyClause({...i,name:t},r)}`:`RENAME INDEX ${this.escapeIdentifier(e)} TO ${this.escapeIdentifier(t)}`});return[`ALTER TABLE ${this.tableRef(e,r.destination)} ${i.join(`, `)}`]}generateAddColumn(e,t){let n=this.generateColumnDef(e.column,t);return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD COLUMN ${n}`}generateDropColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`}generateAlterColumn(e,t){let{tableName:n,columnName:r,to:i}=e,a=this.tableRef(n,t.destination),o=this.generateColumnDef(i,t),s=r===i.name?`ALTER TABLE ${a} MODIFY COLUMN ${o}`:`ALTER TABLE ${a} CHANGE COLUMN ${this.escapeIdentifier(r)} ${o}`,c=this.decimalConversionBracket(e,a,t);return c===null?[s]:[c.validate,s,c.release]}decimalConversionBracket(e,i,a){let{from:o,to:s}=e,c=o.decimal,u=s.decimal;if(u===void 0||!l(o,s))return null;if(e.columnName!==s.name)throw new n(`The MySQL decimal conversion for "${e.tableName}"."${e.columnName}" also renames the column to "${s.name}". Run the rename as a separate migration step before changing the decimal descriptor; an interrupted CHECK proof must keep one stable column identity across MySQL's implicit DDL commits.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.tableName,column:e.columnName,type:`decimal-conversion-with-rename`}});let d=C(s);if(c===void 0)return(d!==`scalar`||!isMySQLExactIntegerType(o.type))&&this.refuseDecimalAdoption(e,a,d),this.decimalScalarConversionBracket(e,i,s.type,u);let f=C(o);if((d===void 0||f!==d)&&this.refuseDecimalConversion(e,a,`moves it from ${v(f)} to ${v(d)} storage, which`),d===`list`){let t=classifyDecimalListDescriptorChange(c,u);return t===`rescaling`&&this.refuseDecimalConversion(e,a,`moves its JSON list from ${r(c)} to ${r(u)}, which rescales every member and so`),t===`narrowing`&&this.refuseDecimalConversion(e,a,`narrows its JSON list from ${r(c)} to ${r(u)}, which`),this.decimalListConversionBracket(e,i,c)}return this.decimalScalarConversionBracket(e,i,s.type,u)}decimalListConversionBracket(e,t,n){let r=this.escapeIdentifier(w(`list`,n));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${r} CHECK (${u(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${r}`}}decimalScalarConversionBracket(e,t,n,r){let i=this.escapeIdentifier(w(`scalar`,r));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${i} CHECK (${_(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${i}`}}refuseDecimalAdoption(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" would adopt unmarked ${e.from.type} storage as a fixed-decimal ${v(i)}. Only INT and BIGINT have one exact descriptor-free meaning that a transient target-domain CHECK can prove. Approximate, text, native-decimal-without-descriptor, and unmarked JSON storage could already contain rounded values or members at an unknown scale. The change is refused before any statement runs, so MySQL cannot implicitly round or reinterpret the stored data. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal storage adoption`,dialect:`mysql`,target:r.destination}})}refuseDecimalConversion(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" ${i} would rewrite every stored value, and MySQL commits each DDL statement implicitly. There is no boundary that could make the member rewrite and its descriptor-marker change indivisible. The change is refused before any statement runs, so the schema and its data are unchanged. Only same-scale precision widening is applied automatically; narrowing or a scale change needs an explicit migration that validates and moves the values itself.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal descriptor conversion`,dialect:`mysql`,target:r.destination}})}generateCreateIndex(e,r){let{tableName:i,index:a}=e;if(this.validateIndexType(a.type,a.name),a.where)throw new n(`Index "${a.name}" declares a partial index predicate (where: "${a.where}"). MySQL does not support partial indexes. Either remove 'where' from the index definition, or move the predicate into a generated column and index that.`,t.FEATURE_NOT_SUPPORTED,{meta:{indexName:a.name,indexWhere:a.where}});let o=a.columns.map(e=>this.escapeIdentifier(e)).join(`, `),s=``;if(a.type===`fulltext`?s=`FULLTEXT `:a.type===`spatial`&&(s=`SPATIAL `),a.unique&&s)throw new n(`Cannot combine UNIQUE with ${a.type?.toUpperCase()} index "${a.name}". MySQL does not support UNIQUE ${a.type?.toUpperCase()} indexes. Either remove 'unique: true' from the index definition, or create a separate unique index.`,t.MIGRATION_FAILED,{meta:{indexName:a.name,indexType:a.type}});return`CREATE ${a.unique?`UNIQUE `:``}${s}INDEX ${this.escapeIdentifier(a.name)} ON ${this.tableRef(i,r.destination)} (${o})`}generateDropIndex(e,t){return`DROP INDEX ${this.escapeIdentifier(e.indexName)} ON ${this.tableRef(e.tableName,t.destination)}`}generateAddForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD ${this.foreignKeyClause(e.fk,t)}`}foreignKeyClause(e,t){let n=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `),r=e.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),i=`CONSTRAINT ${this.escapeIdentifier(e.name)} `;return i+=`FOREIGN KEY (${n}) `,i+=`REFERENCES ${this.tableRef(e.referencedTable,t.destination)} (${r})`,e.onDelete&&e.onDelete!==`noAction`&&(i+=` ON DELETE ${this.formatReferentialAction(e.onDelete)}`),e.onUpdate&&e.onUpdate!==`noAction`&&(i+=` ON UPDATE ${this.formatReferentialAction(e.onUpdate)}`),i}generateDropForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP FOREIGN KEY ${this.escapeIdentifier(e.fkName)}`}generateAddUniqueConstraint(e,t){let{tableName:n,constraint:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} UNIQUE (${i})`}generateDropUniqueConstraint(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP INDEX ${this.escapeIdentifier(e.constraintName)}`}generateAddPrimaryKey(e,t){let{tableName:n,primaryKey:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD PRIMARY KEY (${i})`}generateDropPrimaryKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP PRIMARY KEY`}generateCreateEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateDropEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateAlterEnum(e,t){let{enumName:n,newValues:r,dependentColumns:i}=e;if(!r||r.length===0)return[`-- MySQL: no new values provided for enum "${n}"`];if(!i||i.length===0)return[`-- MySQL: no dependent columns found for enum "${n}"`];let a=[],o=this.getEnumColumnType(``,``,r);a.push(...this.buildEnumReplacementUpdates(e,t));for(let e of i){let n=(t.currentSchema?.tables.find(t=>t.name===e.tableName))?.columns.find(t=>t.name===e.columnName);if(!n){a.push(`-- MySQL: column "${e.columnName}" not found in table "${e.tableName}"`);continue}let r=this.tableRef(e.tableName,t.destination),i=this.escapeIdentifier(e.columnName),s=n.nullable?``:` NOT NULL`,c=n.default===void 0?``:` DEFAULT ${n.default}`;a.push(`ALTER TABLE ${r} MODIFY COLUMN ${i} ${o}${s}${c}`)}return a}async proveNamespaceExists(e){await this.resolveCommandNamespace(e)}async resolveCommandNamespace(e){return await resolveCatalogNamespace(e,this.namespace)}generateAcquireLock(e){return mysqlAcquireLockStatement(this.requireLockScope(),30,e=>this.escapeValue(e))}generateReleaseLock(e){return mysqlReleaseLockStatement(this.requireLockScope(),e=>this.escapeValue(e))}provesLockAcquired(e){return mysqlLockAnswer(e,`acquired`)}provesLockReleased(e){return mysqlLockAnswer(e,`released`)}generateSelectTarget(){return this.namespace===void 0?null:mysqlSelectTargetStatement(this.namespace,e=>this.escapeIdentifier(e))}async proveSession(e){await proveMySQLExactValueSession(e,`database "${this.namespace??`(unbound)`}"`);let t=this.requireLockScope(),n=!1,r,i=Object.create(this);return Object.defineProperty(i,`programPreamble`,{value:async e=>{if(n)return[];if(r!==void 0)return await r,[];r=planInterruptedMySQLDecimalRecovery((t,n)=>e._executeRaw(t,n),t,e=>this.escapeIdentifier(e));try{let e=await r;return n=!0,e}catch(e){throw r=void 0,e}}}),Object.freeze(i),i}programPreamble(){return Promise.reject(new n(`This MySQL sequential migration program is not bound to its locked command's decimal-recovery scope.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-migration-command`}}))}requireLockScope(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no lock scope to name. A MySQL named lock is server-wide, and VibORM will not take one that covers every database on the instance. Supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return this.namespace}generateInventoryTables(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no table inventory to read. VibORM will not fall back to the connection's ambient default database here: a reset inventory decides what gets DROPPED. Supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return{sql:`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME`,params:[this.namespace]}}generateInventoryEnums(){return null}};export{q as t};
99
+ //# sourceMappingURL=mysql-hoo290Dd.mjs.map