viborm 1.16.0 → 1.17.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 (403) hide show
  1. package/dist/adapter-internals-Dz2nNEF5.mjs +2 -0
  2. package/dist/adapter-internals-Dz2nNEF5.mjs.map +1 -0
  3. package/dist/adapter-namespace-C1SUkH2U.mjs +2 -0
  4. package/dist/{adapter-namespace-DwFnfpED.mjs.map → adapter-namespace-C1SUkH2U.mjs.map} +1 -1
  5. package/dist/adapters.d.mts +50 -94
  6. package/dist/adapters.mjs +1 -1
  7. package/dist/{args-7WgBFd_f.mjs → args-DsGRkPRw.mjs} +2 -2
  8. package/dist/{args-7WgBFd_f.mjs.map → args-DsGRkPRw.mjs.map} +1 -1
  9. package/dist/{array-literal-BOzj0E2u.mjs → array-literal-U6SeastY.mjs} +1 -1
  10. package/dist/{array-literal-BOzj0E2u.mjs.map → array-literal-U6SeastY.mjs.map} +1 -1
  11. package/dist/auto-names-GpcDfhaw.mjs +2 -0
  12. package/dist/auto-names-GpcDfhaw.mjs.map +1 -0
  13. package/dist/batch-refs-BuICt2tu.mjs +2 -0
  14. package/dist/{batch-refs-Bd8HvwUc.mjs.map → batch-refs-BuICt2tu.mjs.map} +1 -1
  15. package/dist/better-auth.d.mts +1 -1
  16. package/dist/better-auth.mjs +2 -2
  17. package/dist/bun-sql.d.mts +1 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sqlite.d.mts +1 -1
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/cache/cloudflare-kv.d.mts +1 -1
  22. package/dist/cache/cloudflare-kv.mjs +1 -1
  23. package/dist/cache/memory.d.mts +1 -1
  24. package/dist/cache/memory.mjs +1 -1
  25. package/dist/cache.d.mts +2 -2
  26. package/dist/cache.mjs +1 -1
  27. package/dist/call-D2E7dPCd.mjs +2 -0
  28. package/dist/{call-0bd_B9Vp.mjs.map → call-D2E7dPCd.mjs.map} +1 -1
  29. package/dist/cli.mjs +6 -6
  30. package/dist/cli.mjs.map +1 -1
  31. package/dist/client-Cq_VcF43.d.mts +183 -0
  32. package/dist/client-DkNRAOuH.mjs +2 -0
  33. package/dist/client-DkNRAOuH.mjs.map +1 -0
  34. package/dist/{planner-C-zjj19U.d.mts → client-driver-DuQy6lsN.d.mts} +3 -3
  35. package/dist/client-rIiFOn1W.mjs +9 -0
  36. package/dist/client-rIiFOn1W.mjs.map +1 -0
  37. package/dist/client.d.mts +2 -2
  38. package/dist/client.mjs +1 -1
  39. package/dist/config.d.mts +2 -2
  40. package/dist/config.mjs +1 -1
  41. package/dist/{confine-CyI9IwjC.mjs → confine-FIfjlAHp.mjs} +2 -2
  42. package/dist/{confine-CyI9IwjC.mjs.map → confine-FIfjlAHp.mjs.map} +1 -1
  43. package/dist/{object-store-C4qmW7xf.d.mts → conformance-C1JveA8y.d.mts} +5 -60
  44. package/dist/conformance-C4JYA0JG.mjs +2 -0
  45. package/dist/conformance-C4JYA0JG.mjs.map +1 -0
  46. package/dist/contract-BBone8RD.mjs +2 -0
  47. package/dist/contract-BBone8RD.mjs.map +1 -0
  48. package/dist/coordination-BxMskOgi.mjs +1 -1
  49. package/dist/d1.d.mts +1 -1
  50. package/dist/d1.mjs +1 -1
  51. package/dist/{database-adapter-BMjJiBFm.d.mts → database-adapter-cW0nmWM6.d.mts} +1 -1
  52. package/dist/datetime-physical-codec-Ci0dyOot.mjs +2 -0
  53. package/dist/datetime-physical-codec-Ci0dyOot.mjs.map +1 -0
  54. package/dist/datetime-values-D_G6m5_o.mjs +2 -0
  55. package/dist/datetime-values-D_G6m5_o.mjs.map +1 -0
  56. package/dist/decimal-D4DRlT2y.mjs +2 -0
  57. package/dist/decimal-D4DRlT2y.mjs.map +1 -0
  58. package/dist/{defaults-DAPb-tJ4.mjs → defaults-BrXUK350.mjs} +2 -2
  59. package/dist/{defaults-DAPb-tJ4.mjs.map → defaults-BrXUK350.mjs.map} +1 -1
  60. package/dist/{document-CHaVF7Vn.d.mts → document-B8ClXlb7.d.mts} +1 -1
  61. package/dist/{driver-kiIQS_Fd.mjs → driver-BOsmU3kz.mjs} +2 -2
  62. package/dist/{driver-kiIQS_Fd.mjs.map → driver-BOsmU3kz.mjs.map} +1 -1
  63. package/dist/{driver-BvTixv-m.d.mts → driver-KgGMnfz8.d.mts} +1 -1
  64. package/dist/{driver-lShUkDmf.mjs → driver-PkP_1p80.mjs} +2 -2
  65. package/dist/{driver-lShUkDmf.mjs.map → driver-PkP_1p80.mjs.map} +1 -1
  66. package/dist/{driver-diagnostics-aQ54bArn.mjs → driver-diagnostics-sSpge6kv.mjs} +1 -1
  67. package/dist/{driver-diagnostics-aQ54bArn.mjs.map → driver-diagnostics-sSpge6kv.mjs.map} +1 -1
  68. package/dist/driver.d.mts +1 -1
  69. package/dist/driver.mjs +1 -1
  70. package/dist/durable-object.d.mts +1 -1
  71. package/dist/durable-object.mjs +2 -2
  72. package/dist/error-mapping-B9rSvgG9.mjs +1 -1
  73. package/dist/every-tAZuZ50K.mjs +2 -0
  74. package/dist/{every-JpbiHdMb.mjs.map → every-tAZuZ50K.mjs.map} +1 -1
  75. package/dist/execution-context-couU2tgh.mjs +1 -1
  76. package/dist/{exports-DYnTfvQo.d.mts → exports-reE3GioL.d.mts} +1 -1
  77. package/dist/extension-Bf4vO5mp.mjs +2 -0
  78. package/dist/extension-Bf4vO5mp.mjs.map +1 -0
  79. package/dist/facts-Bjnzv3j-.mjs +2 -0
  80. package/dist/facts-Bjnzv3j-.mjs.map +1 -0
  81. package/dist/{fs-estate-n-QpsFqb.mjs → fs-estate-C3ahNKmi.mjs} +2 -2
  82. package/dist/{fs-estate-n-QpsFqb.mjs.map → fs-estate-C3ahNKmi.mjs.map} +1 -1
  83. package/dist/geo-area-codec-CBdiCOzj.mjs +2 -0
  84. package/dist/{geo-area-codec-Bti2PA2i.mjs.map → geo-area-codec-CBdiCOzj.mjs.map} +1 -1
  85. package/dist/geo-point-DCV0eO1p.mjs +2 -0
  86. package/dist/geo-point-DCV0eO1p.mjs.map +1 -0
  87. package/dist/id-domain-Cj6MnMxg.mjs +2 -0
  88. package/dist/{id-domain-Cg65TLZ-.mjs.map → id-domain-Cj6MnMxg.mjs.map} +1 -1
  89. package/dist/identifier-BdLx66pi.mjs +2 -0
  90. package/dist/identifier-BdLx66pi.mjs.map +1 -0
  91. package/dist/identifier-conversion-CMKVatU4.mjs +3 -0
  92. package/dist/identifier-conversion-CMKVatU4.mjs.map +1 -0
  93. package/dist/{identifiers-BxOf57qy.mjs → identifiers-BAZ_S6Lk.mjs} +1 -1
  94. package/dist/{identifiers-BxOf57qy.mjs.map → identifiers-BAZ_S6Lk.mjs.map} +1 -1
  95. package/dist/{identity-CJlRQA-m.mjs → identity-nPArhpsD.mjs} +2 -2
  96. package/dist/{identity-CJlRQA-m.mjs.map → identity-nPArhpsD.mjs.map} +1 -1
  97. package/dist/index.d.mts +2 -2
  98. package/dist/index.mjs +1 -1
  99. package/dist/index.mjs.map +1 -1
  100. package/dist/instrumentation.d.mts +1 -1
  101. package/dist/instrumentation.mjs +1 -1
  102. package/dist/introspect-dyBpdr2L.mjs +2 -0
  103. package/dist/{introspect-q3Rf_Xv8.mjs.map → introspect-dyBpdr2L.mjs.map} +1 -1
  104. package/dist/json-DvvrTWUw.mjs +2 -0
  105. package/dist/{json-CsAdz9pg.mjs.map → json-DvvrTWUw.mjs.map} +1 -1
  106. package/dist/{json-number-C09rsm1g.mjs → json-number-Guh-5rff.mjs} +1 -1
  107. package/dist/{json-number-C09rsm1g.mjs.map → json-number-Guh-5rff.mjs.map} +1 -1
  108. package/dist/{json-parameter-D7hDrVKw.mjs → json-parameter-DtHhEfyE.mjs} +1 -1
  109. package/dist/{json-parameter-D7hDrVKw.mjs.map → json-parameter-DtHhEfyE.mjs.map} +1 -1
  110. package/dist/judge-words-CqNdnbou.mjs +2 -0
  111. package/dist/judge-words-CqNdnbou.mjs.map +1 -0
  112. package/dist/{key-BDH6oTyC.mjs → key-v4k7Cqb6.mjs} +2 -2
  113. package/dist/{key-BDH6oTyC.mjs.map → key-v4k7Cqb6.mjs.map} +1 -1
  114. package/dist/{keys-CIal55WQ.mjs → keys-BLWaO_YM.mjs} +1 -1
  115. package/dist/{keys-CIal55WQ.mjs.map → keys-BLWaO_YM.mjs.map} +1 -1
  116. package/dist/keys-o4Pl6Vsg.mjs +2 -0
  117. package/dist/{keys-DZdKAd4n.mjs.map → keys-o4Pl6Vsg.mjs.map} +1 -1
  118. package/dist/libsql-C0iMZifz.mjs +3 -0
  119. package/dist/libsql-C0iMZifz.mjs.map +1 -0
  120. package/dist/libsql.d.mts +1 -1
  121. package/dist/libsql.mjs +1 -1
  122. package/dist/light-reLULeHN.mjs +2 -0
  123. package/dist/{light-D2wNSbzY.mjs.map → light-reLULeHN.mjs.map} +1 -1
  124. package/dist/memory-DtTuFo-h.mjs +2 -0
  125. package/dist/memory-DtTuFo-h.mjs.map +1 -0
  126. package/dist/methods-part-Dsi0DBNU.mjs +2 -0
  127. package/dist/{methods-part-BaNx3o7b.mjs.map → methods-part-Dsi0DBNU.mjs.map} +1 -1
  128. package/dist/migrations/mysql/runtime.d.mts +7 -0
  129. package/dist/migrations/mysql/runtime.mjs +2 -0
  130. package/dist/migrations/mysql/runtime.mjs.map +1 -0
  131. package/dist/migrations/mysql.d.mts +7 -5
  132. package/dist/migrations/mysql.mjs +1 -1
  133. package/dist/migrations/mysql.mjs.map +1 -1
  134. package/dist/migrations/postgres/runtime.d.mts +7 -0
  135. package/dist/migrations/postgres/runtime.mjs +2 -0
  136. package/dist/migrations/postgres/runtime.mjs.map +1 -0
  137. package/dist/migrations/postgres.d.mts +7 -5
  138. package/dist/migrations/postgres.mjs +1 -1
  139. package/dist/migrations/postgres.mjs.map +1 -1
  140. package/dist/migrations/snowflake.d.mts +7 -5
  141. package/dist/migrations/snowflake.mjs +1 -1
  142. package/dist/migrations/snowflake.mjs.map +1 -1
  143. package/dist/migrations/sqlite/runtime.d.mts +7 -0
  144. package/dist/migrations/sqlite/runtime.mjs +2 -0
  145. package/dist/migrations/sqlite/runtime.mjs.map +1 -0
  146. package/dist/migrations/sqlite.d.mts +7 -5
  147. package/dist/migrations/sqlite.mjs +1 -1
  148. package/dist/migrations/sqlite.mjs.map +1 -1
  149. package/dist/migrations/storage/durable-object.d.mts +1 -1
  150. package/dist/migrations/storage/durable-object.mjs +1 -1
  151. package/dist/migrations/storage/fs.d.mts +1 -1
  152. package/dist/migrations/storage/fs.mjs +1 -1
  153. package/dist/migrations/storage/r2.d.mts +1 -1
  154. package/dist/migrations/storage/r2.mjs +1 -1
  155. package/dist/migrations/surrealdb.d.mts +7 -5
  156. package/dist/migrations/surrealdb.mjs +1 -1
  157. package/dist/migrations/surrealdb.mjs.map +1 -1
  158. package/dist/migrations/tenant.d.mts +4 -3
  159. package/dist/migrations/tenant.mjs +1 -1
  160. package/dist/migrations/tenant.mjs.map +1 -1
  161. package/dist/migrations.d.mts +7 -5
  162. package/dist/migrations.mjs +1 -1
  163. package/dist/migrations.mjs.map +1 -1
  164. package/dist/model-ByktcCGW.mjs +2 -0
  165. package/dist/model-ByktcCGW.mjs.map +1 -0
  166. package/dist/mysql-DPYi1p_g.mjs +4 -0
  167. package/dist/mysql-DPYi1p_g.mjs.map +1 -0
  168. package/dist/mysql-adapter-6gVm5PHp.mjs +2 -0
  169. package/dist/{mysql-adapter-BFWYPoM0.mjs.map → mysql-adapter-6gVm5PHp.mjs.map} +1 -1
  170. package/dist/mysql2.d.mts +1 -1
  171. package/dist/mysql2.mjs +1 -1
  172. package/dist/{named-statements-CkOOD__I.mjs → named-statements-CswIc5m1.mjs} +2 -2
  173. package/dist/{named-statements-CkOOD__I.mjs.map → named-statements-CswIc5m1.mjs.map} +1 -1
  174. package/dist/native-types-BUkcVedc.mjs +2 -0
  175. package/dist/native-types-BUkcVedc.mjs.map +1 -0
  176. package/dist/neon-http.d.mts +1 -1
  177. package/dist/neon-http.mjs +1 -1
  178. package/dist/normalized-result-D7nVkF36.mjs +1 -1
  179. package/dist/{object-store-Chq1PMYz.mjs → object-store-DnrLNxz_.mjs} +2 -2
  180. package/dist/{object-store-Chq1PMYz.mjs.map → object-store-DnrLNxz_.mjs.map} +1 -1
  181. package/dist/object-store-j4kgh61D.d.mts +59 -0
  182. package/dist/{on-ZkOVmE4-.mjs → on-nOenqmgP.mjs} +2 -2
  183. package/dist/{on-ZkOVmE4-.mjs.map → on-nOenqmgP.mjs.map} +1 -1
  184. package/dist/on.d.mts +1 -1
  185. package/dist/on.mjs +1 -1
  186. package/dist/ordering/keys.mjs +1 -1
  187. package/dist/ordering.d.mts +1 -1
  188. package/dist/ordering.mjs +2 -2
  189. package/dist/pending-operation-B5o-zhES.mjs +2 -0
  190. package/dist/{pending-operation-D4gUKMxD.mjs.map → pending-operation-B5o-zhES.mjs.map} +1 -1
  191. package/dist/permissions.d.mts +1 -1
  192. package/dist/permissions.mjs +1 -1
  193. package/dist/pg.d.mts +2 -2
  194. package/dist/pg.mjs +1 -1
  195. package/dist/pglite.d.mts +1 -1
  196. package/dist/pglite.mjs +1 -1
  197. package/dist/{physical-DO4PEYcc.mjs → physical-BheMRPY0.mjs} +2 -2
  198. package/dist/{physical-DO4PEYcc.mjs.map → physical-BheMRPY0.mjs.map} +1 -1
  199. package/dist/{pinned-session-Y7-2pRBJ.mjs → pinned-session-eNyd0dkT.mjs} +2 -2
  200. package/dist/{pinned-session-Y7-2pRBJ.mjs.map → pinned-session-eNyd0dkT.mjs.map} +1 -1
  201. package/dist/planetscale.d.mts +1 -1
  202. package/dist/planetscale.mjs +1 -1
  203. package/dist/postgres-CEGFOi8D.mjs +27 -0
  204. package/dist/postgres-CEGFOi8D.mjs.map +1 -0
  205. package/dist/postgres-adapter-B-im38AE.mjs +2 -0
  206. package/dist/postgres-adapter-B-im38AE.mjs.map +1 -0
  207. package/dist/{postgres-adapter-BpLizOaK.mjs → postgres-adapter-OoqoBdhb.mjs} +2 -2
  208. package/dist/{postgres-adapter-BpLizOaK.mjs.map → postgres-adapter-OoqoBdhb.mjs.map} +1 -1
  209. package/dist/{postgres-result-133boRW-.mjs → postgres-result-D-bqmofR.mjs} +1 -1
  210. package/dist/{postgres-result-133boRW-.mjs.map → postgres-result-D-bqmofR.mjs.map} +1 -1
  211. package/dist/postgres.d.mts +2 -2
  212. package/dist/postgres.mjs +1 -1
  213. package/dist/provider-limits-DvcCUw7l.mjs +2 -0
  214. package/dist/provider-limits-DvcCUw7l.mjs.map +1 -0
  215. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs → provider-parameter-snapshot-DnJ6Av9y.mjs} +2 -2
  216. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs.map → provider-parameter-snapshot-DnJ6Av9y.mjs.map} +1 -1
  217. package/dist/push-fingerprint-CegYVFFp.mjs +18 -0
  218. package/dist/push-fingerprint-CegYVFFp.mjs.map +1 -0
  219. package/dist/{quantized-BKBs0joq.mjs → quantized-DLD2cd6q.mjs} +1 -1
  220. package/dist/{quantized-BKBs0joq.mjs.map → quantized-DLD2cd6q.mjs.map} +1 -1
  221. package/dist/query-DSEMPA7r.mjs +2 -0
  222. package/dist/query-DSEMPA7r.mjs.map +1 -0
  223. package/dist/query-backend-CzwVfrQ6.mjs +2 -0
  224. package/dist/{query-backend-TisPjCPF.mjs.map → query-backend-CzwVfrQ6.mjs.map} +1 -1
  225. package/dist/{query-inspection-DwYBKSDG.mjs → query-inspection-CvtTL5Fs.mjs} +2 -2
  226. package/dist/{query-inspection-DwYBKSDG.mjs.map → query-inspection-CvtTL5Fs.mjs.map} +1 -1
  227. package/dist/raw-B8cNef_V.mjs +2 -0
  228. package/dist/{raw-DqEb71JZ.mjs.map → raw-B8cNef_V.mjs.map} +1 -1
  229. package/dist/{relation-bound-CSNKLyDy.mjs → relation-bound-DHP5cpTE.mjs} +1 -1
  230. package/dist/{relation-bound-CSNKLyDy.mjs.map → relation-bound-DHP5cpTE.mjs.map} +1 -1
  231. package/dist/{result-parsing-BbffueEX.mjs → result-parsing-DfwBAXY2.mjs} +1 -1
  232. package/dist/{result-parsing-BbffueEX.mjs.map → result-parsing-DfwBAXY2.mjs.map} +1 -1
  233. package/dist/{rows-of-Bgl9GVtK.mjs → rows-of-UeSasWGq.mjs} +2 -2
  234. package/dist/{rows-of-Bgl9GVtK.mjs.map → rows-of-UeSasWGq.mjs.map} +1 -1
  235. package/dist/rule-words-ojG0-vSf.mjs +2 -0
  236. package/dist/{rule-words-DMbQuvD2.mjs.map → rule-words-ojG0-vSf.mjs.map} +1 -1
  237. package/dist/runtime-BAqlANG_.mjs +10 -0
  238. package/dist/runtime-BAqlANG_.mjs.map +1 -0
  239. package/dist/runtime-D0oaIS1E.mjs +2 -0
  240. package/dist/runtime-D0oaIS1E.mjs.map +1 -0
  241. package/dist/runtime-Dfkv59_p.mjs +15 -0
  242. package/dist/runtime-Dfkv59_p.mjs.map +1 -0
  243. package/dist/runtime-client-CvGGOOFd.d.mts +38 -0
  244. package/dist/runtime-client-xeiXA_1m.mjs +2 -0
  245. package/dist/runtime-client-xeiXA_1m.mjs.map +1 -0
  246. package/dist/scalar-BTYxpiP_.mjs +4 -0
  247. package/dist/scalar-BTYxpiP_.mjs.map +1 -0
  248. package/dist/schema/introspect.d.mts +2 -2
  249. package/dist/schema/introspect.mjs +1 -1
  250. package/dist/schema/json.d.mts +2 -2
  251. package/dist/schema/json.mjs +1 -1
  252. package/dist/schema-BzkBJTF-.mjs +2 -0
  253. package/dist/{schema-DDkAUfOb.mjs.map → schema-BzkBJTF-.mjs.map} +1 -1
  254. package/dist/schema-D7MyYTjA.mjs +2 -0
  255. package/dist/{schema-DqR_Kcje.mjs.map → schema-D7MyYTjA.mjs.map} +1 -1
  256. package/dist/{schema-introspection-Bbo4DN_d.mjs → schema-introspection-b4xPGPfu.mjs} +4 -4
  257. package/dist/{schema-introspection-Bbo4DN_d.mjs.map → schema-introspection-b4xPGPfu.mjs.map} +1 -1
  258. package/dist/schema.d.mts +1 -1
  259. package/dist/schema.mjs +1 -1
  260. package/dist/{select-assembly-CEpNu-Gw.mjs → select-assembly-B01JtBRm.mjs} +2 -2
  261. package/dist/{select-assembly-CEpNu-Gw.mjs.map → select-assembly-B01JtBRm.mjs.map} +1 -1
  262. package/dist/serializer-CIhcZMxs.mjs +7 -0
  263. package/dist/serializer-CIhcZMxs.mjs.map +1 -0
  264. package/dist/{settle-Pui-1tfJ.mjs → settle-CIbvnLED.mjs} +1 -1
  265. package/dist/{settle-Pui-1tfJ.mjs.map → settle-CIbvnLED.mjs.map} +1 -1
  266. package/dist/{settled-DYYPcaBX.mjs → settled-Clanz_kI.mjs} +2 -2
  267. package/dist/{settled-DYYPcaBX.mjs.map → settled-Clanz_kI.mjs.map} +1 -1
  268. package/dist/snowflake-C1dqbche.mjs +2 -0
  269. package/dist/{snowflake-BfF8xwfP.mjs.map → snowflake-C1dqbche.mjs.map} +1 -1
  270. package/dist/snowflake.d.mts +2 -2
  271. package/dist/snowflake.mjs +2 -2
  272. package/dist/snowflake.mjs.map +1 -1
  273. package/dist/soft-delete.d.mts +1 -1
  274. package/dist/soft-delete.mjs +1 -1
  275. package/dist/{spans-DwDXMvyd.mjs → spans-CVl3RKUR.mjs} +1 -1
  276. package/dist/{spans-DwDXMvyd.mjs.map → spans-CVl3RKUR.mjs.map} +1 -1
  277. package/dist/sql-AHN2niBz.mjs +2 -0
  278. package/dist/{sql-Bu63iAfT.mjs.map → sql-AHN2niBz.mjs.map} +1 -1
  279. package/dist/sql-control-Cdp0_Mwy.mjs +2 -0
  280. package/dist/sql-control-Cdp0_Mwy.mjs.map +1 -0
  281. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs → sql-statement-tokens-BdVJnUQY.mjs} +2 -2
  282. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs.map → sql-statement-tokens-BdVJnUQY.mjs.map} +1 -1
  283. package/dist/sql-tegqTqGq.mjs +1 -1
  284. package/dist/sql.d.mts +1 -1
  285. package/dist/sqlite-adapter-B7r7w3CS.mjs +2 -0
  286. package/dist/sqlite-adapter-B7r7w3CS.mjs.map +1 -0
  287. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs → sqlite-statement-classifier-CBmKy8Ta.mjs} +2 -2
  288. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs.map → sqlite-statement-classifier-CBmKy8Ta.mjs.map} +1 -1
  289. package/dist/sqlite-storage-audit-D8nA9ylL.mjs +2 -0
  290. package/dist/sqlite-storage-audit-D8nA9ylL.mjs.map +1 -0
  291. package/dist/{sqlite-utils-Bfmtkt1b.mjs → sqlite-utils-BAUMCrok.mjs} +2 -2
  292. package/dist/{sqlite-utils-Bfmtkt1b.mjs.map → sqlite-utils-BAUMCrok.mjs.map} +1 -1
  293. package/dist/sqlite3.d.mts +1 -1
  294. package/dist/sqlite3.mjs +1 -1
  295. package/dist/{standard-sql-Bl2OHGfi.mjs → standard-sql-tpcKlArE.mjs} +2 -2
  296. package/dist/{standard-sql-Bl2OHGfi.mjs.map → standard-sql-tpcKlArE.mjs.map} +1 -1
  297. package/dist/surrealdb.d.mts +2 -2
  298. package/dist/surrealdb.mjs +1 -1
  299. package/dist/surrealdb.mjs.map +1 -1
  300. package/dist/surrealql-AyDLKSEQ.mjs +2 -0
  301. package/dist/surrealql-AyDLKSEQ.mjs.map +1 -0
  302. package/dist/time-step-BIdl2Iy7.mjs +2 -0
  303. package/dist/time-step-BIdl2Iy7.mjs.map +1 -0
  304. package/dist/transaction-operation-CaWzo7gE.mjs +1 -1
  305. package/dist/type-mapping-BYre7JQ1.mjs +3 -0
  306. package/dist/type-mapping-BYre7JQ1.mjs.map +1 -0
  307. package/dist/{types-Dy33vBdd.mjs → types-M-IdB4Mo.mjs} +1 -1
  308. package/dist/{types-Dy33vBdd.mjs.map → types-M-IdB4Mo.mjs.map} +1 -1
  309. package/dist/{unit-DUPX5Sdd.mjs → unit-Dnp2HIWg.mjs} +2 -2
  310. package/dist/{unit-DUPX5Sdd.mjs.map → unit-Dnp2HIWg.mjs.map} +1 -1
  311. package/dist/{unit-words-BXpLpyr2.mjs → unit-words-DjVhRXAQ.mjs} +2 -2
  312. package/dist/{unit-words-BXpLpyr2.mjs.map → unit-words-DjVhRXAQ.mjs.map} +1 -1
  313. package/dist/{utils-BHkJsduV.mjs → utils-BB_4NZQC.mjs} +2 -2
  314. package/dist/{utils-BHkJsduV.mjs.map → utils-BB_4NZQC.mjs.map} +1 -1
  315. package/dist/utils-DYrxwV_M.mjs +2 -0
  316. package/dist/utils-DYrxwV_M.mjs.map +1 -0
  317. package/dist/{v1-parse-shared-cJ-uD14P.mjs → v1-parse-shared-CNiFHAJF.mjs} +1 -1
  318. package/dist/{v1-parse-shared-cJ-uD14P.mjs.map → v1-parse-shared-CNiFHAJF.mjs.map} +1 -1
  319. package/dist/validation-CEnhYqhl.mjs +2 -0
  320. package/dist/{validation-BHjx13zG.mjs.map → validation-CEnhYqhl.mjs.map} +1 -1
  321. package/dist/validation.d.mts +1 -1
  322. package/dist/validation.mjs +1 -1
  323. package/dist/validator-CISkL46K.mjs +2 -0
  324. package/dist/validator-CISkL46K.mjs.map +1 -0
  325. package/dist/{values-Ch2cTlss.mjs → values-D0k60ei0.mjs} +2 -2
  326. package/dist/{values-Ch2cTlss.mjs.map → values-D0k60ei0.mjs.map} +1 -1
  327. package/dist/{client-Dlz3-2JC.d.mts → verify-v1-CJFrJ4lx.d.mts} +10 -183
  328. package/dist/version-nEOMCWfV.mjs +2 -0
  329. package/dist/{version-0BDwfy7C.mjs.map → version-nEOMCWfV.mjs.map} +1 -1
  330. package/dist/view-CmLQ0I6x.mjs +2 -0
  331. package/dist/{view-CHgjF2BO.mjs.map → view-CmLQ0I6x.mjs.map} +1 -1
  332. package/dist/write-sinks-BhwgQn_5.mjs +2 -0
  333. package/dist/{write-sinks-Bei5vFHP.mjs.map → write-sinks-BhwgQn_5.mjs.map} +1 -1
  334. package/package.json +27 -2
  335. package/dist/adapter-namespace-DwFnfpED.mjs +0 -2
  336. package/dist/batch-refs-Bd8HvwUc.mjs +0 -2
  337. package/dist/call-0bd_B9Vp.mjs +0 -2
  338. package/dist/client-D7sWgUt2.mjs +0 -2
  339. package/dist/client-D7sWgUt2.mjs.map +0 -1
  340. package/dist/client-DEfFqv4S.mjs +0 -9
  341. package/dist/client-DEfFqv4S.mjs.map +0 -1
  342. package/dist/datetime-physical-codec-DAF7WJpy.mjs +0 -2
  343. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +0 -1
  344. package/dist/every-JpbiHdMb.mjs +0 -2
  345. package/dist/extension-Dh1ddrlA.mjs +0 -2
  346. package/dist/extension-Dh1ddrlA.mjs.map +0 -1
  347. package/dist/geo-area-codec-Bti2PA2i.mjs +0 -2
  348. package/dist/id-domain-Cg65TLZ-.mjs +0 -2
  349. package/dist/identifier-conversion-BTDxDwDB.mjs +0 -2
  350. package/dist/identifier-conversion-BTDxDwDB.mjs.map +0 -1
  351. package/dist/introspect-q3Rf_Xv8.mjs +0 -2
  352. package/dist/json-CsAdz9pg.mjs +0 -2
  353. package/dist/judge-words-k5GCc4cV.mjs +0 -2
  354. package/dist/judge-words-k5GCc4cV.mjs.map +0 -1
  355. package/dist/keys-DZdKAd4n.mjs +0 -2
  356. package/dist/libsql-DEZ0uhK2.mjs +0 -3
  357. package/dist/libsql-DEZ0uhK2.mjs.map +0 -1
  358. package/dist/light-D2wNSbzY.mjs +0 -2
  359. package/dist/memory-BaGWNdvk.mjs +0 -2
  360. package/dist/memory-BaGWNdvk.mjs.map +0 -1
  361. package/dist/methods-part-BaNx3o7b.mjs +0 -2
  362. package/dist/model-Dtd37Sky.mjs +0 -2
  363. package/dist/model-Dtd37Sky.mjs.map +0 -1
  364. package/dist/mysql-BFPF8xyv.mjs +0 -9
  365. package/dist/mysql-BFPF8xyv.mjs.map +0 -1
  366. package/dist/mysql-adapter-BFWYPoM0.mjs +0 -2
  367. package/dist/native-types-1ewJXVks.mjs +0 -2
  368. package/dist/native-types-1ewJXVks.mjs.map +0 -1
  369. package/dist/pending-operation-D4gUKMxD.mjs +0 -2
  370. package/dist/postgres-DQQE2ys_.mjs +0 -34
  371. package/dist/postgres-DQQE2ys_.mjs.map +0 -1
  372. package/dist/postgres-adapter-psTVfuw7.mjs +0 -2
  373. package/dist/postgres-adapter-psTVfuw7.mjs.map +0 -1
  374. package/dist/provider-limits-Bcsz0EJv.mjs +0 -2
  375. package/dist/provider-limits-Bcsz0EJv.mjs.map +0 -1
  376. package/dist/query-BTb6iakn.mjs +0 -2
  377. package/dist/query-BTb6iakn.mjs.map +0 -1
  378. package/dist/query-backend-TisPjCPF.mjs +0 -2
  379. package/dist/raw-DqEb71JZ.mjs +0 -2
  380. package/dist/rule-words-DMbQuvD2.mjs +0 -2
  381. package/dist/scalar-Dm9brvAU.mjs +0 -4
  382. package/dist/scalar-Dm9brvAU.mjs.map +0 -1
  383. package/dist/schema-DDkAUfOb.mjs +0 -2
  384. package/dist/schema-DqR_Kcje.mjs +0 -2
  385. package/dist/serializer-ettLu5xG.mjs +0 -33
  386. package/dist/serializer-ettLu5xG.mjs.map +0 -1
  387. package/dist/snowflake-BfF8xwfP.mjs +0 -2
  388. package/dist/sql-Bu63iAfT.mjs +0 -2
  389. package/dist/sqlite-adapter-Cb-SJw2f.mjs +0 -2
  390. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +0 -1
  391. package/dist/surrealql-DY74AUeD.mjs +0 -2
  392. package/dist/surrealql-DY74AUeD.mjs.map +0 -1
  393. package/dist/time-step-DJaIhpAz.mjs +0 -2
  394. package/dist/time-step-DJaIhpAz.mjs.map +0 -1
  395. package/dist/validation-BHjx13zG.mjs +0 -2
  396. package/dist/validator-DMzH5Tz0.mjs +0 -2
  397. package/dist/validator-DMzH5Tz0.mjs.map +0 -1
  398. package/dist/version-0BDwfy7C.mjs +0 -2
  399. package/dist/view-CHgjF2BO.mjs +0 -2
  400. package/dist/write-sinks-Bei5vFHP.mjs +0 -2
  401. /package/dist/{contract-CxJn0_cV.d.mts → contract-CAoFgKSO.d.mts} +0 -0
  402. /package/dist/{named-statements-NF7Iycjk.d.mts → named-statements-CT4Gbd6t.d.mts} +0 -0
  403. /package/dist/{sql-C4_sFNDm.d.mts → sql-C-SBCGCx.d.mts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serializer-CIhcZMxs.mjs","names":["refuse","refuse","hex","#view","#model","#columns","#root","#aggregate","name"],"sources":["../src/migrations/native-rename.ts","../src/migrations/utils.ts","../src/migrations/types.ts","../src/migrations/resolver.ts","../src/migrations/push/enum-removals.ts","../src/migrations/differ.ts","../src/query-engine/raptor3/kept-view.ts","../src/adapters/inline-literals.ts","../src/query-engine/raptor3/view-body.ts","../src/migrations/view-definition.ts","../src/migrations/serializer.ts"],"sourcesContent":["import type { DiffOperation, SchemaSnapshot, TableDef } from \"./types\";\n\nconst DOLLAR_QUOTE = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/;\nconst IDENTIFIER_START = /[A-Za-z_]/;\nconst IDENTIFIER_PART = /[A-Za-z0-9_$]/;\nconst BARE_IDENTIFIER = /^[a-z_][a-z0-9_$]*$/;\nconst SQL_WHITESPACE = /\\s/;\n\nexport type NativeRenameOperation = Extract<\n DiffOperation,\n { type: \"renameTable\" | \"renameColumn\" }\n>;\n\n/**\n * Applies the schema-wide effect a database native rename has already made.\n *\n * The resolver uses this as its next differ input, generated down migrations\n * use it to address definitions before the inverse rename runs, and SQLite's\n * batch replay uses it before a later table reconstruction. It never mutates\n * the snapshot supplied by the caller.\n */\nexport function applyNativeRename(\n snapshot: SchemaSnapshot,\n operation: NativeRenameOperation\n): SchemaSnapshot {\n return {\n ...snapshot,\n tables:\n operation.type === \"renameTable\"\n ? renameTable(snapshot.tables, operation.from, operation.to)\n : renameColumn(\n snapshot.tables,\n operation.tableName,\n operation.from,\n operation.to\n ),\n };\n}\n\nfunction renameTable(\n tables: readonly TableDef[],\n from: string,\n to: string\n): TableDef[] {\n return tables.map((table) => ({\n ...table,\n name: table.name === from ? to : table.name,\n foreignKeys: table.foreignKeys.map((foreignKey) =>\n foreignKey.referencedTable === from\n ? { ...foreignKey, referencedTable: to }\n : foreignKey\n ),\n }));\n}\n\nfunction renameColumn(\n tables: readonly TableDef[],\n tableName: string,\n from: string,\n to: string\n): TableDef[] {\n const renamed = (name: string) => (name === from ? to : name);\n\n return tables.map((table) => {\n const ownsColumn = table.name === tableName;\n return {\n ...table,\n columns: ownsColumn\n ? table.columns.map((column) =>\n column.name === from ? { ...column, name: to } : column\n )\n : table.columns,\n ...(ownsColumn && table.primaryKey\n ? {\n primaryKey: {\n ...table.primaryKey,\n columns: table.primaryKey.columns.map(renamed),\n },\n }\n : {}),\n indexes: ownsColumn\n ? table.indexes.map((index) => ({\n ...index,\n columns: index.columns.map(renamed),\n ...(index.where === undefined\n ? {}\n : { where: renameSqlIdentifier(index.where, from, to) }),\n }))\n : table.indexes,\n foreignKeys: table.foreignKeys.map((foreignKey) => ({\n ...foreignKey,\n columns: ownsColumn\n ? foreignKey.columns.map(renamed)\n : foreignKey.columns,\n referencedColumns:\n foreignKey.referencedTable === tableName\n ? foreignKey.referencedColumns.map(renamed)\n : foreignKey.referencedColumns,\n })),\n uniqueConstraints: ownsColumn\n ? table.uniqueConstraints.map((constraint) => ({\n ...constraint,\n columns: constraint.columns.map(renamed),\n }))\n : table.uniqueConstraints,\n };\n });\n}\n\n/**\n * Rewrites one identifier in an opaque SQL expression without touching values.\n *\n * PostgreSQL and SQLite persist partial-index predicates as SQL text, but a\n * native column rename changes the parsed column references in those\n * predicates. Snapshot replay must model the same effect before a later table\n * recreation. Quoted identifiers retain their delimiter; ordinary identifiers\n * retain their spelling style when the target can be written bare. Strings,\n * dollar-quoted bodies, and comments are copied byte-for-byte.\n */\nfunction renameSqlIdentifier(sql: string, from: string, to: string): string {\n let rewritten = \"\";\n let cursor = 0;\n\n while (cursor < sql.length) {\n const quote = sql[cursor];\n\n if (quote === \"'\") {\n const end = quotedRegionEnd(sql, cursor, \"'\", \"'\");\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === '\"' || quote === \"`\") {\n const end = quotedRegionEnd(sql, cursor, quote, quote);\n if (sql[end - 1] !== quote) {\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n const body = sql.slice(cursor + 1, end - 1);\n const identifier = body.replaceAll(`${quote}${quote}`, quote);\n rewritten +=\n identifier === from && !isNonColumnIdentifier(sql, cursor, end)\n ? `${quote}${to.replaceAll(quote, `${quote}${quote}`)}${quote}`\n : sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"[\") {\n const end = quotedRegionEnd(sql, cursor, \"]\", \"]\");\n if (sql[end - 1] !== \"]\") {\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n const body = sql.slice(cursor + 1, end - 1);\n const identifier = body.replaceAll(\"]]\", \"]\");\n rewritten +=\n identifier === from && !isNonColumnIdentifier(sql, cursor, end)\n ? `[${escapeBracketIdentifier(to)}]`\n : sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"-\" && sql[cursor + 1] === \"-\") {\n const newline = sql.indexOf(\"\\n\", cursor + 2);\n const end = newline < 0 ? sql.length : newline;\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"/\" && sql[cursor + 1] === \"*\") {\n const end = blockCommentEnd(sql, cursor);\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"$\") {\n const delimiter = dollarQuoteDelimiter(sql, cursor);\n if (delimiter !== undefined) {\n const closing = sql.indexOf(delimiter, cursor + delimiter.length);\n const end = closing < 0 ? sql.length : closing + delimiter.length;\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n }\n if (isIdentifierStart(quote)) {\n let end = cursor + 1;\n while (end < sql.length && isIdentifierPart(sql[end]!)) end += 1;\n const identifier = sql.slice(cursor, end);\n const lowercaseIdentifier = identifier.toLowerCase();\n const escapeStringQuote =\n lowercaseIdentifier === \"e\" && sql[end] === \"'\"\n ? end\n : lowercaseIdentifier === \"u\" &&\n sql[end] === \"&\" &&\n sql[end + 1] === \"'\"\n ? end + 1\n : undefined;\n if (escapeStringQuote !== undefined) {\n const literalEnd = quotedRegionEnd(\n sql,\n escapeStringQuote,\n \"'\",\n \"'\",\n true\n );\n rewritten += sql.slice(cursor, literalEnd);\n cursor = literalEnd;\n continue;\n }\n const isStringPrefix =\n sql[end] === \"'\" ||\n (lowercaseIdentifier === \"u\" &&\n sql[end] === \"&\" &&\n sql[end + 1] === \"'\");\n rewritten +=\n !(isStringPrefix || isNonColumnIdentifier(sql, cursor, end)) &&\n unquotedIdentifierMatches(identifier, from)\n ? bareIdentifierOrQuoted(to)\n : identifier;\n cursor = end;\n continue;\n }\n\n rewritten += quote;\n cursor += 1;\n }\n\n return rewritten;\n}\n\nfunction quotedRegionEnd(\n sql: string,\n start: number,\n closingQuote: string,\n escapedQuote: string,\n backslashEscapes = false\n): number {\n let cursor = start + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== closingQuote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === escapedQuote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return sql.length;\n}\n\nfunction blockCommentEnd(sql: string, start: number): number {\n let cursor = start + 2;\n let depth = 1;\n while (cursor < sql.length && depth > 0) {\n if (sql[cursor] === \"/\" && sql[cursor + 1] === \"*\") {\n depth += 1;\n cursor += 2;\n } else if (sql[cursor] === \"*\" && sql[cursor + 1] === \"/\") {\n depth -= 1;\n cursor += 2;\n } else {\n cursor += 1;\n }\n }\n return cursor;\n}\n\nfunction dollarQuoteDelimiter(sql: string, start: number): string | undefined {\n const rest = sql.slice(start);\n const match = DOLLAR_QUOTE.exec(rest);\n return match?.[0];\n}\n\nfunction isIdentifierStart(character: string | undefined): boolean {\n return character !== undefined && IDENTIFIER_START.test(character);\n}\n\nfunction isIdentifierPart(character: string): boolean {\n return IDENTIFIER_PART.test(character);\n}\n\nfunction unquotedIdentifierMatches(identifier: string, from: string): boolean {\n return from === from.toLowerCase() && identifier.toLowerCase() === from;\n}\n\nfunction isNonColumnIdentifier(\n sql: string,\n start: number,\n end: number\n): boolean {\n let next = end;\n while (next < sql.length && SQL_WHITESPACE.test(sql[next]!)) next += 1;\n if (sql[next] === \"(\" || (sql[next] === \"=\" && sql[next + 1] === \">\")) {\n return true;\n }\n\n let previous = start - 1;\n while (previous >= 0 && SQL_WHITESPACE.test(sql[previous]!)) previous -= 1;\n if (sql[previous] === \".\") return true;\n if (sql[previous] === \":\" && sql[previous - 1] === \":\") return true;\n\n const previousEnd = previous + 1;\n while (previous >= 0 && isIdentifierPart(sql[previous]!)) previous -= 1;\n const previousWord = sql.slice(previous + 1, previousEnd).toLowerCase();\n return previousWord === \"as\" || previousWord === \"collate\";\n}\n\nfunction bareIdentifierOrQuoted(identifier: string): string {\n return BARE_IDENTIFIER.test(identifier)\n ? identifier\n : `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction escapeBracketIdentifier(identifier: string): string {\n return identifier.split(\"]\").join(\"]]\");\n}\n","/**\n * Shared migration helpers that do not own a V1 command.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationDriver } from \"./drivers\";\nimport { orderTableDrops } from \"./drop-order\";\nimport { sha256Hex, utf8Bytes } from \"./identity\";\nimport type { DiffOperation, SchemaSnapshot } from \"./types\";\nimport { withViewReplacements } from \"./view\";\n\nexport {\n createQueryExecutor,\n normalizeDialect,\n type QueryExecutor,\n} from \"./runtime-utils\";\n\n/** PostgreSQL/MySQL derived identifiers keep their uniqueness under byte caps. */\nexport function derivedMigrationName(name: string): string {\n if (utf8Bytes(name).length <= 63) return name;\n let prefix = \"\";\n for (const character of name) {\n if (utf8Bytes(prefix + character).length > 54) break;\n prefix += character;\n }\n return `${prefix}_${sha256Hex(utf8Bytes(name)).slice(0, 8)}`;\n}\n\n/** Default generated-key spelling; dialects may supply their physical rule. */\nexport function defaultGeneratedPrimaryKeyName(\n tableName: string,\n name?: string\n): string {\n return name || `${tableName}_pkey`;\n}\n\n// =============================================================================\n// OPERATION UTILITIES\n// =============================================================================\n\n/**\n * Operation execution order priorities.\n * Lower numbers execute first.\n */\nconst OPERATION_PRIORITY: Record<DiffOperation[\"type\"], number> = {\n // Before every table and enum operation: nothing runs under a view.\n dropView: 0,\n createEnum: 1,\n dropForeignKey: 2,\n dropIndex: 3,\n dropUniqueConstraint: 4,\n dropPrimaryKey: 5,\n dropColumn: 6,\n dropTable: 7,\n createTable: 8,\n renameTable: 9,\n addColumn: 10,\n renameColumn: 11,\n alterColumn: 12,\n addPrimaryKey: 13,\n addUniqueConstraint: 14,\n createIndex: 15,\n addForeignKey: 16,\n alterEnum: 1.5,\n dropEnum: 18,\n // After every table and enum operation: a view reads what they leave.\n createView: 19,\n};\n\n/**\n * Slot for the index drops that have to run *after* the batch's index creates.\n * Between `createIndex` and `addForeignKey`, so a superseded index is gone\n * before a new constraint is bound to whatever is left.\n */\nconst SUPERSEDED_INDEX_DROP_PRIORITY =\n (OPERATION_PRIORITY.createIndex + OPERATION_PRIORITY.addForeignKey) / 2;\n\n/**\n * Picks out the `dropIndex` operations whose replacement has to exist first.\n *\n * MySQL binds a foreign key to whichever index covers its columns and refuses\n * to drop that index while it is the last one covering them (errno 1553). A\n * schema edit that supersedes such an index — widening it, or covering the same\n * columns with a unique constraint — plans the drop and its replacement in the\n * same batch, so the replacement has to be in place before the drop runs.\n *\n * Two arrangements keep a drop in its early slot instead:\n * - The batch creates an index of the *same name*, which the drop has to free\n * first. The name is matched on its own, not per table: PostgreSQL and SQLite\n * scope an index name to the schema/database, so a batch that frees a name on\n * one table and takes it on another collides too (Postgres 42P07). Matching\n * on the name alone can only keep a drop early, never defer one, so it cannot\n * reopen the 1553 case — there the created index has a different name.\n * - A table that also drops a column loses that column's indexes along with it,\n * so a drop deferred past the column drop would address an index already\n * gone. (A dropped *table* cannot collide: index diffs are only produced for\n * tables present in both snapshots.)\n */\nfunction supersededIndexDrops(operations: DiffOperation[]): Set<DiffOperation> {\n const createdIndexNames = new Set<string>();\n const tablesLosingColumns = new Set<string>();\n for (const op of operations) {\n if (op.type === \"createIndex\") {\n createdIndexNames.add(op.index.name);\n } else if (op.type === \"addUniqueConstraint\") {\n createdIndexNames.add(op.constraint.name);\n } else if (op.type === \"addPrimaryKey\" && op.primaryKey.name) {\n createdIndexNames.add(op.primaryKey.name);\n } else if (op.type === \"dropColumn\") {\n tablesLosingColumns.add(op.tableName);\n }\n }\n\n const superseded = new Set<DiffOperation>();\n for (const op of operations) {\n if (\n op.type === \"dropIndex\" &&\n // A raw index covers no foreign key, so 1553 never holds it; and a table\n // rebuild before its drop would have to re-create it, from a template\n // a removed declaration no longer has.\n !op.raw &&\n !createdIndexNames.has(op.indexName) &&\n !tablesLosingColumns.has(op.tableName)\n ) {\n superseded.add(op);\n }\n }\n return superseded;\n}\n\n/**\n * Sorts operations for proper execution order:\n * 1. Create enums (before tables that use them)\n * 2. Drop foreign keys (before dropping tables/columns)\n * 3. Drop indexes, constraints, columns\n * 4. Drop tables\n * 5. Create tables\n * 6. Establish table and column renames before operations using the new names\n * 7. Add or alter columns and constraints\n * 8. Create indexes\n * 9. Drop the indexes those creates supersede (see `supersededIndexDrops`)\n * 10. Add foreign keys (after tables/columns exist)\n *\n * Views are dropped before all of it and created after all of it; their\n * order among themselves is `withViewReplacements`'.\n */\nexport function sortOperations(operations: DiffOperation[]): DiffOperation[] {\n const superseded = supersededIndexDrops(operations);\n const priorityOf = (op: DiffOperation) =>\n superseded.has(op)\n ? SUPERSEDED_INDEX_DROP_PRIORITY\n : OPERATION_PRIORITY[op.type];\n const baseline = operations\n .map((operation, index) => ({ operation, index }))\n .sort((a, b) => priorityOf(a.operation) - priorityOf(b.operation));\n const renames = baseline.filter(\n ({ operation }) =>\n operation.type === \"renameTable\" || operation.type === \"renameColumn\"\n );\n if (renames.length === 0) return baseline.map(({ operation }) => operation);\n const ordered: DiffOperation[] = [];\n const visited = new Set<number>();\n const active = new Set<number>();\n const visit = (entry: (typeof baseline)[number]): void => {\n if (visited.has(entry.index)) return;\n if (active.has(entry.index)) {\n throw new MigrationError(\n \"Migration operations contain a cyclic native rename dependency\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n active.add(entry.index);\n for (const prerequisite of renames) {\n if (prerequisite.index === entry.index) continue;\n const rename = prerequisite.operation;\n const operation = entry.operation;\n if (rename.type === \"renameTable\") {\n // A later producer can reuse an earlier table name. A column rename\n // before that name was consumed addresses the earlier identity.\n if (\n operation.type === \"renameColumn\" &&\n prerequisite.index > entry.index &&\n renames.some(\n (earlier) =>\n earlier.index > entry.index &&\n earlier.index < prerequisite.index &&\n earlier.operation.type === \"renameTable\" &&\n earlier.operation.from === operation.tableName\n )\n )\n continue;\n const needed =\n operation.type === \"renameTable\"\n ? prerequisite.index < entry.index && rename.to === operation.from\n : operationTargetsTable(operation, rename.to);\n if (needed) visit(prerequisite);\n } else if (rename.type === \"renameColumn\") {\n const needed =\n operation.type === \"renameTable\"\n ? prerequisite.index < entry.index &&\n rename.tableName === operation.from\n : operation.type === \"renameColumn\"\n ? prerequisite.index < entry.index &&\n rename.tableName === operation.tableName &&\n rename.to === operation.from\n : operationTargetsColumn(operation, rename.tableName, rename.to);\n if (needed) visit(prerequisite);\n }\n }\n active.delete(entry.index);\n visited.add(entry.index);\n ordered.push(entry.operation);\n };\n for (const entry of baseline) visit(entry);\n return ordered;\n}\n\n/** A table operation that must address the post-rename identity. */\nfunction operationTargetsTable(\n operation: DiffOperation,\n tableName: string\n): boolean {\n if (operation.type === \"createTable\") {\n return operation.table.name === tableName;\n }\n if (operation.type === \"alterEnum\" || operation.type === \"dropEnum\") {\n return (\n operation.dependentColumns?.some(\n (column) => column.tableName === tableName\n ) ?? false\n );\n }\n return \"tableName\" in operation && operation.tableName === tableName;\n}\n\nfunction operationTargetsColumn(\n operation: DiffOperation,\n tableName: string,\n columnName: string\n): boolean {\n // A drop names a key as the rename left it: on PostgreSQL a derived key\n // name follows its column. A raw index's name never does.\n if (operation.type === \"dropIndex\" && operation.raw) return false;\n if (\n operation.type === \"dropIndex\" ||\n operation.type === \"dropUniqueConstraint\" ||\n operation.type === \"dropForeignKey\"\n ) {\n return operation.tableName === tableName;\n }\n if (operation.type === \"alterEnum\" || operation.type === \"dropEnum\") {\n return (\n operation.dependentColumns?.some(\n (column) =>\n column.tableName === tableName && column.columnName === columnName\n ) ?? false\n );\n }\n return (\n \"tableName\" in operation &&\n operation.tableName === tableName &&\n \"columnName\" in operation &&\n operation.columnName === columnName\n );\n}\n\n/**\n * Lifts *forward-reference* foreign keys out of `createTable` operations into\n * separate `addForeignKey` operations, so a table whose FK points at a table\n * created later in the same batch does not emit the constraint before its\n * referenced table exists.\n *\n * This is the DDL-ordering fix for `push()` / generated migrations: a schema\n * that declares a child model (the endpoint holding the FK) *before* its parent\n * would otherwise emit `ALTER TABLE child ADD ... FOREIGN KEY REFERENCES parent`\n * (Postgres) or an inline FK (MySQL) immediately after `CREATE TABLE child`,\n * before `CREATE TABLE parent` runs — Postgres `42P01`, MySQL analogous — and\n * the whole transactional push aborts with zero tables created.\n *\n * The transform is capability-gated and deliberately *surgical*:\n * - Drivers that cannot `ALTER TABLE ADD FOREIGN KEY` (SQLite/LibSQL) keep FKs\n * inline and are returned untouched — they resolve forward references lazily\n * and rewriting an FK into an `addForeignKey` op would trigger a table\n * recreation against an introspected-empty current schema.\n * - Only FKs that reference a table created *later* in this batch are lifted.\n * Backward references (referenced-first schemas, self-references, FKs to\n * pre-existing tables) already work and are left byte-identical, preserving\n * the DDL of schemas that were never broken.\n *\n * Lifted `addForeignKey` operations are appended after every other operation so\n * they run once all `CREATE TABLE`s have executed. Non-lifted operations retain\n * their exact input order.\n */\nexport function extractForwardReferenceForeignKeys(\n operations: DiffOperation[],\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return operations;\n }\n\n // Position of each table within the sequence of createTable operations.\n const createdTablePosition = new Map<string, number>();\n let position = 0;\n for (const op of operations) {\n if (op.type === \"createTable\") {\n createdTablePosition.set(op.table.name, position);\n position += 1;\n }\n }\n\n const result: DiffOperation[] = [];\n const liftedForeignKeys: DiffOperation[] = [];\n\n for (const op of operations) {\n if (op.type !== \"createTable\") {\n result.push(op);\n continue;\n }\n\n const selfPosition = createdTablePosition.get(op.table.name);\n // Partition this table's FKs into those that must stay inline and those\n // that point forward to a table created later in the batch.\n const retained = op.table.foreignKeys.filter((fk) => {\n const targetPosition = createdTablePosition.get(fk.referencedTable);\n const isForwardReference =\n targetPosition !== undefined &&\n selfPosition !== undefined &&\n targetPosition > selfPosition;\n return !isForwardReference;\n });\n\n if (retained.length === op.table.foreignKeys.length) {\n // No forward references — leave the operation byte-identical.\n result.push(op);\n continue;\n }\n\n const forwardForeignKeys = op.table.foreignKeys.filter(\n (fk) => !retained.includes(fk)\n );\n\n result.push({\n ...op,\n table: { ...op.table, foreignKeys: retained },\n });\n for (const fk of forwardForeignKeys) {\n liftedForeignKeys.push({\n type: \"addForeignKey\",\n tableName: op.table.name,\n fk,\n });\n }\n }\n\n return [...result, ...liftedForeignKeys];\n}\n\n/**\n * Materializes the foreign-key drops a dropped-table graph needs, ONCE, for\n * every consumer: push, generated up SQL, and inverted generated down SQL.\n *\n * The differ omits a foreign-key drop when both endpoint tables disappear —\n * there is no surviving table to alter, so nothing produces the operation — and\n * §6.1 removes the `CASCADE` that used to paper over it. Without this stage a\n * `RESTRICT` drop of two mutually-referencing tables fails no matter which\n * order they are emitted in, and a cycle fails in every order.\n *\n * Every implicated key is included regardless of the table order the batch\n * happens to have, including keys whose owning AND referenced tables are both\n * being dropped, and including cycles. `sortOperations` then puts every\n * `dropForeignKey` (priority 2) ahead of every `dropTable` (priority 7).\n *\n * Drivers that cannot `ALTER TABLE ... DROP CONSTRAINT` keep their operations\n * byte-identical: SQLite and LibSQL hold foreign keys inline and rebuild tables\n * instead, so an explicit drop is not a statement they can emit.\n */\nexport function materializeDroppedTableForeignKeys(\n operations: DiffOperation[],\n current: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return operations;\n }\n\n const droppedTables = new Set<string>();\n const plannedDrops = new Set<string>();\n for (const op of operations) {\n if (op.type === \"dropTable\") {\n droppedTables.add(op.tableName);\n } else if (op.type === \"dropForeignKey\") {\n plannedDrops.add(`${op.tableName} ${op.fkName}`);\n }\n }\n if (droppedTables.size === 0) {\n return operations;\n }\n\n const materialized: DiffOperation[] = [];\n for (const table of current.tables) {\n for (const fk of table.foreignKeys) {\n const implicated =\n droppedTables.has(table.name) || droppedTables.has(fk.referencedTable);\n if (implicated && !plannedDrops.has(`${table.name} ${fk.name}`)) {\n materialized.push({\n type: \"dropForeignKey\",\n tableName: table.name,\n fkName: fk.name,\n });\n }\n }\n }\n\n return materialized.length === 0\n ? operations\n : [...materialized, ...operations];\n}\n\n/**\n * One compile-order owner for generated schema programs. Generate and push\n * both hand this result to the compiler, and nothing sorts it afterwards. Do\n * not lift, materialize or order drops at a second call site. Drops are\n * ordered last, once every foreign-key removal the program makes is known;\n * then the views around the whole of it, once every table change is known.\n */\nexport function prepareSchemaProgram(\n operations: DiffOperation[],\n current: SchemaSnapshot,\n desired: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n return withViewReplacements(\n orderTableDrops(\n materializeDroppedTableForeignKeys(\n extractForwardReferenceForeignKeys(operations, migrationDriver),\n current,\n migrationDriver\n ),\n current\n ),\n current,\n desired,\n // SQLite changes a column, a key or a constraint by rebuilding the table.\n migrationDriver.dialect === \"sqlite\",\n // SurrealDB stores a foreign key's column as a record link, so adding or\n // dropping one changes what a view's filter on it compares (measured).\n migrationDriver.dialect === \"surrealql\"\n );\n}\n\n// =============================================================================\n// MIGRATION FILE UTILITIES\n// =============================================================================\n\n/**\n * Generate a migration name based on the operations.\n */\nexport function generateMigrationName(operations: DiffOperation[]): string {\n if (operations.length === 0) {\n return \"empty\";\n }\n\n const primaryOp = operations[0];\n if (!primaryOp) {\n return \"migration\";\n }\n\n switch (primaryOp.type) {\n case \"createTable\":\n return operations.length === 1\n ? `create-${primaryOp.table.name}`\n : \"initial\";\n case \"dropTable\":\n return `drop-${primaryOp.tableName}`;\n case \"addColumn\":\n return `add-${primaryOp.column.name}-to-${primaryOp.tableName}`;\n case \"dropColumn\":\n return `drop-${primaryOp.columnName}-from-${primaryOp.tableName}`;\n case \"renameTable\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"renameColumn\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"createIndex\":\n return `add-index-${primaryOp.index.name}`;\n case \"dropIndex\":\n return `drop-index-${primaryOp.indexName}`;\n case \"addForeignKey\":\n return `add-fk-${primaryOp.fk.name}`;\n case \"dropForeignKey\":\n return `drop-fk-${primaryOp.fkName}`;\n case \"createEnum\":\n return `create-enum-${primaryOp.enumDef.name}`;\n case \"dropEnum\":\n return `drop-enum-${primaryOp.enumName}`;\n case \"alterEnum\":\n return `alter-enum-${primaryOp.enumName}`;\n case \"createView\":\n return operations.every((operation) => operation.type === \"createView\")\n ? `create-view-${primaryOp.view.name}`\n : \"migration\";\n case \"dropView\":\n return `drop-view-${primaryOp.viewName}`;\n default:\n return \"migration\";\n }\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n// =============================================================================\n// SCHEMA SNAPSHOT (database-agnostic representation)\n// =============================================================================\n\nexport interface SchemaSnapshot {\n tables: TableDef[];\n enums?: EnumDef[] | undefined;\n /**\n * Generated-file history for polymorphic discriminator members.\n * This is descriptive metadata only; the structural differ ignores it.\n */\n polymorphicStorage?: readonly PolymorphicSnapshotStorage[] | undefined;\n /**\n * The views the schema declares (`s.view`), sorted by name. The key is\n * absent when there is none, so a snapshot without a view keeps its bytes,\n * its hash and every state id built on it.\n */\n views?: ViewDef[] | undefined;\n}\n\n/**\n * One view: a read of the schema's tables that the database keeps under\n * `name`. Its identity is `hash` (40 lowercase hex characters), never `sql`:\n * a catalog rewrites the text it is given.\n */\nexport interface ViewDef {\n name: string;\n hash: string;\n /**\n * The body, a parameter-free SELECT in the dialect's own SQL, without the\n * wrapper that carries the marker. A stored snapshot always has it; only an\n * introspected one lacks it, since a database holds the text it rewrote.\n */\n sql?: string | undefined;\n /** The tables and views the body reads, by physical name, sorted, each once. */\n dependsOn: string[];\n /**\n * The database stores the view's rows (PostgreSQL's materialized view),\n * computed by its `CREATE` and again by each refresh. Set only for a view\n * declared `.materialized()` on a dialect whose driver materializes views:\n * elsewhere such a view is an ordinary one, and its snapshot says nothing of\n * it. Absent on an ordinary view, so its bytes and hash stay as they were.\n */\n materialized?: true | undefined;\n /**\n * A materialized view's indexes, in a table's form: a unique index for each\n * key the view derives from its source (what `findUnique` can name, and\n * what a concurrent refresh needs), then each one declared with `.index()`.\n * Never set without {@link materialized}; absent when there is none.\n */\n indexes?: IndexDef[] | undefined;\n /**\n * Declared `.materialized({ refresh: \"auto\" })` on a dialect whose\n * triggers keep it: a table holding the view's rows, which triggers on its\n * source keep current at each write. Absent on every other view.\n */\n auto?: AutoViewDef | undefined;\n}\n\n/**\n * What keeps a view declared `refresh: \"auto\"` current, beside the table that\n * holds its rows (named as the view, its marker beside it).\n */\nexport interface AutoViewDef {\n /**\n * Every object the view needs beside its table, each carrying the view's\n * marker, sorted by kind then name: the triggers (on its source, and on\n * MySQL on the parents whose cascades reach it), PostgreSQL's trigger\n * function, and the ordinary view that holds its body. What introspection\n * finds of them; one missing or changed replaces the view.\n */\n objects: AutoViewObject[];\n /**\n * How to create it, from the declared view: a stored snapshot always has\n * it, an introspected one never, as {@link ViewDef.sql}.\n */\n storage?: AutoViewStorage | undefined;\n /**\n * Introspected only: what is left of such a view whose table a hand\n * dropped. Its drop drops its objects and no table.\n */\n tableless?: true | undefined;\n}\n\n/** One object a view declared `refresh: \"auto\"` needs beside its table. */\nexport interface AutoViewObject {\n kind: \"function\" | \"trigger\" | \"view\";\n name: string;\n /** The table a trigger fires on. */\n table?: string | undefined;\n}\n\n/** How a view declared `refresh: \"auto\"` is stored and kept. */\nexport interface AutoViewStorage {\n /** The table whose writes it follows. */\n source: string;\n /** Its table's columns, in the order of its body's. */\n columns: ColumnDef[];\n /** Its key, its table's primary key: its source's key, or its grouped columns, by the view's column names. */\n key: string[];\n /** The source's column of each member of {@link key}, in order: what a trigger reads of its row. */\n sourceKey: string[];\n /** Whether its rows are groups of its source's rows. */\n grouped: boolean;\n /** The source's columns its body reads, sorted: an update that changes none of them leaves it as it is. */\n reads: string[];\n /**\n * MySQL's cascades that reach its source, which fire no trigger there: a\n * trigger before each delete of a parent does what each foreign key would.\n */\n cascades?: AutoViewCascade[] | undefined;\n}\n\n/** One parent's trigger, on MySQL, for the foreign keys of `refresh: \"auto\"` views' cascades. */\nexport interface AutoViewCascade {\n /** The parent table, whose row deletions it follows. */\n table: string;\n /** The trigger's name. */\n trigger: string;\n /** What a deletion of a parent row does to each child, in order. */\n children: {\n table: string;\n columns: string[];\n referencedColumns: string[];\n action: \"cascade\" | \"setNull\";\n }[];\n}\n\nexport interface PolymorphicToOneSnapshotMember {\n readonly publicType: string;\n readonly storedType: string;\n readonly targetTable: string;\n}\n\n/**\n * Logical-only history for a to-one polymorphic relation. The physical\n * facts (columns, index) live in the owner's {@link TableDef} where the\n * structural differ owns them; `storageRef` is the join key into the owner\n * table's `relationStorage` registry — the physical type-column name at\n * serialization time, opaque to every reader and normalized through accepted\n * rename operations before history joins.\n */\nexport interface PolymorphicToOneSnapshot {\n readonly ownerTable: string;\n readonly relation: string;\n readonly kind: \"toOne\";\n readonly storageRef: string;\n readonly members: readonly PolymorphicToOneSnapshotMember[];\n}\n\nexport interface PolymorphicToManySnapshotMember {\n readonly publicType: string;\n readonly storedType: string;\n readonly targetTable: string;\n readonly memberJunctionTable: string;\n readonly inverseCardinality: \"one\" | \"many\";\n}\n\n/**\n * Logical-only history for a collection polymorphic relation: nothing\n * physical (no side columns, constraint names, or referential actions) — each\n * member names its junction table and the structural differ owns that table's\n * shape entirely.\n */\nexport interface PolymorphicToManySnapshot {\n readonly ownerTable: string;\n readonly relation: string;\n readonly kind: \"toMany\";\n readonly members: readonly PolymorphicToManySnapshotMember[];\n}\n\nexport type PolymorphicSnapshotStorage =\n | PolymorphicToOneSnapshot\n | PolymorphicToManySnapshot;\n\n/**\n * One relation-owned physical storage annotation on the table that carries it,\n * keyed in {@link TableDef.relationStorage} by the storage ref (the physical\n * type-column name at serialization time).\n */\nexport interface PolymorphicToOneStorageRegistryEntry {\n readonly kind: \"polymorphicToOne\";\n readonly typeColumn: string;\n readonly idColumn: string;\n readonly index: string;\n}\n\nexport interface TableDef {\n name: string;\n columns: ColumnDef[];\n primaryKey?: PrimaryKeyDef | undefined;\n indexes: IndexDef[];\n foreignKeys: ForeignKeyDef[];\n uniqueConstraints: UniqueConstraintDef[];\n /**\n * Relation-owned storage registry, annotation ONLY: the structural differ\n * ignores it, drivers pass it through `finalizeTable` untouched, no DDL\n * reads it, and introspected snapshots never carry it. Its sole reader is\n * polymorphic member history, which joins\n * {@link PolymorphicToOneSnapshot.storageRef} into it.\n */\n relationStorage?:\n | Readonly<Record<string, PolymorphicToOneStorageRegistryEntry>>\n | undefined;\n /**\n * A generated junction, where a driver stores one differently from a table:\n * {@link MigrationDriver.markJunction} says so. No SQL driver sets it.\n */\n junction?: true | undefined;\n}\n\nexport interface ColumnDef {\n name: string;\n type: string; // Normalized type (e.g., \"varchar(255)\", \"integer\", \"boolean\")\n nullable: boolean;\n default?: string | undefined; // SQL expression for default value\n autoIncrement?: boolean | undefined;\n /**\n * The declared fixed-decimal domain this column stores, when it stores one.\n *\n * `type` is the ACTIVE PHYSICAL representation and this is the ONE logical\n * descriptor beside it — the pair every consumer reads (serializer, snapshot,\n * differ, DDL, introspection, defaults, table reconstruction). They are not\n * redundant: on PostgreSQL and MySQL the physical type spells the domain, but\n * on SQLite the class is `INTEGER` (scalar) or `TEXT` (list) whatever the\n * precision and scale are, so a descriptor change is invisible in `type`\n * alone and the differ would plan nothing for it.\n *\n * Every snapshot producer carries it — the serializer from\n * `ScalarState[\"decimal\"]`, and each introspection from the fact its dialect\n * can prove (a PostgreSQL typmod, a MySQL `DECIMAL(p,s)` or column-comment\n * marker, a SQLite reserved CHECK constraint name) — because a side that\n * cannot recover it would read as a change on every push, forever.\n *\n * There is no parallel decimal metadata map on `Model`, adapter, or\n * migration driver (plan §7.2): this field is the migration layer's only\n * copy, and it is a copy of the frozen descriptor the resolved scalar owns.\n */\n decimal?: DecimalDescriptor | undefined;\n /**\n * The declared SQLite storage vocabulary for one scalar DateTime column.\n *\n * SQLite's three physical types do not identify the logical domain: TEXT,\n * INTEGER, and REAL also store unrelated scalar families. The serializer\n * therefore carries the declaration beside the physical type so an explicit\n * migration can translate an existing DateTime instead of reinterpreting its\n * bytes. Live introspection cannot recover this logical fact and omits it.\n */\n dateTime?: DateTimePhysicalForm | undefined;\n /** SQLite writer CHECK version; physical metadata, never a public point language. */\n geoPointEncoding?: \"legacy\" | \"binary64\" | undefined;\n}\n\nexport interface PrimaryKeyDef {\n columns: string[];\n name?: string | undefined;\n /**\n * SQLite only: the table is `WITHOUT ROWID`, clustered by this key\n * (`Model.withoutRowid`). It lives on the key because it is a property of\n * how the key stores rows: a table without one cannot carry it, and a\n * change of it is the key's change (`dropPrimaryKey` + `addPrimaryKey`, a\n * recreation on SQLite). Absent on every other table and dialect, so their\n * snapshots and hashes are unchanged.\n */\n withoutRowid?: true | undefined;\n}\n\nexport interface IndexDef {\n name: string;\n columns: string[];\n unique: boolean;\n type?: \"btree\" | \"hash\" | \"gin\" | \"gist\" | \"fulltext\" | \"spatial\" | undefined;\n where?: string | undefined; // For partial indexes\n /**\n * An index in the database's own language (`Model.rawIndex`). `columns` are\n * the columns its template names, in the order they first appear, and it is\n * never unique, typed or partial whatever the text says. `hash` is\n * `rawIndexHash(template)`; only an introspected snapshot lacks `template`,\n * since a database holds the rendered text and VibORM's marker beside it.\n */\n raw?: RawIndexDef | undefined;\n}\n\nexport interface RawIndexDef {\n readonly hash: string;\n readonly template?: string | undefined;\n}\n\nexport interface ForeignKeyDef {\n name: string;\n columns: string[];\n referencedTable: string;\n referencedColumns: string[];\n onDelete?: ReferentialAction | undefined;\n onUpdate?: ReferentialAction | undefined;\n}\n\nexport type ReferentialAction =\n | \"cascade\"\n | \"setNull\"\n | \"restrict\"\n | \"noAction\"\n | \"setDefault\";\n\nexport interface UniqueConstraintDef {\n name: string;\n columns: string[];\n}\n\nexport interface EnumDef {\n name: string;\n values: string[];\n}\n\n/**\n * A CHECK constraint on a column a PostgreSQL enum recreation converts.\n *\n * A schema snapshot models no CHECK, so only `push` knows one: it reads it from\n * the live catalog while planning. The recreation drops it before its columns\n * become text, where PostgreSQL would re-parse it against the wrong type, and\n * adds it back under the same name once they are the enum again.\n */\nexport interface EnumDependentCheck {\n tableName: string;\n name: string;\n /** `pg_get_constraintdef`: `NOT VALID` included when it was never validated. */\n definition: string;\n /** The enum values its definition names as constants. */\n values: string[];\n}\n\n// =============================================================================\n// DIFF OPERATIONS (resolved, ready to execute)\n// =============================================================================\n\nexport type DiffOperation =\n | { type: \"createTable\"; table: TableDef }\n | { type: \"dropTable\"; tableName: string }\n | { type: \"renameTable\"; from: string; to: string }\n | { type: \"addColumn\"; tableName: string; column: ColumnDef }\n | { type: \"dropColumn\"; tableName: string; columnName: string }\n | { type: \"renameColumn\"; tableName: string; from: string; to: string }\n | {\n type: \"alterColumn\";\n tableName: string;\n columnName: string;\n from: ColumnDef;\n to: ColumnDef;\n }\n | { type: \"createIndex\"; tableName: string; index: IndexDef }\n | {\n type: \"dropIndex\";\n tableName: string;\n indexName: string;\n /**\n * A raw index's drop: its name never follows a column, so it need not\n * wait for a column rename (and a rollback then restores it after the\n * rename back, rendered with the column it names).\n */\n raw?: true | undefined;\n }\n | { type: \"addForeignKey\"; tableName: string; fk: ForeignKeyDef }\n | { type: \"dropForeignKey\"; tableName: string; fkName: string }\n | {\n type: \"addUniqueConstraint\";\n tableName: string;\n constraint: UniqueConstraintDef;\n }\n | { type: \"dropUniqueConstraint\"; tableName: string; constraintName: string }\n | { type: \"addPrimaryKey\"; tableName: string; primaryKey: PrimaryKeyDef }\n | { type: \"dropPrimaryKey\"; tableName: string; constraintName: string }\n | { type: \"createView\"; view: ViewDef }\n | {\n type: \"dropView\";\n viewName: string;\n /**\n * The view is a materialized one, as the snapshot holding it says:\n * PostgreSQL drops each kind with its own statement.\n */\n materialized?: true | undefined;\n /** A view declared `refresh: \"auto\"`: what the snapshot holding it says keeps it. */\n auto?: AutoViewDef | undefined;\n }\n | { type: \"createEnum\"; enumDef: EnumDef }\n | {\n type: \"dropEnum\";\n enumName: string;\n /**\n * Columns that depend on this enum.\n * Required for SQLite to know which columns need CHECK constraint removal.\n */\n dependentColumns?: Array<{ tableName: string; columnName: string }>;\n }\n | {\n type: \"alterEnum\";\n enumName: string;\n addValues?: string[] | undefined;\n removeValues?: string[] | undefined;\n /**\n * Full list of desired enum values (required when removing values)\n * Used to recreate the enum type in PostgreSQL\n */\n newValues?: string[] | undefined;\n /**\n * Columns that depend on this enum (required when removing values)\n * Each entry is { tableName, columnName }\n */\n dependentColumns?:\n | Array<{ tableName: string; columnName: string }>\n | undefined;\n /**\n * The live CHECK constraints on those columns (PostgreSQL push only;\n * offline generation cannot see them and leaves this unset).\n */\n dependentChecks?: EnumDependentCheck[] | undefined;\n /**\n * Global replacement values for removed enum values.\n * Used as fallback when no column-specific mapping exists.\n * Maps old value -> new value for data migration.\n *\n * Example: { \"pending\": \"inactive\" } - rows with \"pending\" become \"inactive\"\n * Use null to set rows to NULL: { \"pending\": null }\n */\n valueReplacements?: Record<string, string | null> | undefined;\n /**\n * Per-column replacement values for removed enum values.\n * Allows different columns to have different mappings.\n * Key is \"tableName.columnName\", value is the replacement map.\n *\n * Example: { \"users.status\": { \"pending\": \"inactive\" }, \"orders.status\": { \"pending\": \"cancelled\" } }\n */\n columnValueReplacements?:\n | Record<string, Record<string, string | null>>\n | undefined;\n /**\n * Default replacement for any removed values without explicit mapping.\n * Useful when the enum field has a default value - use that here.\n * Use null to set rows to NULL.\n *\n * Example: If your field has `.default(\"active\")`, set defaultReplacement: \"active\"\n */\n defaultReplacement?: string | null | undefined;\n };\n\n// =============================================================================\n// AMBIGUOUS CHANGES (require user input to resolve)\n// =============================================================================\n\n/** Detected when columns are added AND dropped in the same table */\nexport type AmbiguousColumnChange = {\n type: \"ambiguousColumn\";\n tableName: string;\n droppedColumn: ColumnDef;\n addedColumn: ColumnDef;\n};\n\n/** Detected when tables are added AND dropped */\nexport type AmbiguousTableChange = {\n type: \"ambiguousTable\";\n droppedTable: string;\n addedTable: string;\n droppedTableDef: TableDef;\n addedTableDef: TableDef;\n};\n\nexport type AmbiguousChange = AmbiguousColumnChange | AmbiguousTableChange;\n\n/** User's resolution for an ambiguous change */\nexport type ChangeResolution =\n | { type: \"rename\" } // Treat as rename (preserve data)\n | { type: \"addAndDrop\" }; // Treat as separate add + drop (data loss)\n\n// =============================================================================\n// DIFF RESULT (output of differ, before resolution)\n// =============================================================================\n\nexport interface DiffResult {\n /** Operations that are unambiguous and ready to execute */\n operations: DiffOperation[];\n /** Changes that need user input to resolve */\n ambiguousChanges: AmbiguousChange[];\n}\n\n// =============================================================================\n// RESOLVER (handles ambiguous changes)\n// =============================================================================\n\n/** Callback to resolve ambiguous changes (used by CLI or programmatic API) */\nexport type Resolver = (\n changes: AmbiguousChange[]\n) => Promise<Map<AmbiguousChange, ChangeResolution>>;\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACK\n// =============================================================================\n\n/**\n * Valid resolution results.\n * - \"proceed\": Accept the change (for destructive)\n * - \"reject\": Reject the change and abort\n * - \"rename\": Treat as a rename (for ambiguous)\n * - \"addAndDrop\": Treat as separate add + drop (for ambiguous)\n * - \"enumMapped\": Enum values have been mapped (for enumValueRemoval)\n */\nexport type ResolveResult =\n | \"proceed\"\n | \"reject\"\n | \"rename\"\n | \"addAndDrop\"\n | \"enumMapped\";\n\n/**\n * Base properties shared by destructive and ambiguous changes.\n */\ninterface BaseResolveChange {\n /** The specific operation type */\n operation:\n | \"dropTable\"\n | \"dropColumn\"\n | \"addColumn\"\n | \"alterColumn\"\n | \"renameTable\"\n | \"renameColumn\";\n\n /** The table involved */\n table: string;\n\n /** The column involved (if applicable) */\n column?: string;\n\n /** Human-readable description of the change */\n description: string;\n\n /** Reject this change and abort the operation */\n reject(): \"reject\";\n}\n\n/**\n * A destructive change that will cause data loss.\n * Available methods: `proceed()`, `reject()`\n */\nexport interface DestructiveResolveChange extends BaseResolveChange {\n type: \"destructive\";\n\n /** Accept the destructive change (causes data loss) */\n proceed(): \"proceed\";\n}\n\n/**\n * An ambiguous change that could be a rename or add+drop.\n * Available methods: `rename()`, `addAndDrop()`, `reject()`\n */\nexport interface AmbiguousResolveChange extends BaseResolveChange {\n type: \"ambiguous\";\n\n /** The old name (for renames) */\n oldName?: string;\n\n /** The new name (for renames) */\n newName?: string;\n\n /** The old type (for alterColumn) */\n oldType?: string;\n\n /** The new type (for alterColumn) */\n newType?: string;\n\n /** Treat as a rename (preserves data) */\n rename(): \"rename\";\n\n /** Treat as separate add + drop (causes data loss) */\n addAndDrop(): \"addAndDrop\";\n}\n\n/**\n * An enum value removal that needs replacement mappings for a specific column.\n * Called once per column that uses the enum, allowing different mappings per column.\n * Available methods: `mapValues()`, `useNull()`, `reject()`\n */\nexport interface EnumValueRemovalChange {\n type: \"enumValueRemoval\";\n\n /** The enum name */\n enumName: string;\n\n /** The table containing the column */\n tableName: string;\n\n /** The column using this enum */\n columnName: string;\n\n /** Whether this column is nullable (if true, useNull() is safe) */\n isNullable: boolean;\n\n /** Values being removed */\n removedValues: string[];\n\n /** Available values to map to */\n availableValues: string[];\n\n /** Human-readable description */\n description: string;\n\n /**\n * Map removed values to replacement values.\n * @param replacements - Map of old value → new value (or null for NULL)\n */\n mapValues(replacements: Record<string, string | null>): \"enumMapped\";\n\n /**\n * Set all removed values to NULL.\n * This is a shorthand for mapValues where all values map to null.\n * Note: Only safe if the column is nullable.\n */\n useNull(): \"enumMapped\";\n\n /** Reject this change and abort the operation */\n reject(): \"reject\";\n}\n\n/**\n * A change that requires user resolution.\n * Use the type discriminant to determine which methods are available:\n * - `destructive`: `proceed()`, `reject()`\n * - `ambiguous`: `rename()`, `addAndDrop()`, `reject()`\n * - `enumValueRemoval`: `mapValues()`, `reject()`\n */\nexport type ResolveChange =\n | DestructiveResolveChange\n | AmbiguousResolveChange\n | EnumValueRemovalChange;\n\nexport type EnumResolutionDecision =\n | {\n readonly kind: \"mapValues\";\n readonly mappings: Record<string, string | null>;\n }\n | { readonly kind: \"useNull\" }\n | { readonly kind: \"mixed\" };\n\nconst enumResolutionDecisions = new WeakMap<\n ResolveChange,\n EnumResolutionDecision\n>();\n\n/** Internal authoritative decision made through an enum change's own methods. */\nexport function readEnumResolutionDecision(\n change: ResolveChange\n): EnumResolutionDecision | undefined {\n return enumResolutionDecisions.get(change);\n}\n\nfunction recordEnumResolutionDecision(\n change: EnumValueRemovalChange,\n decision: Exclude<EnumResolutionDecision, { readonly kind: \"mixed\" }>\n): void {\n const previous = enumResolutionDecisions.get(change);\n enumResolutionDecisions.set(\n change,\n previous !== undefined && previous.kind !== decision.kind\n ? { kind: \"mixed\" }\n : decision\n );\n}\n\n/**\n * Unified callback for resolving changes that need user input.\n * Called once per change, allowing granular control over each decision.\n *\n * @param change - The change requiring resolution\n * @returns The resolution decision (call a method on change to get this)\n *\n * @example\n * ```ts\n * resolve: async (change) => {\n * console.log(change.description);\n *\n * if (change.type === \"destructive\") {\n * return confirm(\"Accept data loss?\") ? change.proceed() : change.reject();\n * }\n *\n * if (change.type === \"ambiguous\") {\n * return change.rename();\n * }\n *\n * if (change.type === \"enumValueRemoval\") {\n * // Map removed enum values to new values\n * return change.mapValues({\n * 'PENDING': 'INACTIVE',\n * 'OLD_VALUE': null, // Set to NULL\n * });\n * }\n * }\n * ```\n */\nexport type ResolveCallback = (\n change: ResolveChange\n) =>\n | Promise<ResolveResult | undefined | void>\n | ResolveResult\n | undefined\n | void;\n\n/**\n * Create a destructive change object with resolution methods.\n */\nexport function createDestructiveChange(props: {\n operation: \"dropTable\" | \"dropColumn\" | \"addColumn\" | \"alterColumn\";\n table: string;\n column?: string;\n description: string;\n}): DestructiveResolveChange {\n return {\n type: \"destructive\",\n ...props,\n proceed: () => \"proceed\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an ambiguous change object with resolution methods.\n */\nexport function createAmbiguousChange(props: {\n operation: \"renameTable\" | \"renameColumn\";\n table: string;\n column?: string;\n oldName?: string;\n newName?: string;\n oldType?: string;\n newType?: string;\n description: string;\n}): AmbiguousResolveChange {\n return {\n type: \"ambiguous\",\n ...props,\n rename: () => \"rename\",\n addAndDrop: () => \"addAndDrop\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an enum value removal change object with resolution methods.\n */\nexport function createEnumValueRemovalChange(props: {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n description: string;\n}): EnumValueRemovalChange {\n const change: EnumValueRemovalChange = {\n type: \"enumValueRemoval\",\n ...props,\n mapValues: (replacements: Record<string, string | null>) => {\n const mappings: Record<string, string | null> = {};\n for (const [value, replacement] of Object.entries(replacements)) {\n mappings[value] = replacement;\n }\n Object.freeze(mappings);\n recordEnumResolutionDecision(change, { kind: \"mapValues\", mappings });\n return \"enumMapped\";\n },\n useNull: () => {\n recordEnumResolutionDecision(change, { kind: \"useNull\" });\n return \"enumMapped\";\n },\n reject: () => \"reject\",\n };\n return change;\n}\n\nexport type Dialect =\n | \"postgresql\"\n | \"sqlite\"\n | \"mysql\"\n | \"surrealql\"\n | \"snowflake\";\n\n/**\n * The durable estate target a migration history is generated for.\n *\n * PostgreSQL carries its schema because generated artifacts are\n * schema-qualified: a history generated for `billing` cannot be replayed as a\n * `public` estate. MySQL and SQLite arms carry ONLY their dialect — MySQL\n * artifacts are database-relative on purpose, so one estate deploys to\n * `app_dev`, `app_test` and `app_prod`, and SQLite has no namespace concept.\n *\n * This is the DURABLE compatibility claim, not the live execution destination.\n * The live destination is the adapter's namespace, which MySQL reads at its\n * live boundary and never persists here.\n */\nexport type MigrationTarget = (\n | { readonly dialect: \"postgresql\"; readonly namespace: string }\n | { readonly dialect: \"mysql\" }\n | { readonly dialect: \"sqlite\" }\n | { readonly dialect: \"surrealql\" }\n | { readonly dialect: \"snowflake\" }\n) & { readonly tables?: readonly string[] };\n","/**\n * Resolver System\n *\n * Handles ambiguous changes that require user input to resolve.\n * Provides utilities for converting user resolutions into concrete operations.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\nimport {\n type DiffOptions,\n diff,\n getDestructiveOperationDescriptions,\n isDestructiveOperation,\n} from \"./differ\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport { applyNativeRename } from \"./native-rename\";\nimport type {\n AmbiguousChange,\n AmbiguousResolveChange,\n ChangeResolution,\n DestructiveResolveChange,\n DiffOperation,\n DiffResult,\n EnumValueRemovalChange,\n ResolveCallback,\n ResolveChange,\n ResolveResult,\n Resolver,\n SchemaSnapshot,\n} from \"./types\";\nimport {\n createAmbiguousChange,\n createDestructiveChange,\n readEnumResolutionDecision,\n} from \"./types\";\nimport { sortOperations } from \"./utils\";\nimport { parseApproval } from \"./v1-parse\";\nimport type { MigrationApprovalV1, MigrationDecisionV1 } from \"./v1-types\";\n\nexport function validateResolveResult(\n expected: \"ambiguous\",\n change: AmbiguousResolveChange,\n result: unknown\n): \"rename\" | \"addAndDrop\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: \"destructive\",\n change: DestructiveResolveChange,\n result: unknown\n): \"proceed\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: \"enumValueRemoval\",\n change: EnumValueRemovalChange,\n result: unknown\n): \"enumMapped\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: ResolveChange[\"type\"],\n change: ResolveChange,\n result: unknown\n): ResolveResult | undefined {\n if (result === undefined) return undefined;\n\n if (result === \"reject\") return result;\n if (\n expected === \"ambiguous\" &&\n (result === \"rename\" || result === \"addAndDrop\")\n ) {\n return result;\n }\n if (expected === \"destructive\" && result === \"proceed\") {\n return result;\n }\n if (expected === \"enumValueRemoval\" && result === \"enumMapped\") {\n const decision = readEnumResolutionDecision(change);\n if (decision !== undefined && decision.kind !== \"mixed\") return result;\n }\n\n const received =\n typeof result === \"string\"\n ? `\"${result}\"`\n : result === null\n ? \"null\"\n : typeof result;\n throw new MigrationError(\n `Invalid resolution ${received} for ${expected} change; use change helper method.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n type: \"invalid-resolution-result\",\n },\n }\n );\n}\n\n// =============================================================================\n// RESOLUTION APPLICATION\n// =============================================================================\n\n/** The operations one resolved ambiguous change stands for. */\nexport function operationsFor(\n change: AmbiguousChange,\n resolution: ChangeResolution\n): DiffOperation[] {\n if (change.type === \"ambiguousColumn\") {\n return resolution.type === \"rename\"\n ? [\n {\n type: \"renameColumn\",\n tableName: change.tableName,\n from: change.droppedColumn.name,\n to: change.addedColumn.name,\n },\n ]\n : [\n {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n },\n {\n type: \"addColumn\",\n tableName: change.tableName,\n column: change.addedColumn,\n },\n ];\n }\n return resolution.type === \"rename\"\n ? [\n {\n type: \"renameTable\",\n from: change.droppedTable,\n to: change.addedTable,\n },\n ]\n : [\n { type: \"dropTable\", tableName: change.droppedTable },\n { type: \"createTable\", table: change.addedTableDef },\n ];\n}\n\n/**\n * Resolves every ambiguity exposed by accepted changes.\n *\n * Each decision is applied to a working source snapshot, then the ordinary\n * differ runs again with the original options. Native renames therefore expose\n * nested ambiguities and descriptor alterations through the same owner that\n * found the outer change; no local table differ or pre-rename operation list is\n * retained.\n */\nexport async function resolveAmbiguousChanges(\n initialDiffResult: DiffResult,\n currentSnapshot: SchemaSnapshot,\n desiredSnapshot: SchemaSnapshot,\n resolver: Resolver,\n options: DiffOptions = {}\n): Promise<DiffOperation[]> {\n let workingSnapshot = currentSnapshot;\n let diffResult = initialDiffResult;\n const resolutionOperations: DiffOperation[] = [];\n const resolvedAmbiguities = new Set<string>();\n const liveTableNames = new Map(\n currentSnapshot.tables.map((table) => [table.name, table.name])\n );\n\n while (diffResult.ambiguousChanges.length > 0) {\n const resolutions = await resolver(diffResult.ambiguousChanges);\n\n for (const change of diffResult.ambiguousChanges) {\n const key = ambiguityKey(change);\n if (resolvedAmbiguities.has(key)) {\n throw new MigrationError(\n `Ambiguous migration change did not converge after resolution: ${key}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n resolvedAmbiguities.add(key);\n\n const resolution = resolutions.get(change);\n if (!resolution)\n throw new MigrationError(\n `Missing resolution for ${formatAmbiguousChange(change)}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n const operations = operationsFor(change, resolution);\n resolutionOperations.push(...operations);\n\n for (const operation of operations) {\n workingSnapshot = applyResolutionEffect(\n workingSnapshot,\n operation,\n options.projectRename\n );\n if (operation.type === \"renameTable\") {\n const liveName = liveTableNames.get(operation.from) ?? operation.from;\n liveTableNames.delete(operation.from);\n liveTableNames.set(operation.to, liveName);\n } else if (operation.type === \"dropTable\") {\n liveTableNames.delete(operation.tableName);\n }\n }\n }\n\n diffResult = await diff(\n workingSnapshot,\n desiredSnapshot,\n optionsForWorkingSnapshot(options, liveTableNames)\n );\n }\n\n return sortOperations([...resolutionOperations, ...diffResult.operations]);\n}\n\nfunction ambiguityKey(change: AmbiguousChange): string {\n return change.type === \"ambiguousTable\"\n ? `table:${change.droppedTable}\\u0000${change.addedTable}`\n : `column:${change.tableName}\\u0000${change.droppedColumn.name}\\u0000${change.addedColumn.name}`;\n}\n\nfunction optionsForWorkingSnapshot(\n options: DiffOptions,\n liveTableNames: ReadonlyMap<string, string>\n): DiffOptions {\n const canonicalize = options.canonicalizeIndexPredicate;\n if (!canonicalize) return options;\n return {\n ...options,\n canonicalizeIndexPredicate: (tableName, predicates) =>\n canonicalize(liveTableNames.get(tableName) ?? tableName, predicates),\n };\n}\n\nfunction applyResolutionEffect(\n snapshot: SchemaSnapshot,\n operation: DiffOperation,\n projectRename: typeof applyNativeRename = applyNativeRename\n): SchemaSnapshot {\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n return projectRename(snapshot, operation);\n }\n if (operation.type === \"dropTable\") {\n return {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) => table.name !== operation.tableName\n ),\n };\n }\n if (operation.type === \"createTable\") {\n return { ...snapshot, tables: [...snapshot.tables, operation.table] };\n }\n if (operation.type === \"dropColumn\") {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? {\n ...table,\n columns: table.columns.filter(\n (column) => column.name !== operation.columnName\n ),\n }\n : table\n ),\n };\n }\n if (operation.type === \"addColumn\") {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? { ...table, columns: [...table.columns, operation.column] }\n : table\n ),\n };\n }\n return snapshot;\n}\n\nexport function ambiguousToResolveChange(\n change: AmbiguousChange\n): AmbiguousResolveChange {\n if (change.type === \"ambiguousColumn\") {\n return createAmbiguousChange({\n operation: \"renameColumn\",\n table: change.tableName,\n column: change.addedColumn.name,\n oldName: change.droppedColumn.name,\n newName: change.addedColumn.name,\n oldType: change.droppedColumn.type,\n newType: change.addedColumn.type,\n description: `Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in table \"${change.tableName}\" (rename or add+drop?)`,\n });\n }\n return createAmbiguousChange({\n operation: \"renameTable\",\n table: change.addedTable,\n oldName: change.droppedTable,\n newName: change.addedTable,\n description: `Table \"${change.droppedTable}\" → \"${change.addedTable}\" (rename or add+drop?)`,\n });\n}\n\n/**\n * `admittedDrops` collects the drop each `addAndDrop` answer already decided,\n * so the destructive question is not asked a second time for it.\n */\nexport function callbackAsResolver(\n callback: ResolveCallback,\n admittedDrops?: Set<string>\n): Resolver {\n return async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const resolveChange = ambiguousToResolveChange(change);\n const result = await callback(resolveChange);\n if (result === \"rename\") {\n resolutions.set(change, { type: \"rename\" });\n continue;\n }\n if (result === \"addAndDrop\") {\n resolutions.set(change, { type: \"addAndDrop\" });\n admittedDrops?.add(ambiguousDropKey(change));\n continue;\n }\n throw new MigrationError(\n `Unresolved ambiguous change: ${resolveChange.description}\\n` +\n \"Generate requires change.rename() or change.addAndDrop() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return resolutions;\n };\n}\n\n// =============================================================================\n// DESTRUCTIVE CHANGES\n// =============================================================================\n\nexport function ambiguousDropKey(change: AmbiguousChange): string {\n return change.type === \"ambiguousTable\"\n ? `table\\u0000${change.droppedTable}`\n : `column\\u0000${change.tableName}\\u0000${change.droppedColumn.name}`;\n}\n\nfunction destructiveDropKey(operation: DiffOperation): string {\n if (operation.type === \"dropTable\") {\n return `table\\u0000${operation.tableName}`;\n }\n if (operation.type === \"dropColumn\") {\n return `column\\u0000${operation.tableName}\\u0000${operation.columnName}`;\n }\n return \"\";\n}\n\n/**\n * Puts every destructive operation (enum value removals excepted: they have\n * their own mapping question) to `resolve` once, for push and generate alike.\n * A rejected or unanswered change refuses, unless `force` admits an unanswered\n * one. Without a callback nothing is asked: the refusal names every change.\n * Returns the approval of every destructive change, in operation order; a drop\n * an `addAndDrop` answer already decided is approved by that answer.\n */\nexport async function approveDestructiveOperations(\n operations: readonly DiffOperation[],\n resolve: ResolveCallback | undefined,\n force: boolean,\n admittedDrops: ReadonlySet<string> = new Set()\n): Promise<MigrationApprovalV1[]> {\n const destructive = operations.filter(\n (operation) =>\n operation.type !== \"alterEnum\" && isDestructiveOperation(operation)\n );\n const facts = destructive.map(describeDestructiveOperation);\n const changes = facts.map(({ column, ...change }) =>\n createDestructiveChange(column === null ? change : { ...change, column })\n );\n if (!resolve && changes.length > 0) {\n throw new MigrationError(\n `Destructive changes need approval:\\n${changes.map((change) => `- ${change.description}`).join(\"\\n\")}\\n\\nPass resolve returning change.proceed() or change.reject().`,\n VibORMErrorCode.MIGRATION_CONSENT_REQUIRED,\n {\n meta: {\n hint: \"Pass resolve returning change.proceed().\",\n },\n }\n );\n }\n for (const [index, change] of changes.entries()) {\n if (!admittedDrops.has(destructiveDropKey(destructive[index]!))) {\n const result = validateResolveResult(\n \"destructive\",\n change,\n await resolve?.(change)\n );\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n if (result === undefined && !force) {\n throw new MigrationError(\n `Unresolved destructive change: ${change.description}\\n` +\n \"Return change.proceed() or change.reject() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n }\n }\n return facts.map(({ operation, table, column }) => ({\n operation,\n table,\n column,\n }));\n}\n\nfunction describeDestructiveOperation(\n op: DiffOperation\n): MigrationApprovalV1 & { readonly description: string } {\n switch (op.type) {\n case \"dropTable\":\n return {\n operation: \"dropTable\",\n table: op.tableName,\n column: null,\n description: `Drop table \"${op.tableName}\" (all data will be lost)`,\n };\n case \"dropColumn\":\n return {\n operation: \"dropColumn\",\n table: op.tableName,\n column: op.columnName,\n description: `Drop column \"${op.columnName}\" from table \"${op.tableName}\" (data will be lost)`,\n };\n case \"addColumn\":\n return {\n operation: \"addColumn\",\n table: op.tableName,\n column: op.column.name,\n description: `Add required column \"${op.tableName}.${op.column.name}\" without a backfill default (fails on populated tables)`,\n };\n case \"alterColumn\":\n return {\n operation: \"alterColumn\",\n table: op.tableName,\n column: op.columnName,\n // The SAME sentences the differ already writes for this operation, and\n // not a second summary of it. Rendering `from.type → to.type` here was\n // silent about the one change whose type does not move: a narrowing\n // decimal domain on SQLite reads `(INTEGER → INTEGER)`, so the user was\n // asked to accept a data-refusing change with nothing on screen to say\n // what it was. Every destructive alterColumn produces at least one\n // description, because the differ's description and classifier share\n // the same owner and ask the same three questions.\n description: getDestructiveOperationDescriptions([op]).join(\"; \"),\n };\n default:\n throw new MigrationError(\n `Unexpected operation type: ${op.type}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n}\n\n// =============================================================================\n// DEFAULT RESOLVERS\n// =============================================================================\n\n/**\n * Resolver that always chooses \"addAndDrop\" for all ambiguous changes.\n * Useful for clean slate scenarios where data loss is acceptable.\n */\nexport const alwaysAddDropResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n resolutions.set(change, { type: \"addAndDrop\" });\n }\n return resolutions;\n};\n\n/**\n * Resolver that throws an error if any ambiguous changes are detected.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const strictResolver: Resolver = async (changes) => {\n if (changes.length > 0) {\n const descriptions = changes.map((change) => {\n if (change.type === \"ambiguousColumn\") {\n return `Column \"${change.droppedColumn.name}\" was removed and \"${change.addedColumn.name}\" was added in table \"${change.tableName}\"`;\n }\n return `Table \"${change.droppedTable}\" was removed and \"${change.addedTable}\" was added`;\n });\n\n throw new MigrationError(\n `Ambiguous changes detected that require resolution:\\n${descriptions.join(\"\\n\")}\\n\\n` +\n \"Supply a resolve callback choosing rename() or addAndDrop() for each change.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return new Map();\n};\n\n// =============================================================================\n// RESOLVER HELPERS\n// =============================================================================\n\nconst DECISION_KEYS = {\n column: [\"type\", \"tableName\", \"from\", \"to\", \"resolution\"],\n table: [\"type\", \"from\", \"to\", \"resolution\"],\n enumValueRemoval: [\"type\", \"tableName\", \"columnName\", \"mapValues\"],\n destructive: [\"type\", \"operation\", \"table\", \"column\"],\n} as const satisfies Record<MigrationDecisionV1[\"type\"], readonly string[]>;\nconst DECISION_TYPES = Object.keys(\n DECISION_KEYS\n) as readonly (keyof typeof DECISION_KEYS)[];\nconst ALL_DECISION_KEYS = [...new Set(Object.values(DECISION_KEYS).flat())];\nconst RESOLUTIONS = [\"rename\", \"addAndDrop\"] as const;\n\n/** Each predefined resolver's decisions, and those a plan used since the last check. */\nconst decisionUse = new WeakMap<\n ResolveCallback,\n {\n readonly decisions: readonly MigrationDecisionV1[];\n readonly used: Set<MigrationDecisionV1>;\n }\n>();\n\n/**\n * Intent as data (plan T2): a resolve callback built from plain JSON\n * decisions, so an API can carry them. It answers each change one decision\n * names and leaves every other change unanswered, which refuses it. An entry\n * that is not a decision is refused here (V4002); `generate` refuses (V4002)\n * a decision that answered no change of its plan, such as one naming a table\n * or column the plan does not touch. It serves one request: build one per\n * `generate`.\n */\nexport function createPredefinedResolver(\n decisions: readonly MigrationDecisionV1[]\n): ResolveCallback {\n const admitted = snapshotExactArray(\n decisions,\n \"decisions\",\n refuseDecision\n ).map(parseDecision);\n const used = new Set<MigrationDecisionV1>();\n const resolve: ResolveCallback = (change) => {\n for (const decision of admitted) {\n const answer = answerChange(decision, change);\n if (answer === undefined) continue;\n used.add(decision);\n return answer;\n }\n return undefined;\n };\n decisionUse.set(resolve, { decisions: admitted, used });\n return resolve;\n}\n\n/** Refuses the decisions of a predefined resolver that answered no change. */\nexport function refuseUnusedDecisions(\n resolve: ResolveCallback | undefined\n): void {\n const use = resolve && decisionUse.get(resolve);\n if (!use) return;\n const unused = use.decisions.filter((decision) => !use.used.has(decision));\n use.used.clear();\n if (unused.length > 0) {\n refuseDecision(\n `Unused decisions match no change: ${JSON.stringify(unused)}`\n );\n }\n}\n\nfunction answerChange(\n decision: MigrationDecisionV1,\n change: ResolveChange\n): ResolveResult | undefined {\n switch (decision.type) {\n case \"destructive\":\n return change.type === \"destructive\" &&\n change.operation === decision.operation &&\n change.table === decision.table &&\n (change.column ?? null) === decision.column\n ? change.proceed()\n : undefined;\n case \"enumValueRemoval\":\n return change.type === \"enumValueRemoval\" &&\n change.tableName === decision.tableName &&\n change.columnName === decision.columnName\n ? change.mapValues(decision.mapValues)\n : undefined;\n default: {\n const named =\n change.type === \"ambiguous\" &&\n change.oldName === decision.from &&\n change.newName === decision.to &&\n (decision.type === \"table\"\n ? change.operation === \"renameTable\"\n : change.operation === \"renameColumn\" &&\n change.table === decision.tableName);\n if (!named) return undefined;\n return decision.resolution === \"rename\"\n ? change.rename()\n : change.addAndDrop();\n }\n }\n}\n\nfunction parseDecision(entry: unknown, index: number): MigrationDecisionV1 {\n const label = `decisions[${index}]`;\n const raw = snapshotExactRecord(\n entry,\n ALL_DECISION_KEYS,\n label,\n refuseDecision\n );\n const type =\n DECISION_TYPES.find((name) => name === raw.type) ??\n refuseDecision(`${label}.type must be one of ${DECISION_TYPES.join(\", \")}`);\n // A missing key is refused by its reader below.\n const record = snapshotExactRecord(\n raw,\n DECISION_KEYS[type],\n label,\n refuseDecision\n );\n const text = (key: string): string => {\n const value = record[key];\n return typeof value === \"string\"\n ? value\n : refuseDecision(`${label}.${key} must be a string`);\n };\n const resolution = () =>\n RESOLUTIONS.find((name) => name === record.resolution) ??\n refuseDecision(`${label}.resolution must be rename or addAndDrop`);\n switch (type) {\n case \"column\":\n return {\n type,\n tableName: text(\"tableName\"),\n from: text(\"from\"),\n to: text(\"to\"),\n resolution: resolution(),\n };\n case \"table\":\n return {\n type,\n from: text(\"from\"),\n to: text(\"to\"),\n resolution: resolution(),\n };\n case \"enumValueRemoval\":\n return {\n type,\n tableName: text(\"tableName\"),\n columnName: text(\"columnName\"),\n mapValues: parseValueMapping(record.mapValues, `${label}.mapValues`),\n };\n default:\n return {\n type,\n ...parseApproval(record, label, refuseDecision),\n };\n }\n}\n\nfunction parseValueMapping(\n value: unknown,\n label: string\n): Readonly<Record<string, string | null>> {\n if (!isRecord(value)) return refuseDecision(`${label} must be an object`);\n const mapping: Record<string, string | null> = {};\n for (const [from, to] of Object.entries(value)) {\n if (!(typeof to === \"string\" || to === null)) {\n refuseDecision(`${label}.${from} must be a string or null`);\n }\n mapping[from] = to;\n }\n return Object.freeze(mapping);\n}\n\nfunction refuseDecision(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\n/**\n * Formats ambiguous changes for display\n */\nexport function formatAmbiguousChange(change: AmbiguousChange): string {\n if (change.type === \"ambiguousColumn\") {\n return (\n `Column rename detected in table \"${change.tableName}\":\\n` +\n ` \"${change.droppedColumn.name}\" (${change.droppedColumn.type}) → \"${change.addedColumn.name}\" (${change.addedColumn.type})`\n );\n }\n return (\n \"Table rename detected:\\n\" +\n ` \"${change.droppedTable}\" → \"${change.addedTable}\"`\n );\n}\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACKS\n// =============================================================================\n\n/**\n * Rejects all changes requiring resolution.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const rejectAllResolver: ResolveCallback = async (change) =>\n change.reject();\n\n/**\n * Accepts destructive changes, treats ambiguous column changes as renames,\n * and maps enum value removals to NULL.\n * A table pair stays undecided, so the plan refuses: the dropped side may be\n * another application's table, and only a callback naming the pair may\n * rename it.\n */\nexport const lenientResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.operation === \"renameColumn\" ? change.rename() : undefined;\n }\n\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n\n/**\n * Accepts destructive changes, treats ambiguous changes as add+drop,\n * and maps enum value removals to NULL.\n * Useful when you don't care about preserving data in ambiguous scenarios.\n */\nexport const addDropResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.addAndDrop();\n }\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n","import { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { parseMySqlEnumValues } from \"../drivers/type-mapping\";\nimport { validateResolveResult } from \"../resolver\";\nimport {\n createEnumValueRemovalChange,\n type DiffOperation,\n type ResolveCallback,\n readEnumResolutionDecision,\n type SchemaSnapshot,\n} from \"../types\";\n\nconst INLINE_ENUM_TOKEN =\n /^(?:enum\\(|text check\\(\"(?:[^\"]|\"\")*\"\\s+in\\s+\\()(\\s*'(?:[^']|'')*'(?:\\s*,\\s*'(?:[^']|'')*')*\\s*)\\)\\)?$/i;\n\n/** The closed inline enum carriers emitted by MySQL and SQLite drivers. */\nexport function inlineEnumValues(type: string): string[] | undefined {\n const match = INLINE_ENUM_TOKEN.exec(type.trim());\n if (!match?.[1]) return;\n if (type.trim().toLowerCase().startsWith(\"enum(\"))\n return parseMySqlEnumValues(type) ?? undefined;\n return Array.from(match[1].matchAll(/'((?:[^']|'')*)'/g), (item) =>\n item[1]!.replaceAll(\"''\", \"'\")\n );\n}\n\nexport interface EnumRemoval {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n}\n\ntype ColumnMappings = Record<string, string | null>;\n\nexport type EnumColumnMappings = Map<string, Map<string, ColumnMappings>>;\n\n/**\n * Detects enum value removals that need resolution.\n * Returns one removal per column that uses the enum.\n * Nullability never supplies a data-mapping decision.\n */\nexport function detectEnumValueRemovals(\n operations: DiffOperation[],\n currentSchema: SchemaSnapshot\n): EnumRemoval[] {\n const removals: EnumRemoval[] = [];\n\n for (const op of operations) {\n if (\n op.type === \"alterEnum\" &&\n op.removeValues &&\n op.removeValues.length > 0\n ) {\n const unresolvedValues = op.removeValues.filter((value) => {\n const hasExplicit =\n op.valueReplacements !== undefined && value in op.valueReplacements;\n const hasDefault = op.defaultReplacement !== undefined;\n return !(hasExplicit || hasDefault);\n });\n\n if (unresolvedValues.length > 0) {\n const dependentColumns = op.dependentColumns || [];\n\n for (const dependentColumn of dependentColumns) {\n const table = currentSchema.tables.find(\n (tableDef) => tableDef.name === dependentColumn.tableName\n );\n if (!table) {\n throw new MigrationError(\n `Table \"${dependentColumn.tableName}\" not found in current schema for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n const column = table.columns.find(\n (columnDef) => columnDef.name === dependentColumn.columnName\n );\n if (!column) {\n throw new MigrationError(\n `Column \"${dependentColumn.columnName}\" not found in table \"${dependentColumn.tableName}\" for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n removals.push({\n enumName: op.enumName,\n tableName: dependentColumn.tableName,\n columnName: dependentColumn.columnName,\n isNullable: column.nullable,\n removedValues: unresolvedValues,\n availableValues: op.newValues || [],\n });\n }\n }\n }\n }\n\n return removals;\n}\n\n/**\n * Applies force mode resolutions for enum value removals.\n * Sets all removed values to NULL for each column.\n */\nexport function applyForceEnumResolutions(\n operations: DiffOperation[],\n enumRemovals: EnumRemoval[]\n): DiffOperation[] {\n if (enumRemovals.length === 0) {\n return operations;\n }\n\n const removalsByEnum = new Map<string, EnumRemoval[]>();\n for (const removal of enumRemovals) {\n const existing = removalsByEnum.get(removal.enumName) || [];\n existing.push(removal);\n removalsByEnum.set(removal.enumName, existing);\n }\n\n return operations.map((op) => {\n if (op.type !== \"alterEnum\" || !op.removeValues) {\n return op;\n }\n\n const removals = removalsByEnum.get(op.enumName);\n if (!removals || removals.length === 0) {\n return op;\n }\n\n const columnValueReplacements: Record<string, ColumnMappings> = {\n ...op.columnValueReplacements,\n };\n\n for (const removal of removals) {\n const columnKey = getColumnKey(removal);\n columnValueReplacements[columnKey] = {\n ...columnValueReplacements[columnKey],\n ...createNullMappings(removal.removedValues),\n };\n }\n\n return {\n ...op,\n columnValueReplacements,\n };\n });\n}\n\nexport async function resolveEnumValueRemovalMappings(\n enumRemovals: EnumRemoval[],\n resolve: ResolveCallback,\n force: boolean\n): Promise<EnumColumnMappings> {\n const columnMappings: EnumColumnMappings = new Map();\n\n for (const removal of enumRemovals) {\n const change = createEnumValueRemovalChange({\n enumName: removal.enumName,\n tableName: removal.tableName,\n columnName: removal.columnName,\n isNullable: removal.isNullable,\n removedValues: removal.removedValues,\n availableValues: removal.availableValues,\n description:\n `Column \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - ` +\n `removing values: ${removal.removedValues.join(\", \")}. ` +\n `Map to: ${removal.availableValues.join(\", \")} or NULL`,\n });\n\n const result = validateResolveResult(\n \"enumValueRemoval\",\n change,\n await resolve(change)\n );\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n\n const columnKey = getColumnKey(removal);\n\n if (result === undefined) {\n if (force) {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n createNullMappings(removal.removedValues)\n );\n } else {\n throw new MigrationError(\n `Unresolved enum value removal: ${change.description}\\n` +\n \"Return change.mapValues() or change.useNull() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n continue;\n }\n\n if (result === \"enumMapped\") {\n const decision = readEnumResolutionDecision(change);\n if (decision?.kind === \"mapValues\") {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n decision.mappings\n );\n } else if (decision?.kind === \"useNull\") {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n createNullMappings(removal.removedValues)\n );\n }\n }\n }\n\n return columnMappings;\n}\n\nexport function applyResolvedEnumMappings(\n operations: DiffOperation[],\n columnMappings: EnumColumnMappings\n): DiffOperation[] {\n const enumOperations: DiffOperation[] = [];\n\n for (const op of operations) {\n if (op.type === \"alterEnum\") {\n const enumColumnMappings = columnMappings.get(op.enumName);\n if (enumColumnMappings && enumColumnMappings.size > 0) {\n const columnValueReplacements: Record<string, ColumnMappings> = {\n ...op.columnValueReplacements,\n };\n\n for (const [columnKey, mappings] of enumColumnMappings) {\n columnValueReplacements[columnKey] = {\n ...columnValueReplacements[columnKey],\n ...mappings,\n };\n }\n\n enumOperations.push({\n ...op,\n columnValueReplacements,\n });\n } else {\n enumOperations.push(op);\n }\n }\n }\n\n return enumOperations;\n}\n\nfunction setColumnMappings(\n columnMappings: EnumColumnMappings,\n enumName: string,\n columnKey: string,\n mappings: ColumnMappings\n): void {\n let enumMappings = columnMappings.get(enumName);\n if (!enumMappings) {\n enumMappings = new Map();\n columnMappings.set(enumName, enumMappings);\n }\n enumMappings.set(columnKey, mappings);\n}\n\nfunction createNullMappings(values: string[]): Record<string, null> {\n const nullMappings: Record<string, null> = {};\n for (const value of values) {\n nullMappings[value] = null;\n }\n return nullMappings;\n}\n\nfunction getColumnKey(removal: EnumRemoval): string {\n return `${removal.tableName}.${removal.columnName}`;\n}\n","import { sqliteGeoPointEncoding } from \"../adapters/databases/sqlite/storage/geo-point\";\n\n/**\n * Schema Differ\n *\n * Compares two SchemaSnapshots and produces a list of DiffOperations,\n * detecting ambiguous changes that require user input.\n */\n\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n decimalChangeNarrows,\n describeDecimalDomain,\n migrationDecimalStorageKind,\n} from \"./decimal\";\nimport type { applyNativeRename } from \"./native-rename\";\nimport { inlineEnumValues } from \"./push/enum-removals\";\nimport {\n canonicalUniqueEntities,\n normalizeDefault,\n normalizeType,\n} from \"./push-fingerprint\";\nimport type {\n AmbiguousChange,\n ColumnDef,\n DiffOperation,\n DiffResult,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\nimport { sortOperations } from \"./utils\";\nimport { dropViewOperation, sameAutoViewObjects } from \"./view\";\n\n// =============================================================================\n// PARTIAL-INDEX PREDICATE CANONICALIZATION (Decision 7.4)\n// =============================================================================\n\n/**\n * Asks the database for its own spelling of each declared index predicate.\n *\n * The differ has no connection of its own; the push path owns one and hands\n * this in (`planPush`). One call carries every predicate of one table, so the\n * round trip is paid once per table that has a partial index whose two\n * spellings differ — usually never, at most once per push.\n *\n * The result is positional. `undefined` at a position means the database did\n * not answer for that predicate, and the differ then treats it as\n * uncomparable — never as equal.\n */\nexport type IndexPredicateCanonicalizer = (\n tableName: string,\n predicates: readonly string[]\n) => Promise<ReadonlyArray<string | undefined>>;\n\nexport interface DiffOptions {\n /**\n * Compares the declared SQLite DateTime storage vocabulary carried by V1\n * snapshots. Enable only when both sides preserve that declaration. Live\n * SQLite introspection cannot recover it from TEXT, INTEGER, or REAL and\n * therefore leaves this off so an unchanged push does not drift forever.\n */\n compareDateTimeDeclarations?: boolean;\n\n /**\n * Canonicalizes partial-index predicates through the live database. Omitted\n * by callers with no connection (`generate`, which diffs two snapshots) and\n * by dialects whose catalog stores the declared statement verbatim; the\n * differ then compares the two texts raw, which is the fail-closed reading.\n */\n canonicalizeIndexPredicate?: IndexPredicateCanonicalizer;\n\n /**\n * Recognizes a foreign key and a unique constraint by its SHAPE instead of by\n * its name — see `foreignKeyShape` below for why, and for what breaks without\n * it. Set by `planPush` from the migration driver's\n * `introspectionReadsConstraintNames` capability; left off by `generate`,\n * which diffs two snapshots the serializer wrote and where every name is\n * therefore the declared one.\n */\n matchConstraintsByShape?: boolean;\n\n /** Effectful planning admission; diagnostic diffs must retain drift evidence. */\n refuseConstraintNameChurn?: boolean;\n\n /** The exact producer's additional physical effects of an accepted rename. */\n projectRename?: typeof applyNativeRename;\n}\n\n/** What holds indexes: a table, or a materialized view. */\ninterface IndexHolder {\n readonly indexes?: readonly IndexDef[] | undefined;\n}\n\n/** Canonical spellings, keyed by table and by the predicate as declared. */\ntype CanonicalPredicates = ReadonlyMap<string, string>;\n\nconst EMPTY_CANONICAL_PREDICATES: CanonicalPredicates = new Map();\n\n/** NUL joins the halves: no table name and no SQL text can contain one. */\nfunction predicateKey(tableName: string, predicate: string): string {\n return `${tableName}\\u0000${predicate}`;\n}\n\n/**\n * Asks the database for its spelling of every predicate that a partial index\n * present in both snapshots spells two ways.\n *\n * Scoped on purpose. A predicate only one side carries, or that both sides\n * spell identically, is settled without a round trip — so a schema with no\n * partial index, or one that already converged, costs nothing.\n */\nasync function canonicalizeChangedPredicates(\n currentTables: ReadonlyMap<string, IndexHolder>,\n desiredTables: ReadonlyMap<string, IndexHolder>,\n canonicalize: IndexPredicateCanonicalizer | undefined\n): Promise<CanonicalPredicates> {\n if (!canonicalize) return EMPTY_CANONICAL_PREDICATES;\n\n const canonical = new Map<string, string>();\n\n for (const [tableName, desiredTable] of desiredTables) {\n const currentTable = currentTables.get(tableName);\n if (!currentTable) continue;\n\n const currentIndexes = new Map(\n (currentTable.indexes ?? []).map((i) => [i.name, i])\n );\n const pending = new Set<string>();\n\n for (const desiredIndex of desiredTable.indexes ?? []) {\n const currentIndex = currentIndexes.get(desiredIndex.name);\n if (!currentIndex) continue;\n const left = normalizeIndexWhere(currentIndex.where);\n const right = normalizeIndexWhere(desiredIndex.where);\n if (left === undefined || right === undefined || left === right) continue;\n pending.add(left);\n pending.add(right);\n }\n\n if (pending.size === 0) continue;\n\n const predicates = [...pending];\n const spellings = await canonicalize(tableName, predicates);\n for (const [position, predicate] of predicates.entries()) {\n const spelling = spellings[position];\n if (spelling !== undefined) {\n canonical.set(predicateKey(tableName, predicate), spelling);\n }\n }\n }\n\n return canonical;\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction columnPropertiesEqual(\n a: ColumnDef,\n b: ColumnDef,\n compareDateTimeDeclarations: boolean\n): boolean {\n return (\n normalizeType(a.type) === normalizeType(b.type) &&\n a.nullable === b.nullable &&\n normalizeDefault(a.default, a.type) ===\n normalizeDefault(b.default, b.type) &&\n // The declared domain is compared beside the physical type, not instead of\n // it, because the two carry different amounts of the fact per dialect: a\n // PostgreSQL `numeric(10,5)` spells its whole domain in the type, while a\n // SQLite decimal is `INTEGER` (or `TEXT` for a list) at every precision and\n // scale there is. Left out, a SQLite descriptor change plans NOTHING —\n // the type is byte-identical on both sides — and the column silently keeps\n // storing coefficients at the old scale.\n sqliteGeoPointEncoding(a) === sqliteGeoPointEncoding(b) &&\n sameDecimalDescriptor(a.decimal, b.decimal) &&\n (!compareDateTimeDeclarations || a.dateTime === b.dateTime)\n );\n}\n\nfunction columnsEqual(\n a: ColumnDef,\n b: ColumnDef,\n compareDateTimeDeclarations: boolean\n): boolean {\n return (\n a.name === b.name &&\n columnPropertiesEqual(a, b, compareDateTimeDeclarations)\n );\n}\n\nfunction columnsCanBeRenamed(a: ColumnDef, b: ColumnDef): boolean {\n if (normalizeType(a.type) === normalizeType(b.type)) return true;\n const aDecimalKind = migrationDecimalStorageKind(a);\n return (\n aDecimalKind !== undefined &&\n aDecimalKind === migrationDecimalStorageKind(b)\n );\n}\n\nfunction normalizeIndexType(type: IndexDef[\"type\"]): string {\n // An index with no declared type is a B-tree on every dialect. The two\n // snapshot producers spell that differently — introspection reads \"btree\"\n // back from the Postgres/MySQL catalog, SQLite reports no type at all, and\n // the serializer leaves an undeclared type undefined — so the same index\n // must not read as a change.\n return type ?? \"btree\";\n}\n\nfunction normalizeIndexUnique(unique: IndexDef[\"unique\"]): boolean {\n // `type`'s twin (above): the serializer leaves a plain `.index()`'s `unique`\n // undefined while every introspection reads a boolean back from the catalog,\n // so the same index must not read as a change. Left raw, every push re-plans\n // drop+create forever — and on MySQL the drop is a hard 1553 abort when the\n // declared index is the one InnoDB bound the FK to.\n return unique ?? false;\n}\n\nfunction normalizeIndexWhere(where: IndexDef[\"where\"]): string | undefined {\n // `type`'s and `unique`'s third twin, and the one place the partial index's\n // two spellings are reconciled. The serializer passes the declared predicate\n // through untouched; the emitter writes ` WHERE ${where}`, and SQLite stores\n // that statement verbatim, padding and all. Reading it back consumes the\n // whitespace run that separates `WHERE` from the predicate, so a declaration\n // written with padding comes back without its leading part — the same index\n // in two spellings. Left raw, every push re-plans drop+create forever.\n const trimmed = where?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * The one place the two snapshots' predicates are compared, and the reader of\n * the canonical spellings the database supplied (Decision 7.4).\n *\n * `normalizeIndexWhere` above reconciles the *padding* of one text; it cannot\n * reconcile two texts. PostgreSQL's catalog does not store the declared\n * statement — `pg_get_expr(indpred, indrelid)` deparses it, so a declared\n * `published = true` reads back as `(published = true)`, and every push drops\n * and re-creates every partial index. No client-side normalization closes that\n * while staying fail-closed: flatten whitespace and parentheses and\n * `a AND (b OR c)` starts comparing equal to `(a AND b) OR c`, so a real change\n * would stop being seen. So the database is asked, and `canonical` holds what\n * it answered. Two predicates are the same predicate only when BOTH were\n * canonicalized and the two canonical spellings are identical.\n */\nfunction indexWhereEqual(\n tableName: string,\n a: IndexDef,\n b: IndexDef,\n canonical: CanonicalPredicates\n): boolean {\n const left = normalizeIndexWhere(a.where);\n const right = normalizeIndexWhere(b.where);\n if (left === right) return true;\n // A predicate that appears or disappears is a real change on every dialect,\n // and no round trip can make a partial index equal to a total one.\n if (left === undefined || right === undefined) return false;\n\n const leftCanonical = canonical.get(predicateKey(tableName, left));\n const rightCanonical = canonical.get(predicateKey(tableName, right));\n // Fail closed. Without both spellings — no canonicalizer, a dialect that has\n // none, a connection that refused, a predicate the database could not parse —\n // two texts that do not read alike stay a change.\n return leftCanonical !== undefined && leftCanonical === rightCanonical;\n}\n\nfunction indexesEqual(\n tableName: string,\n a: IndexDef,\n b: IndexDef,\n canonical: CanonicalPredicates\n): boolean {\n // A raw index equals only a raw index of the same text over the same\n // columns: a hand-made index under its name is replaced by it.\n if (a.raw || b.raw)\n return (\n a.name === b.name &&\n a.raw?.hash === b.raw?.hash &&\n arraysEqual(a.columns, b.columns)\n );\n return (\n a.name === b.name &&\n normalizeIndexUnique(a.unique) === normalizeIndexUnique(b.unique) &&\n arraysEqual(a.columns, b.columns) &&\n normalizeIndexType(a.type) === normalizeIndexType(b.type) &&\n indexWhereEqual(tableName, a, b, canonical)\n );\n}\n\nfunction arraysEqual<T>(a: T[], b: T[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((val, idx) => val === b[idx]);\n}\n\n// =============================================================================\n// CONSTRAINT IDENTITY\n// =============================================================================\n\nfunction normalizeReferentialAction(\n action: ReferentialAction | undefined\n): ReferentialAction {\n // `normalizeIndexUnique`'s twin on the foreign-key side. Every introspection\n // reads a concrete action back from the catalog — \"NO ACTION\" when the DDL\n // declared none — while a snapshot may leave it undefined, and both spell the\n // same constraint: SQLite and MySQL omit the clause for `noAction`,\n // PostgreSQL writes `ON DELETE NO ACTION`, which is what omitting it means.\n // Left raw, the same key reads as a change and is dropped and re-added on\n // every push.\n return action ?? \"noAction\";\n}\n\n/**\n * What a foreign key IS, with the name left out: the columns it binds, what\n * they point at, and what happens on delete and on update. NUL joins the\n * columns and SOH the parts — no SQL identifier and no action name holds\n * either, so two shapes read alike only when every part does.\n *\n * The name is left out because on some dialects it is not readable. On\n * PostgreSQL and MySQL the catalog carries the name the DDL gave the\n * constraint, so a name IS an identity there and the differ matches on it.\n * SQLite carries no name for either constraint this file matches:\n * `PRAGMA foreign_key_list` has no name column at all, so introspection\n * synthesises `<table>_fk_<n>`, and an inline `CONSTRAINT x UNIQUE (...)` is\n * reported only under SQLite's own `sqlite_autoindex_<table>_<n>`. Matched by\n * name, the declared constraint is therefore missing and the read one extra on\n * every push of an unchanged schema, forever — and the two repairs the differ\n * plans are both wrong:\n *\n * - the foreign key is dropped and re-added, and SQLite has no\n * `ALTER TABLE ADD FOREIGN KEY`, so each of those rebuilds the whole table\n * — copy included — twice per push, for a schema nobody edited;\n * - the unique constraint's drop is `DROP INDEX \"sqlite_autoindex_...\"`,\n * which SQLite refuses (\"index associated with UNIQUE or PRIMARY KEY\n * constraint cannot be dropped\"), so the SECOND push of any SQLite schema\n * carrying a compound unique fails outright.\n *\n * So where the name cannot be read, the shape is the identity: two constraints\n * of one shape are one constraint, whatever the reader called them.\n */\nfunction foreignKeyShape(fk: ForeignKeyDef): string {\n return [\n fk.columns.join(\"\\u0000\"),\n fk.referencedTable,\n fk.referencedColumns.join(\"\\u0000\"),\n normalizeReferentialAction(fk.onDelete),\n normalizeReferentialAction(fk.onUpdate),\n ].join(\"\\u0001\");\n}\n\n/** `foreignKeyShape`'s twin: a unique constraint is its column list. */\nfunction uniqueConstraintShape(constraint: UniqueConstraintDef): string {\n return constraint.columns.join(\"\\u0000\");\n}\n\n/**\n * Pairs each `current` constraint with the `desired` one it is, under whichever\n * identity the dialect supports, and reports what `desired` had left over.\n *\n * Multisets, not maps, on purpose. A database written before\n * `SQLite3MigrationDriver.getCurrentTable` learned to replay the batch can hold\n * several byte-identical foreign keys on one table — they accumulated, one per\n * push, without bound. Keying by identity alone would collapse those into one\n * entry and leave the extras attached forever; pairing k of n leaves n-k\n * unmatched, and unmatched is what gets dropped.\n */\nfunction matchByIdentity<T>(\n current: readonly T[],\n desired: readonly T[],\n identityOf: (item: T) => string\n): { matches: Array<T | undefined>; unmatchedDesired: T[] } {\n const availableByIdentity = new Map<string, number[]>();\n for (const [position, item] of desired.entries()) {\n const identity = identityOf(item);\n const positions = availableByIdentity.get(identity);\n if (positions) {\n positions.push(position);\n } else {\n availableByIdentity.set(identity, [position]);\n }\n }\n\n const consumed = new Set<number>();\n const matches = current.map((item) => {\n const position = availableByIdentity.get(identityOf(item))?.shift();\n if (position === undefined) return undefined;\n consumed.add(position);\n return desired[position];\n });\n\n return {\n matches,\n unmatchedDesired: desired.filter(\n (_, position) => !consumed.has(position)\n ) as T[],\n };\n}\n\n/**\n * A table's keyed members: each current one is dropped when nothing desired\n * matches it, or dropped and re-added when its match differs; each unmatched\n * desired one is then added. Current order first, then desired order.\n */\nfunction diffKeyed<T>(\n current: readonly T[],\n desired: readonly T[],\n identityOf: (item: T) => string,\n equal: (from: T, to: T) => boolean,\n drop: (item: T) => DiffOperation,\n add: (item: T) => DiffOperation\n): DiffOperation[] {\n const { matches, unmatchedDesired } = matchByIdentity(\n current,\n desired,\n identityOf\n );\n return [\n ...current.flatMap((item, position) => {\n const match = matches[position];\n if (match === undefined) return [drop(item)];\n return equal(item, match) ? [] : [drop(item), add(match)];\n }),\n ...unmatchedDesired.map(add),\n ];\n}\n\n/** The index operations of one table or materialized view, by name. */\nfunction diffIndexes(\n relation: string,\n current: readonly IndexDef[],\n desired: readonly IndexDef[],\n canonical: CanonicalPredicates\n): DiffOperation[] {\n return diffKeyed(\n current,\n desired,\n (index) => index.name,\n (from, to) => indexesEqual(relation, from, to, canonical),\n (index) => ({\n type: \"dropIndex\",\n tableName: relation,\n indexName: index.name,\n ...(index.raw ? { raw: true } : {}),\n }),\n (index) => ({ type: \"createIndex\", tableName: relation, index })\n );\n}\n\nfunction enumsEqual(a: EnumDef, b: EnumDef): boolean {\n return a.name === b.name && arraysEqual(a.values, b.values);\n}\n\n// =============================================================================\n// TABLE DIFFER\n// =============================================================================\n\ninterface TableDiffResult {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n}\n\nfunction refuseConstraintNameMismatch(\n table: string,\n actual: string,\n desired: string\n): never {\n throw new MigrationError(\n `Constraint \"${table}.${actual}\" enforces \"${desired}\" under different name; rename or drop first.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table, constraint: actual } }\n );\n}\n\nfunction checkConstraintNameChurn<T extends { readonly name: string }>(\n tableName: string,\n currentList: readonly T[],\n desiredList: readonly T[],\n shapeOf: (item: T) => string\n): void {\n for (const constraint of desiredList) {\n if (currentList.some((actual) => actual.name === constraint.name)) continue;\n const actual = currentList.find(\n (candidate) => shapeOf(candidate) === shapeOf(constraint)\n );\n if (actual)\n refuseConstraintNameMismatch(tableName, actual.name, constraint.name);\n }\n}\n\nfunction diffTable(\n tableName: string,\n current: TableDef,\n desired: TableDef,\n canonical: CanonicalPredicates,\n matchConstraintsByShape: boolean,\n compareDateTimeDeclarations: boolean,\n refuseConstraintNameChurn: boolean,\n projectRename: DiffOptions[\"projectRename\"]\n): TableDiffResult {\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n if (!matchConstraintsByShape && refuseConstraintNameChurn) {\n checkConstraintNameChurn(\n tableName,\n current.foreignKeys,\n desired.foreignKeys,\n foreignKeyShape\n );\n checkConstraintNameChurn(\n tableName,\n current.uniqueConstraints,\n desired.uniqueConstraints,\n uniqueConstraintShape\n );\n const currentPk = current.primaryKey,\n desiredPk = desired.primaryKey;\n if (\n currentPk &&\n desiredPk &&\n arraysEqual(currentPk.columns, desiredPk.columns)\n ) {\n const actual = currentPk.name ?? `${tableName}_pkey`,\n wanted = desiredPk.name ?? `${tableName}_pkey`;\n if (actual !== wanted)\n refuseConstraintNameMismatch(tableName, actual, wanted);\n }\n }\n\n // Build column maps\n const currentColumns = new Map(current.columns.map((c) => [c.name, c]));\n const desiredColumns = new Map(desired.columns.map((c) => [c.name, c]));\n\n // Find dropped and added columns\n const droppedColumns: ColumnDef[] = [];\n const addedColumns: ColumnDef[] = [];\n\n for (const [name, col] of currentColumns) {\n if (!desiredColumns.has(name)) {\n droppedColumns.push(col);\n }\n }\n\n for (const [name, col] of desiredColumns) {\n if (!currentColumns.has(name)) {\n addedColumns.push(col);\n }\n }\n\n // Detect potential column renames (ambiguous changes)\n // A rename is suspected when a column is dropped and another is added\n // with compatible types\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n // The dropped column as the rename would leave it: a type derived from its\n // name (a PostgreSQL per-column enum) follows the column.\n const asRenamed = (dropped: ColumnDef, added: ColumnDef): ColumnDef =>\n projectRename?.(\n { tables: [current] },\n { type: \"renameColumn\", tableName, from: dropped.name, to: added.name }\n ).tables[0]?.columns.find((column) => column.name === added.name) ??\n dropped;\n\n for (const dropped of droppedColumns) {\n for (const added of addedColumns) {\n if (usedDropped.has(dropped.name) || usedAdded.has(added.name)) continue;\n\n if (columnsCanBeRenamed(asRenamed(dropped, added), added)) {\n // This could be a rename - mark as ambiguous\n ambiguousChanges.push({\n type: \"ambiguousColumn\",\n tableName,\n droppedColumn: dropped,\n addedColumn: added,\n });\n usedDropped.add(dropped.name);\n usedAdded.add(added.name);\n }\n }\n }\n\n // Add operations for non-ambiguous drops and adds\n for (const dropped of droppedColumns) {\n if (!usedDropped.has(dropped.name)) {\n operations.push({\n type: \"dropColumn\",\n tableName,\n columnName: dropped.name,\n });\n }\n }\n\n for (const added of addedColumns) {\n if (!usedAdded.has(added.name)) {\n operations.push({\n type: \"addColumn\",\n tableName,\n column: added,\n });\n }\n }\n\n // Check for column modifications (same name, different properties)\n for (const [name, desiredCol] of desiredColumns) {\n const currentCol = currentColumns.get(name);\n if (\n currentCol &&\n !columnsEqual(currentCol, desiredCol, compareDateTimeDeclarations)\n ) {\n const previousValues = inlineEnumValues(currentCol.type);\n const nextValues = inlineEnumValues(desiredCol.type);\n if (\n previousValues &&\n nextValues &&\n normalizeType(currentCol.type) !== normalizeType(desiredCol.type)\n ) {\n operations.push({\n type: \"alterEnum\",\n enumName: desiredCol.type,\n newValues: nextValues,\n addValues: nextValues.filter(\n (value) => !previousValues.includes(value)\n ),\n removeValues: previousValues.filter(\n (value) => !nextValues.includes(value)\n ),\n dependentColumns: [{ tableName, columnName: name }],\n });\n const converted = { ...currentCol, type: desiredCol.type };\n if (\n !columnPropertiesEqual(\n converted,\n desiredCol,\n compareDateTimeDeclarations\n )\n )\n operations.push({\n type: \"alterColumn\",\n tableName,\n columnName: name,\n from: converted,\n to: desiredCol,\n });\n } else {\n operations.push({\n type: \"alterColumn\",\n tableName,\n columnName: name,\n from: currentCol,\n to: desiredCol,\n });\n }\n }\n }\n\n // Foreign keys and uniques match under whichever identity this dialect's\n // introspection supports (see `foreignKeyShape`). Under shape identity a\n // pair IS one shape, so a changed definition — a referential action, a\n // referenced column — is the name-identity dialects' drop and re-add.\n operations.push(\n ...diffIndexes(tableName, current.indexes, desired.indexes, canonical),\n ...diffKeyed(\n current.foreignKeys,\n desired.foreignKeys,\n matchConstraintsByShape ? foreignKeyShape : (fk) => fk.name,\n (from, to) => foreignKeyShape(from) === foreignKeyShape(to),\n (fk) => ({ type: \"dropForeignKey\", tableName, fkName: fk.name }),\n (fk) => ({ type: \"addForeignKey\", tableName, fk })\n ),\n ...diffKeyed(\n current.uniqueConstraints,\n desired.uniqueConstraints,\n matchConstraintsByShape ? uniqueConstraintShape : (uq) => uq.name,\n (from, to) => uniqueConstraintShape(from) === uniqueConstraintShape(to),\n (uq) => ({\n type: \"dropUniqueConstraint\",\n tableName,\n constraintName: uq.name,\n }),\n (constraint) => ({ type: \"addUniqueConstraint\", tableName, constraint })\n )\n );\n\n // Diff primary key\n const currentPk = current.primaryKey;\n const desiredPk = desired.primaryKey;\n\n if (currentPk && !desiredPk) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n } else if (!currentPk && desiredPk) {\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n } else if (\n currentPk &&\n desiredPk &&\n (!arraysEqual(currentPk.columns, desiredPk.columns) ||\n currentPk.withoutRowid !== desiredPk.withoutRowid)\n ) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n }\n\n return { operations, ambiguousChanges };\n}\n\n// =============================================================================\n// MAIN DIFFER\n// =============================================================================\n\n/**\n * Compares two schema snapshots and returns the operations needed to\n * transform the current schema into the desired schema.\n */\nexport async function diff(\n physicalCurrent: SchemaSnapshot,\n physicalDesired: SchemaSnapshot,\n options: DiffOptions = {}\n): Promise<DiffResult> {\n const current = canonicalUniqueEntities(physicalCurrent);\n const desired = canonicalUniqueEntities(physicalDesired);\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n // Logical polymorphic vocabulary is persisted only in authored snapshots.\n // Never publish an empty transition which changes the meaning of stored ids.\n for (const previous of current.polymorphicStorage ?? []) {\n const next = desired.polymorphicStorage?.find(\n (item) =>\n item.ownerTable === previous.ownerTable &&\n item.relation === previous.relation &&\n item.kind === previous.kind\n );\n if (!next) continue;\n for (const member of previous.members) {\n const destination = next.members.find(\n (item) => item.publicType === member.publicType\n );\n if (\n destination &&\n (destination.storedType !== member.storedType ||\n destination.targetTable !== member.targetTable)\n ) {\n throw new MigrationError(\n `Polymorphic \"${previous.ownerTable}.${previous.relation}\" changes \"${member.publicType}\" mapping; author manual transition.`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n }\n }\n\n // Build table maps\n const currentTables = new Map(current.tables.map((t) => [t.name, t]));\n const desiredTables = new Map(desired.tables.map((t) => [t.name, t]));\n const currentViews = new Map(\n (current.views ?? []).map((view) => [view.name, view])\n );\n const desiredViews = new Map(\n (desired.views ?? []).map((view) => [view.name, view])\n );\n // A view that keeps its hash keeps its rows; a materialized one has its\n // indexes compared as a table's are. A view kept by triggers keeps them\n // only with each of its keepers, as a hand can drop one.\n const keptViews = [...desiredViews.keys()].filter((name) => {\n const desiredView = desiredViews.get(name)!;\n const currentView = currentViews.get(name);\n return (\n currentView?.hash === desiredView.hash &&\n sameAutoViewObjects(currentView, desiredView)\n );\n });\n\n const canonicalPredicates = await canonicalizeChangedPredicates(\n new Map<string, IndexHolder>([\n ...currentTables,\n ...keptViews.map((name) => [name, currentViews.get(name)!] as const),\n ]),\n new Map<string, IndexHolder>([\n ...desiredTables,\n ...keptViews.map((name) => [name, desiredViews.get(name)!] as const),\n ]),\n options.canonicalizeIndexPredicate\n );\n\n // Find dropped and added tables\n const droppedTables: string[] = [];\n const addedTables: string[] = [];\n\n for (const [name] of currentTables) {\n if (!desiredTables.has(name)) {\n droppedTables.push(name);\n }\n }\n\n for (const [name] of desiredTables) {\n if (!currentTables.has(name)) {\n addedTables.push(name);\n }\n }\n\n // Detect potential table renames (ambiguous changes)\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n // Similarity orders questions, never answers them: even a zero-overlap\n // drop/create pair still requires an explicit author decision. Present the\n // strongest matches first so an unrelated drop cannot consume a clear rename.\n const candidates = droppedTables\n .flatMap((droppedName) => {\n const droppedTable = currentTables.get(droppedName)!;\n return addedTables.map((addedName) => {\n const addedTable = desiredTables.get(addedName)!;\n const matchingColumns = droppedTable.columns.filter((column) =>\n addedTable.columns.some((other) => columnsEqual(column, other, true))\n ).length;\n const matchingNames = droppedTable.columns.filter((column) =>\n addedTable.columns.some((other) => column.name === other.name)\n ).length;\n return {\n droppedName,\n addedName,\n droppedTable,\n addedTable,\n matchingColumns,\n matchingNames,\n };\n });\n })\n .sort(\n (a, b) =>\n b.matchingNames - a.matchingNames ||\n b.matchingColumns - a.matchingColumns\n );\n for (const candidate of candidates) {\n const { droppedName, addedName, droppedTable, addedTable } = candidate;\n if (usedDropped.has(droppedName) || usedAdded.has(addedName)) continue;\n ambiguousChanges.push({\n type: \"ambiguousTable\",\n droppedTable: droppedName,\n addedTable: addedName,\n droppedTableDef: droppedTable,\n addedTableDef: addedTable,\n });\n usedDropped.add(droppedName);\n usedAdded.add(addedName);\n }\n\n // Add operations for non-ambiguous table drops and creates\n for (const name of droppedTables) {\n if (!usedDropped.has(name)) {\n operations.push({ type: \"dropTable\", tableName: name });\n }\n }\n\n for (const name of addedTables) {\n if (!usedAdded.has(name)) {\n const table = desiredTables.get(name)!;\n operations.push({ type: \"createTable\", table });\n }\n }\n\n // Diff existing tables\n for (const [name, desiredTable] of desiredTables) {\n const currentTable = currentTables.get(name);\n if (currentTable) {\n const tableDiff = diffTable(\n name,\n currentTable,\n desiredTable,\n canonicalPredicates,\n options.matchConstraintsByShape ?? false,\n options.compareDateTimeDeclarations ?? false,\n options.refuseConstraintNameChurn ?? false,\n options.projectRename\n );\n operations.push(...tableDiff.operations);\n ambiguousChanges.push(...tableDiff.ambiguousChanges);\n }\n }\n\n // Diff enums (PostgreSQL specific)\n if (current.enums || desired.enums) {\n const currentEnums = new Map((current.enums || []).map((e) => [e.name, e]));\n const desiredEnums = new Map((desired.enums || []).map((e) => [e.name, e]));\n const dependentColumnsOf = (enumName: string) => {\n const cols = current.tables.flatMap((table) =>\n table.columns.flatMap((column) =>\n column.type === enumName || column.type === `${enumName}[]`\n ? [{ tableName: table.name, columnName: column.name }]\n : []\n )\n );\n return cols.length > 0 ? cols : undefined;\n };\n\n // Dropped enums\n for (const [name] of currentEnums) {\n if (!desiredEnums.has(name)) {\n operations.push({\n type: \"dropEnum\",\n enumName: name,\n dependentColumns: dependentColumnsOf(name),\n });\n }\n }\n\n // Added enums\n for (const [name, enumDef] of desiredEnums) {\n if (!currentEnums.has(name)) {\n operations.push({ type: \"createEnum\", enumDef });\n }\n }\n\n // Modified enums\n for (const [name, desiredEnum] of desiredEnums) {\n const currentEnum = currentEnums.get(name);\n if (currentEnum && !enumsEqual(currentEnum, desiredEnum)) {\n const addValues = desiredEnum.values.filter(\n (v) => !currentEnum.values.includes(v)\n );\n const removeValues = currentEnum.values.filter(\n (v) => !desiredEnum.values.includes(v)\n );\n\n if (\n addValues.length > 0 ||\n removeValues.length > 0 ||\n !arraysEqual(currentEnum.values, desiredEnum.values)\n ) {\n operations.push({\n type: \"alterEnum\",\n enumName: name,\n addValues: addValues.length > 0 ? addValues : undefined,\n removeValues: removeValues.length > 0 ? removeValues : undefined,\n newValues: desiredEnum.values,\n dependentColumns: dependentColumnsOf(name),\n });\n }\n }\n }\n }\n\n // A view is its hash: a changed one is dropped and created again (with its\n // indexes), one side only is created or dropped, and one that keeps it has\n // its indexes diffed, so a new index does not compute a materialized view\n // again. What the program does under a view that keeps its hash is\n // `withViewReplacements`, once the program is resolved.\n for (const [name, view] of currentViews) {\n if (!keptViews.includes(name)) operations.push(dropViewOperation(view));\n }\n for (const [name, view] of desiredViews) {\n if (!keptViews.includes(name))\n operations.push({ type: \"createView\", view });\n }\n for (const name of keptViews)\n operations.push(\n ...diffIndexes(\n name,\n currentViews.get(name)!.indexes ?? [],\n desiredViews.get(name)!.indexes ?? [],\n canonicalPredicates\n )\n );\n\n // Sort operations for proper execution order\n return {\n operations: sortOperations(\n operations.map((operation): DiffOperation => {\n if (operation.type === \"createTable\")\n return {\n ...operation,\n table:\n physicalDesired.tables.find(\n (table) => table.name === operation.table.name\n ) ?? operation.table,\n };\n if (operation.type === \"addUniqueConstraint\") {\n const index = physicalDesired.tables\n .find((table) => table.name === operation.tableName)\n ?.indexes.find((item) => item.name === operation.constraint.name);\n if (index)\n return {\n type: \"createIndex\",\n tableName: operation.tableName,\n index,\n };\n }\n if (operation.type === \"dropUniqueConstraint\") {\n const index = physicalCurrent.tables\n .find((table) => table.name === operation.tableName)\n ?.indexes.find((item) => item.name === operation.constraintName);\n if (index)\n return {\n type: \"dropIndex\",\n tableName: operation.tableName,\n indexName: index.name,\n };\n }\n return operation;\n })\n ),\n ambiguousChanges,\n };\n}\n\n// =============================================================================\n// DESTRUCTIVE OPERATION CHECKS\n// =============================================================================\n\n/** The one destructive-operation classification used by every consumer. */\nexport function isDestructiveOperation(operation: DiffOperation): boolean {\n if (operation.type === \"alterEnum\")\n return (operation.removeValues?.length ?? 0) > 0;\n if (operation.type === \"addColumn\")\n return !operation.column.nullable && operation.column.default === undefined;\n if (operation.type === \"dropTable\" || operation.type === \"dropColumn\") {\n return true;\n }\n return (\n operation.type === \"alterColumn\" &&\n (normalizeType(operation.from.type) !== normalizeType(operation.to.type) ||\n (operation.from.nullable && !operation.to.nullable) ||\n decimalChangeNarrows(operation.from, operation.to))\n );\n}\n\n/** What each destructive column alteration risks, one sentence per risk. */\nexport function getDestructiveOperationDescriptions(\n operations: DiffOperation[]\n): string[] {\n const descriptions: string[] = [];\n\n for (const op of operations) {\n if (op.type === \"alterColumn\") {\n const col = `\"${op.tableName}\".\"${op.columnName}\"`;\n if (normalizeType(op.from.type) !== normalizeType(op.to.type))\n descriptions.push(\n `Change type of ${col} from ${op.from.type} to ${op.to.type} (may lose data)`\n );\n if (op.from.nullable && !op.to.nullable)\n descriptions.push(`Make ${col} NOT NULL (fails if NULLs exist)`);\n if (\n op.from.decimal &&\n op.to.decimal &&\n decimalChangeNarrows(op.from, op.to)\n )\n descriptions.push(\n `Narrow ${col} from ${describeDecimalDomain(op.from.decimal)} to ${describeDecimalDomain(op.to.decimal)}`\n );\n }\n }\n\n return descriptions;\n}\n","/**\n * What a view kept current by the writes of its one source table cannot\n * hold: SurrealDB's every view (`DEFINE TABLE … AS`), and a view declared\n * `.materialized({ refresh: \"auto\" })` elsewhere, whose triggers compute\n * again the row or the group a write touched. Both follow the writes to the\n * source's own rows and nothing else, and find what a write changed by the\n * values of its fields, so the rules here are the same for both: no read of\n * another table, no caller's SQL fragment, no order or window, no distinct,\n * no filter of the groups, no time step. Each writer refuses with its own\n * reasons, the view named.\n *\n * Only the migrations import this module, as they import `view-body.ts`.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport { viewFacts } from \"@schema/view/facts\";\nimport { Sql } from \"@sql\";\nimport type { PreparedPredicate } from \"./shared/query\";\nimport type { Arguments } from \"./shared/schema\";\n\n/** Why a kept view cannot hold each clause, as its writer states it. */\nexport interface KeptViewReasons {\n /** It reads another table: a relation, `_count`, `_aggregate`, a relation filter. */\n readonly stale: string;\n /** It orders, windows or skips its rows. */\n readonly unordered: string;\n /** It keeps one row per distinct value. */\n readonly distinct: string;\n /** It filters its groups (`having`). */\n readonly unfiltered: string;\n /** It groups by a time step. */\n readonly noStep: string;\n}\n\n/** How a writer refuses a clause: `View '<view>' cannot be created from a query that <clause>: <reason>.` */\nexport type RefuseClause = (clause: string, reason: string) => never;\n\n/** The caller's SQL in a filter, which a view's literals cannot write. */\nconst FRAGMENT =\n \"a view's query holds plain values, which its migration writes as literals\";\n\n/**\n * Refuses a filter that is not the source's own fields compared with plain\n * values: a relation (any read of another table) would go stale, and a\n * caller's SQL fragment has no literal.\n */\nfunction refuseFilter(\n predicate: PreparedPredicate,\n reasons: KeptViewReasons,\n refuse: RefuseClause\n): void {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n for (const inner of predicate.predicates)\n refuseFilter(inner, reasons, refuse);\n return;\n case \"not\":\n refuseFilter(predicate.predicate, reasons, refuse);\n return;\n case \"always\":\n return;\n case \"operation\": {\n const operands = [\n ...(predicate.operand ? [predicate.operand] : []),\n ...(predicate.operands ?? []),\n ];\n if (\n predicate.value instanceof Sql ||\n operands.some(\n (operand) =>\n operand.kind === \"sql\" ||\n operand.kind === \"parameter\" ||\n (operand.kind === \"value\" && operand.value instanceof Sql)\n )\n )\n refuse(\"filters with an SQL fragment\", FRAGMENT);\n return;\n }\n default:\n refuse(\"filters through a relation\", reasons.stale);\n }\n}\n\n/**\n * Refuses what `view`'s admitted query says that a view kept current by its\n * source's writes cannot hold, `predicate` being its prepared `where`.\n */\nexport function refuseUnkept(\n view: AnyModel,\n admitted: Arguments,\n predicate: PreparedPredicate | undefined,\n reasons: KeptViewReasons,\n refuse: RefuseClause\n): void {\n const { documents, aggregated } = viewFacts(view)!;\n if (admitted.cursor !== undefined)\n refuse(\"pages from a cursor\", \"a paging anchor is not a row set\");\n if (admitted.take !== undefined) refuse(\"takes a window\", reasons.unordered);\n if (admitted.skip !== undefined) refuse(\"skips rows\", reasons.unordered);\n if (admitted.orderBy !== undefined)\n refuse(\"orders its rows\", reasons.unordered);\n if (admitted.distinct !== undefined)\n refuse(\"keeps one row per distinct value\", reasons.distinct);\n if (admitted.having !== undefined)\n refuse(\"keeps the groups a having holds\", reasons.unfiltered);\n // A relation, `_count` and `_aggregate` are documents read of other rows.\n const [document] = documents;\n if (document !== undefined)\n refuse(`selects '${document}' through a relation`, reasons.stale);\n for (const origin of Object.values(aggregated?.origins ?? {}))\n if (origin.step !== undefined)\n refuse(\"groups by a time step\", reasons.noStep);\n if (predicate !== undefined) refuseFilter(predicate, reasons, refuse);\n}\n","/**\n * A statement's text with every bound value written as a literal of its\n * dialect: the body of a view, which `CREATE VIEW … AS SELECT …` takes\n * without parameters (`docs/architecture/schema-views-plan.md` §3.1).\n *\n * Only the migrations layer imports this module, by path: no adapter, no\n * adapter barrel and nothing the client or the engine imports reaches it, so\n * an application's bundle never carries it.\n *\n * Each literal means what the dialect's reference driver sends for the value\n * in the same position, so the inlined text reads the rows the bound statement\n * reads:\n *\n * - PostgreSQL: node-postgres sends a string, a number, a bigint and a boolean\n * as text of unknown type, which is what a quoted constant is to the\n * server's type resolution (`'10'`, `'true'`); a bare `10` would be `int4`.\n * Bytes are `bytea`, a JSON carrier its text, a JavaScript array one array\n * literal (node-postgres' `arrayString`).\n * - MySQL: mysql2 runs the text protocol, where the driver itself writes each\n * value into the statement (`sqlstring`); these are its literals.\n * - SQLite: better-sqlite3 binds every JavaScript number as REAL, a boolean\n * too once `convertValueForSQLite` made it 1 or 0, a bigint as INTEGER,\n * bytes as a blob.\n *\n * A value kind no read of the dialect binds has no literal here and is\n * refused, never guessed.\n *\n * No value brings a line break into the text: a migration's statements are a\n * review artifact of plain lines (`migrations/sql-blob.ts` refuses a carriage\n * return), so each dialect writes one its own way (an escape on PostgreSQL\n * and MySQL, `char(13)` and `char(10)` on SQLite).\n */\nimport type { SqlDialect } from \"@drivers/types\";\nimport { UnsupportedOperationError } from \"@errors\";\nimport { Sql } from \"@sql\";\nimport { JsonParameter } from \"../sql/json-parameter\";\nimport { mysqlStringLiteral } from \"./databases/mysql/string-literal\";\nimport { arrayLiteralText } from \"./databases/postgres/array-literal\";\n\nconst DIALECT_NAMES: Record<SqlDialect, string> = {\n postgresql: \"PostgreSQL\",\n mysql: \"MySQL\",\n sqlite: \"SQLite\",\n};\n\nconst QUOTE = /'/g;\n/** What a PostgreSQL escape string spells: a backslash, and a line break. */\nconst ESCAPED = /[\\\\\\n\\r]/;\nconst EVERY_ESCAPED = /[\\\\\\n\\r]/g;\nconst POSTGRES_ESCAPES: Record<string, string> = {\n \"\\\\\": \"\\\\\\\\\",\n \"\\n\": \"\\\\n\",\n \"\\r\": \"\\\\r\",\n};\n/** A line break in a SQLite string: SQLite has no escape for one. */\nconst LINE_BREAK = /\\r|\\n/;\nconst LINE_BREAKS = /(\\r|\\n)/;\nconst INTEGER_TEXT = /^-?\\d+$/;\n\n/** The kind a refusal names. */\nconst kindOf = (value: unknown): string => {\n if (value instanceof Date) return \"Date\";\n if (Array.isArray(value)) return \"array\";\n if (value instanceof JsonParameter) return \"JsonParameter\";\n return typeof value;\n};\n\nfunction refuse(dialect: SqlDialect, value: unknown): never {\n const kind = kindOf(value);\n throw new UnsupportedOperationError(\n `A view body binds a value of kind \"${kind}\", which has no ${DIALECT_NAMES[dialect]} literal: no read of this dialect binds one.`,\n { meta: { dialect, feature: \"view literal\", type: kind } }\n );\n}\n\n/**\n * A string holding NUL: no PostgreSQL text holds one, and SQLite ends a\n * statement's text at it. Refused while the body is written, so a migration\n * generated without a database is not one that fails only when applied.\n */\nfunction refuseNul(dialect: SqlDialect): never {\n throw new UnsupportedOperationError(\n `A view body binds a string holding a NUL character, which a ${DIALECT_NAMES[dialect]} string literal cannot hold.`,\n { meta: { dialect, feature: \"view literal\", type: \"string\" } }\n );\n}\n\nconst hex = (bytes: Uint8Array): string =>\n Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n/** A scalar node-postgres writes into an array literal as its own text. */\nconst isArrayMember = (member: unknown): boolean =>\n typeof member === \"string\" ||\n typeof member === \"number\" ||\n typeof member === \"bigint\" ||\n typeof member === \"boolean\";\n\n/**\n * A PostgreSQL string constant of unknown type that reads the same under\n * either `standard_conforming_strings`: one holding a backslash or a line\n * break is an escape string, whose backslashes are doubled and whose line\n * breaks are written `\\n` and `\\r`.\n */\nfunction postgresString(text: string): string {\n if (text.includes(\"\\0\")) refuseNul(\"postgresql\");\n const quoted = text.replace(QUOTE, \"''\");\n return ESCAPED.test(text)\n ? `E'${quoted.replace(EVERY_ESCAPED, (character) => POSTGRES_ESCAPES[character]!)}'`\n : `'${quoted}'`;\n}\n\nfunction postgresLiteral(value: unknown): string {\n if (value === null) return \"NULL\";\n if (typeof value === \"string\") return postgresString(value);\n if (\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n )\n return postgresString(String(value));\n if (value instanceof Uint8Array)\n return `${postgresString(`\\\\x${hex(value)}`)}::bytea`;\n if (value instanceof JsonParameter) return postgresString(value.json);\n if (Array.isArray(value) && value.every(isArrayMember))\n return postgresString(arrayLiteralText(value));\n return refuse(\"postgresql\", value);\n}\n\nfunction mysqlLiteral(value: unknown): string {\n if (value === null) return \"NULL\";\n if (typeof value === \"string\") return mysqlStringLiteral(value);\n if (typeof value === \"number\" || typeof value === \"bigint\")\n return String(value);\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n if (value instanceof Uint8Array) return `X'${hex(value)}'`;\n return refuse(\"mysql\", value);\n}\n\n/**\n * A signed SQLite number, parenthesized when negative: after a `-` of the\n * statement's own, `--` would open a comment.\n */\nconst signed = (text: string): string =>\n text.startsWith(\"-\") ? `(${text})` : text;\n\nconst sqliteString = (text: string): string => `'${text.replace(QUOTE, \"''\")}'`;\n\nfunction sqliteLiteral(value: unknown): string {\n if (value === null) return \"NULL\";\n if (typeof value === \"string\") {\n if (value.includes(\"\\0\")) refuseNul(\"sqlite\");\n if (!LINE_BREAK.test(value)) return sqliteString(value);\n // Its parts joined around `char(13)` and `char(10)`.\n return `(${value\n .split(LINE_BREAKS)\n .filter((part) => part !== \"\")\n .map((part) =>\n part === \"\\r\"\n ? \"char(13)\"\n : part === \"\\n\"\n ? \"char(10)\"\n : sqliteString(part)\n )\n .join(\" || \")})`;\n }\n if (typeof value === \"number\") {\n // The shortest text that reads back as the same double, made REAL where\n // it would read as an INTEGER (`1` → `1.0`), as the driver binds it.\n const text = String(value);\n return signed(INTEGER_TEXT.test(text) ? `${text}.0` : text);\n }\n // Signed 64-bit: `SQLITE_LITERALS.value` refuses any other bigint.\n if (typeof value === \"bigint\") return signed(String(value));\n // `convertValueForSQLite` makes a boolean the number 1 or 0: REAL too.\n if (typeof value === \"boolean\") return value ? \"1.0\" : \"0.0\";\n if (value instanceof Uint8Array) return `X'${hex(value)}'`;\n return refuse(\"sqlite\", value);\n}\n\nconst LITERALS: Record<SqlDialect, (value: unknown) => string> = {\n postgresql: postgresLiteral,\n mysql: mysqlLiteral,\n sqlite: sqliteLiteral,\n};\n\n/**\n * `statement` as parameter-free text for `dialect`: the sibling of\n * `Sql.toStatement`, with each placeholder replaced by its value's literal.\n * No SQL text is read, and nothing is cached on or changed in the shared\n * fragments (`Sql.peek`).\n */\nexport function inlineLiterals(dialect: SqlDialect, statement: Sql): string {\n const literal = LITERALS[dialect];\n const { strings, values } = Sql.peek(statement);\n let text = strings[0]!;\n for (const [index, value] of values.entries())\n text += literal(value) + strings[index + 1]!;\n return text;\n}\n","/**\n * The body of a database view, for the migrations\n * (`docs/architecture/schema-views-plan.md` §3.1): the view's declared read,\n * compiled by the read compiler itself. {@link ViewBodyQueries} changes two\n * things of a read and nothing else: its root scalars are projected as\n * stored, under their column names, and its root states no order unless it\n * takes a window. Its documents (relations, `_count`, `_aggregate`) are\n * projected as a read carries them, so the client decodes a view's JSON\n * column with the decoder of the read that carried it. An aggregated view's\n * body is the read compiler's `groupBy`, its root projected as flat columns:\n * each grouped field as stored, each aggregate a column of its scalar.\n *\n * Only the migrations import this module: nothing the client or the engine\n * imports reaches it, so no application bundle carries it.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { FeatureNotSupportedError, UnsupportedOperationError } from \"@errors\";\nimport type { Schema } from \"@schema/hydration\";\nimport type { AnyModel } from \"@schema/model\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport { AUTO_VIEW_NAME_BYTES } from \"@schema/view/auto-names\";\nimport { type ViewAggregate, viewFacts } from \"@schema/view/facts\";\nimport type { Sql } from \"@sql\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { type KeptViewReasons, refuseUnkept } from \"./kept-view\";\nimport { aggregatedIdentifier, isCompact } from \"./shared/identifier\";\nimport {\n type OrderTerm,\n type PreparedAggregates,\n type PreparedProjection,\n refusesWhileDecoding,\n} from \"./shared/query\";\nimport {\n type Arguments,\n EngineSchema,\n entries,\n type ResolvedSchemaViews,\n} from \"./shared/schema\";\nimport { SqlQueries, type SqlSelectControls } from \"./shared/sql-queries\";\nimport { nameOf, scalarsOf, tableOf } from \"./shared/terms\";\n\n/**\n * How a view's dialect makes an expression one of the view's columns: what\n * its migration driver states, as it states each scalar's column type.\n */\nexport interface ViewColumnSql {\n /**\n * `expression`, an aggregate, as a column of `scalar`: cast to the type\n * the dialect stores that scalar's column in, wherever the cast keeps its\n * value.\n */\n viewCast(expression: Sql, scalar: Scalar): Sql;\n /**\n * A time step's period, a date, as the `YYYY-MM-DD` text `groupBy`\n * publishes for it: where the dialect has periods.\n */\n viewDay?(period: Sql): Sql;\n}\n\nexport interface ViewBodyContext {\n /** The schema the view and every model its query reads belong to. */\n readonly schema: Schema;\n /** The schema's resolved views, where the caller already holds them. */\n readonly resolved?: ResolvedSchemaViews;\n /**\n * The adapter the body is written with, made for this one body (its table\n * renderer is wrapped to note what the body reads). The dialect's migration\n * driver makes it (`MigrationDriver.viewWriter`): one fixed configuration\n * per dialect, so that every driver of a dialect writes one text, in the\n * estate's PostgreSQL schema.\n */\n readonly adapter: DatabaseAdapter;\n /** How the same driver makes an expression a column of the view. */\n readonly columns: ViewColumnSql;\n}\n\nexport interface ViewBody {\n /** The view's SELECT, bound values still in it. */\n readonly statement: Sql;\n /**\n * The decoder shape of a view row, what a client decodes: its scalars'\n * leaves and each JSON column's document, as JSON data. Members keep their\n * order (the order a carried document's array holds them in); a leaf drops\n * its scalar object and lists its enum values.\n */\n readonly shape: unknown;\n /**\n * Physical names of every table and view the statement reads, each once,\n * the source first: relation targets and junction tables, those its\n * filters read included.\n */\n readonly reads: readonly string[];\n}\n\n/** The period a refusal's message ends on, which the view's own adds again. */\nconst FINAL_STOP = /\\.$/;\n\n/**\n * A root whose query takes no window asks the page owner nothing, as a\n * related page that asked for none: no order, no limit.\n */\nconst UNORDERED: SqlSelectControls = { purpose: \"root\", unique: true };\n\n/** A query clause a view cannot hold, and why, named with the view. */\nfunction refuse(view: string, clause: string, reason: string): never {\n throw new UnsupportedOperationError(\n `View '${view}' cannot ${clause}: ${reason}.`,\n { meta: { model: view, feature: clause } }\n );\n}\n\nfunction refuseRoot(view: string, query: Arguments): void {\n if (query.cursor !== undefined)\n refuse(view, \"page from cursor\", \"not a row set\");\n if (query.take !== undefined && query.take < 0)\n refuse(view, \"take negative window\", \"not a row set\");\n if (query.take === undefined && query.orderBy !== undefined)\n refuse(view, \"order without take\", \"views are unordered\");\n if (query.take === undefined && query.skip !== undefined)\n refuse(view, \"skip without take\", \"views are unordered\");\n if (query.orderBy === undefined) return;\n for (const term of entries(query.orderBy))\n for (const direction of Object.values(term))\n if (isRecord(direction) && direction._distance !== undefined)\n refuse(view, \"order by distance\", \"binds per-call value\");\n}\n\n/**\n * The read compiler, writing a view's body. Built for one view, on an adapter\n * of its own.\n */\nclass ViewBodyQueries extends SqlQueries {\n readonly #view: string;\n /** The view's model: its columns' scalars. */\n readonly #model: AnyModel;\n readonly #columns: ViewColumnSql;\n /** The alias the root row is read under, set as the statement opens. */\n #root: string | undefined;\n /**\n * Set for a grouped root that takes no window: it states no order, as a\n * root of rows does. `groupBy` orders its groups by their grouped fields,\n * which a view would pay on every read for an order it does not have.\n */\n unordered = false;\n\n constructor(\n schema: EngineSchema,\n adapter: DatabaseAdapter,\n view: AnyModel,\n columns: ViewColumnSql\n ) {\n super(schema, adapter);\n this.#view = nameOf(view);\n this.#model = view;\n this.#columns = columns;\n }\n\n override rootAlias(): string {\n this.#root = super.rootAlias();\n return this.#root;\n }\n\n /**\n * The root's scalars as stored, each its bare column under its column\n * name: the view's column is the table's, so a filter, an order or an\n * aggregate on the view means what it means on the table. Every other\n * member, and every row below the root, is projected as a read projects it.\n */\n override lowerProjection(\n projection: PreparedProjection,\n alias?: string,\n visible = false\n ): Sql[] {\n if (alias === undefined || alias !== this.#root)\n return super.lowerProjection(projection, alias, visible);\n if (refusesWhileDecoding(projection))\n refuse(\n this.#view,\n \"read recursive or polymorphic relation\",\n \"decoding may refuse rows\"\n );\n const { model } = projection;\n const columns: Sql[] = [];\n for (const field of projection.fields) {\n if (field.kind === \"distance\")\n refuse(this.#view, \"select distance\", \"binds per-call value\");\n columns.push(\n field.kind === \"scalar\"\n ? this.adapter.identifiers.aliased(\n this.column(model, field.name, alias),\n this.columnName(model, field.name)\n )\n : super.lowerProjection({ ...projection, fields: [field] }, alias)[0]!\n );\n }\n return columns;\n }\n\n /** A grouped field at the root, as stored: the view's column is the table's. */\n override pC(model: AnyModel, field: string, alias?: string): Sql {\n return alias !== undefined && alias === this.#root\n ? this.column(model, field, alias)\n : super.pC(model, field, alias);\n }\n\n /**\n * A grouped root's aggregates, each its own column under the view's name\n * for it (`count`, `sumAmount`), read off the view's facts. A carried\n * aggregate below the root (a relation's `_aggregate`) is a read's.\n */\n protected override aggCols(\n model: AnyModel,\n selection: PreparedAggregates,\n alias: string\n ): [string, Sql][] {\n const aggregated = viewFacts(this.#model)?.aggregated;\n if (alias !== this.#root || aggregated === undefined)\n return super.aggCols(model, selection, alias);\n return Object.entries(aggregated.origins).flatMap(\n ([name, { aggregate, field }]): [string, Sql][] =>\n aggregate === undefined\n ? []\n : [[name, this.#aggregate(model, aggregate, field, alias, name)]]\n );\n }\n\n /**\n * One aggregate as a column of its scalar (`viewCast`). The provider's own\n * `SUM`: where a read splits a sum into parts its provider cannot\n * overflow, the view's column holds the sum its scalar holds. `MIN` and\n * `MAX` answer their column's type: a compact identifier is picked in the\n * text it travels in and stored back as its column stores it.\n */\n #aggregate(\n model: AnyModel,\n aggregate: ViewAggregate,\n field: string | undefined,\n alias: string,\n name: string\n ): Sql {\n const a = this.adapter;\n const column =\n field === undefined ? undefined : this.column(model, field, alias);\n const state =\n field === undefined ? undefined : scalarsOf(model)[field]?.[\"~\"].state;\n if (aggregate === \"_min\" || aggregate === \"_max\") {\n const { id } = this.leaf(model, field!);\n const operand = aggregatedIdentifier(a, id, column!);\n const boolean = state?.type === \"boolean\";\n const picked =\n aggregate === \"_min\"\n ? a.aggregates.min(operand, boolean)\n : a.aggregates.max(operand, boolean);\n return isCompact(id)\n ? a.expressions.idCast(picked, id.representation)\n : picked;\n }\n const value =\n aggregate === \"_count\"\n ? a.aggregates.count(column)\n : aggregate === \"_sum\"\n ? a.aggregates.sum(column!)\n : state?.decimal === undefined\n ? a.aggregates.avg(column!)\n : a.aggregates.decimalAvg(column!, state.decimal);\n return this.#columns.viewCast(value, scalarsOf(this.#model)[name]!);\n }\n\n protected override grpOrd(\n ...order: Parameters<SqlQueries[\"grpOrd\"]>\n ): OrderTerm[] {\n return this.unordered ? [] : super.grpOrd(...order);\n }\n\n /** Every caller's SQL operand is settled here before it is lowered. */\n override settle(_fragment: Sql): Sql {\n return refuse(\n this.#view,\n \"filter with SQL fragment\",\n \"views admit literals only\"\n );\n }\n}\n\nconst AUTO: KeptViewReasons = {\n stale: \"triggers only track source table writes\",\n unordered: \"triggers recompute on unordered rows\",\n distinct: \"triggers require one row per source row\",\n unfiltered: \"triggers do not filter groups\",\n noStep: \"triggers key groups by stored columns\",\n};\n\nfunction refuseAuto(\n view: AnyModel,\n source: AnyModel,\n admitted: Arguments,\n queries: SqlQueries\n): void {\n const name = nameOf(view);\n const at = (clause: string, reason: string): never =>\n refuse(name, clause, reason);\n const table = tableOf(view);\n if (table.length > AUTO_VIEW_NAME_BYTES)\n at(\n `use name '${table}' (> ${AUTO_VIEW_NAME_BYTES} chars)`,\n \"exceeds 63-byte limit\"\n );\n if (viewFacts(source) !== undefined)\n at(`read view '${nameOf(source)}'`, \"triggers require a base table\");\n refuseUnkept(\n view,\n admitted,\n admitted.where === undefined\n ? undefined\n : queries.prepareSelector(source, admitted.where).predicate,\n AUTO,\n at\n );\n const { columns, aggregated } = viewFacts(view)!;\n if (aggregated === undefined) {\n const primary = getModelKeyCatalog(source).addressableKeys.find(\n (key) => key.kind === \"primary\"\n );\n if (!primary?.fields.every((field) => columns.includes(field)))\n at(\n `omit primary key of '${nameOf(source)}'`,\n \"triggers locate rows by primary key\"\n );\n return;\n }\n const nullable = aggregated.by.find(\n (field) => aggregated.scalars[field]?.[\"~\"].state.nullable\n );\n if (nullable !== undefined)\n at(`group by nullable '${nullable}'`, \"triggers cannot key NULL groups\");\n}\n\n/**\n * Leaves as JSON data: a scalar object is the leaf's declaring scalar, which\n * the leaf's other members already state; a set of enum values is listed.\n */\nfunction asData(this: unknown, key: string, value: unknown): unknown {\n if (key === \"scalar\" && isRecord(this) && this.kind === \"scalar\")\n return undefined;\n return value instanceof Set ? [...value] : value;\n}\n\n/**\n * The body of `view`, a model of `context.schema` that `view` declared: its\n * declared query admitted as its source's `findMany` and compiled by the read\n * compiler without extension, row domain or call, refused where a view cannot\n * hold what it says (plan §2.2).\n */\nexport function viewBody(context: ViewBodyContext, view: AnyModel): ViewBody {\n const { source, query, aggregated } = viewFacts(view)!;\n const schema = new EngineSchema(context.schema, context.resolved);\n const { adapter, columns } = context;\n // Every persistent table a lowering names goes through this one renderer.\n const reads = new Set<string>([tableOf(source)]);\n const { identifiers, period } = adapter;\n adapter.identifiers = {\n ...identifiers,\n table: (name, alias) => {\n reads.add(name);\n return identifiers.table(name, alias);\n },\n };\n // A period is stored as the day a read publishes for it, not as the text\n // the read decodes that day from.\n if (period && columns.viewDay)\n Object.assign(adapter, {\n period: { ...period, text: (day: Sql) => columns.viewDay!(day) },\n });\n const name = nameOf(view);\n const queries = new ViewBodyQueries(schema, adapter, view, columns);\n const operation = aggregated ? \"groupBy\" : \"findMany\";\n // The refusal of a query its source does not take names the view, not\n // only the read of the source that would have taken it.\n let admitted: Arguments;\n try {\n admitted = schema.admit(source, operation, query);\n } catch (cause) {\n refuse(\n name,\n \"its source does not take\",\n cause instanceof Error ? cause.message : String(cause)\n );\n }\n refuseRoot(name, admitted);\n if (viewFacts(view)!.refresh === \"auto\")\n refuseAuto(view, source, admitted, queries);\n queries.unordered = aggregated !== undefined && admitted.take === undefined;\n let statement: Sql;\n try {\n statement =\n aggregated === undefined &&\n admitted.take === undefined &&\n admitted.distinct === undefined\n ? queries.select(source, admitted, undefined, UNORDERED).sql\n : queries.read(source, operation, admitted).query.sql;\n } catch (cause) {\n // What the read compiler refuses on this dialect (a time step outside\n // PostgreSQL) is refused with the view named.\n if (cause instanceof FeatureNotSupportedError)\n refuse(\n name,\n \"this database cannot read\",\n cause.message.replace(FINAL_STOP, \"\")\n );\n throw cause;\n }\n return {\n statement,\n shape: JSON.parse(\n JSON.stringify(queries.prepareProjection(view, {}).shape, asData)\n ),\n reads: [...reads],\n };\n}\n","/**\n * The definition of one declared view, for the snapshot the serializer\n * writes: its body compiled from the declared query, its identity, and what\n * it reads.\n *\n * The identity is what was DECLARED and what a client will DECODE, never the\n * body's text: the declared query, the table it reads, the decoder shape of a\n * view row (a JSON column holds a positional document, so a view written for\n * another shape would decode wrong in silence), and the relations the query\n * crosses, as resolved (a relation moved between two columns that both stay\n * changes the body and no column). An engine change that respells a read\n * therefore plans no migration. {@link VIEW_REVISION} is the lever for the\n * other case: a release whose bodies must all be written again raises it.\n *\n * What a body takes from a TABLE it reads is not here: its name, its columns\n * and its primary key (the order a body breaks ties by). A program that\n * changes one of those replaces the view around the change\n * (`withViewReplacements`, `view.ts`), which is the other half of this rule.\n *\n * A materialized view's declared indexes are not here either: the serializer\n * writes them beside the view, and a change to them is an index operation\n * that leaves the stored rows as they are. Its keys are here: each is a\n * unique index, which only fresh rows are known to satisfy.\n */\n\nimport { inlineLiterals } from \"../adapters/inline-literals\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { viewBody } from \"../query-engine/raptor3/view-body\";\nimport { fieldRefPayload, isFieldRef } from \"../schema/field-ref\";\nimport { jsonNullKindOf } from \"../schema/json-null\";\nimport { type AnyModel, Model } from \"../schema/model\";\nimport { getModelKeyCatalog } from \"../schema/model/keys\";\nimport { emptyRecord, put } from \"../schema/record\";\nimport type { AnyRelation } from \"../schema/relation\";\nimport type { ResolvedRelationIndex } from \"../schema/validation/relation-resolution\";\nimport { viewIsItsRead } from \"../schema/validation/rules/view\";\nimport type { ValidationContext } from \"../schema/validation/types\";\nimport { viewFacts } from \"../schema/view/facts\";\nimport { createResolvedSchemaRegistry } from \"../validation/builder\";\nimport { isRecord } from \"../validation/value-guards\";\nimport type {\n MigrationDriver,\n ViewWriteContext,\n ViewWriter,\n WrittenView,\n} from \"./drivers/base\";\nimport { domainHash, HASH_DOMAIN, utf8Bytes } from \"./identity\";\n\nexport interface ViewDefinition {\n /** Parameter-free SELECT in the driver's dialect: the view's body, without the wrapper and marker. */\n readonly sql: string;\n /** The view's identity: 40 lowercase hex characters. */\n readonly hash: string;\n /** Physical names of the tables and views the body reads, sorted, each once. */\n readonly dependsOn: readonly string[];\n /**\n * The view is declared `.materialized()` and the driver materializes views:\n * the database stores its rows. Part of the identity only then, so a view\n * that changes kind is replaced, and a dialect that keeps such a view\n * ordinary sees it as the same view.\n */\n readonly materialized: boolean;\n /**\n * The view is declared `.materialized({ refresh: \"auto\" })` and the\n * driver keeps such a view by triggers: a table its source's writes keep\n * current. Part of the identity only then; never with {@link materialized}.\n */\n readonly auto: boolean;\n}\n\n/** What the serializer holds when it asks for a view's definition. */\nexport interface ViewDefinitionContext {\n /** The schema's models and views, by key, hydrated. */\n readonly models: Readonly<Record<string, AnyModel>>;\n /** The resolved relation index the snapshot is serialized over. */\n readonly relations: ResolvedRelationIndex;\n /** The migration driver the snapshot is for (its dialect, target and namespace). */\n readonly migrationDriver: MigrationDriver;\n}\n\n/** Raised by a release that must write every view body again. */\nconst VIEW_REVISION = 1;\n/** Raised by a release that must write every `refresh: \"auto\"` view's triggers again. */\nconst AUTO_REVISION = 1;\n\n/** What every view of one schema is defined over, built once per resolved index. */\ninterface SchemaFacts {\n readonly registry: ReturnType<typeof createResolvedSchemaRegistry>;\n readonly validation: ValidationContext;\n}\nconst schemas = new WeakMap<ResolvedRelationIndex, SchemaFacts>();\n\nconst hex = (bytes: Uint8Array): string =>\n Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n/** What an operand callback is answered for a field it asks for, while a view's identity is read. */\nclass AskedField {\n readonly field: string;\n constructor(field: string) {\n this.field = field;\n }\n}\n\n/** The context an operand callback is called with here: each field answers its own name. */\nconst ASKED = {\n fields: new Proxy({}, { get: (_, field) => new AskedField(String(field)) }),\n};\n\nconst tagged = (tag: string, payload: unknown): Record<string, unknown> => {\n const record = emptyRecord<unknown>();\n put(record, tag, payload);\n return record;\n};\n\n/**\n * A declared query as identity data, without loss: two queries that differ\n * never read as one. What JSON has no spelling for is tagged, a record that\n * would read as a tag (one key, beginning with `$`, as in a schema document)\n * is wrapped in `$raw`, and a column named in place of a\n * value, by a field reference or by the callback that hands one out, is\n * `$field`. A callback is asked what it answers: by the time an identity is\n * read the body is compiled, so it answers a reference, an SQL fragment or\n * any other answer having been refused there. A reference compares two\n * columns of one row, so its field's name says all of it.\n */\nfunction identityValue(value: unknown): unknown {\n const jsonNull = jsonNullKindOf(value);\n if (jsonNull !== undefined) return tagged(\"$jsonNull\", jsonNull);\n if (typeof value === \"bigint\") return tagged(\"$bigint\", value.toString());\n if (typeof value === \"number\" && !Number.isFinite(value))\n return tagged(\"$number\", String(value));\n if (typeof value === \"function\") return identityValue(value(ASKED));\n if (typeof value !== \"object\" || value === null) return value;\n if (value instanceof Date) return tagged(\"$date\", String(value.getTime()));\n if (value instanceof Uint8Array) return tagged(\"$bytes\", hex(value));\n if (value instanceof AskedField) return tagged(\"$field\", value.field);\n if (isFieldRef(value)) return tagged(\"$field\", fieldRefPayload(value).field);\n if (Array.isArray(value)) return value.map(identityValue);\n // A value that states itself as JSON (a Decimal) is that statement, apart\n // from the plain value it would otherwise be taken for.\n if (\"toJSON\" in value && typeof value.toJSON === \"function\")\n return tagged(\"$json\", identityValue(value.toJSON()));\n const record = emptyRecord<unknown>();\n for (const [key, member] of Object.entries(value))\n if (member !== undefined) put(record, key, identityValue(member));\n const keys = Object.keys(record);\n return keys.length === 1 && keys[0]!.startsWith(\"$\")\n ? tagged(\"$raw\", record)\n : record;\n}\n\n/**\n * A resolved relation as identity data: a model is its table, and what a\n * relation or a scalar object holds beside its resolved facts is left out.\n * Schema objects only: the declared query is written apart, by\n * `identityValue`, so that no value of it is read as one.\n */\nfunction relationValue(_key: string, value: unknown): unknown {\n if (value instanceof Model) return { $table: value[\"~\"].names.sql };\n return typeof value === \"object\" && value !== null && \"~\" in value\n ? undefined\n : value;\n}\n\n/**\n * The relations `value`, a part of a view's query read at `model`, crosses:\n * each key that names a relation of the model it is read at, then what its\n * own value crosses at the relation's target. A key that names a scalar holds\n * a value, whatever is in it; any other key is a clause or an operator of the\n * same model. `_count: true` counts every to-many relation.\n */\nfunction crossedRelations(\n model: AnyModel,\n value: unknown,\n relations: ResolvedRelationIndex,\n crossed: Map<string, unknown>\n): void {\n if (Array.isArray(value)) {\n for (const member of value)\n crossedRelations(model, member, relations, crossed);\n return;\n }\n if (!isRecord(value)) return;\n const slots = relations.get(model);\n const state = model[\"~\"].state;\n const cross = (field: string, member: unknown): void => {\n const slot = slots?.get(field);\n if (slot === undefined) return;\n crossed.set(`${model[\"~\"].names.sql}.${field}`, slot);\n const { edge } = slot;\n // Where the relation leads: the other end of a pair (both ends of a self\n // relation are this model), or every model a variant slot may hold, and\n // its carrier from the other side.\n const targets =\n \"endpoints\" in edge\n ? edge.endpoints.map(({ source }) => source)\n : [\n edge.carrier.source,\n ...edge.members.flatMap((variant) =>\n \"targetModel\" in variant\n ? [variant.targetModel]\n : [variant.topology.source.model, variant.topology.target.model]\n ),\n ];\n // Asked at the slot's own model: a view reads its source's slot.\n const at = slot.slot.source;\n const self = targets.every((target) => target === at);\n for (const target of new Set(targets))\n if (self || target !== at)\n crossedRelations(target, member, relations, crossed);\n };\n for (const [key, member] of Object.entries(value)) {\n if (key in state.scalars) continue;\n if (key === \"_count\" && member === true) {\n for (const [field, relation] of Object.entries(\n state.relations as Record<string, AnyRelation>\n ))\n if (relation[\"~\"].state.cardinality === \"many\") cross(field, undefined);\n } else if (slots?.has(key)) cross(key, member);\n else crossedRelations(model, member, relations, crossed);\n }\n}\n\n/**\n * The body of `view` as `writer`'s database takes it: a SQL dialect's is the\n * view's declared read compiled by the read compiler itself on the writer's\n * adapter (`viewBody`), then written without parameters (`inlineLiterals`);\n * another driver writes its own.\n */\nexport function writeView(\n writer: ViewWriter,\n context: ViewWriteContext,\n view: AnyModel\n): WrittenView {\n if (\"write\" in writer) return writer.write(context, view);\n const body = viewBody(\n { ...context, adapter: writer.adapter, columns: writer.columns },\n view\n );\n return {\n sql: inlineLiterals(writer.dialect, body.statement),\n shape: body.shape,\n reads: body.reads,\n };\n}\n\n/**\n * The definition of `view` for `context.migrationDriver`'s dialect: its body\n * written without parameters, what it reads, and its identity.\n */\nexport function viewDefinition(\n view: AnyModel,\n context: ViewDefinitionContext\n): ViewDefinition {\n const { models, relations, migrationDriver } = context;\n const { dialect } = migrationDriver;\n const writer = migrationDriver.viewWriter();\n if (writer === undefined)\n throw new MigrationError(\n `The view \"${view[\"~\"].names.ts}\" cannot be migrated: VibORM creates no view on ${dialect}.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { feature: \"view\", dialect } }\n );\n let schema = schemas.get(relations);\n if (schema === undefined) {\n schema = {\n registry: createResolvedSchemaRegistry(models, relations),\n validation: {\n modelToName: new Map(\n Object.entries(models).map(([key, model]) => [model, key])\n ),\n tableToModels: new Map(),\n },\n };\n schemas.set(relations, schema);\n }\n // The view rules, whether or not the migration skipped its advice: a view\n // exists only where a migration created it, so this is where they bind.\n const issues = viewIsItsRead(\n new Map(Object.entries(models)),\n view[\"~\"].names.ts ?? \"\",\n view,\n schema.validation\n );\n if (issues.length > 0)\n throw new MigrationError(\n issues.map(({ code, message }) => `${message} (${code})`).join(\"; \"),\n VibORMErrorCode.INVALID_INPUT,\n { meta: { feature: \"view\", model: view[\"~\"].names.ts } }\n );\n const body = writeView(\n writer,\n {\n schema: models,\n resolved: { index: relations, registry: schema.registry },\n },\n view\n );\n const name = view[\"~\"].names.sql;\n const dependsOn = [...new Set(body.reads)]\n .filter((read) => read !== name)\n .sort();\n const facts = viewFacts(view)!;\n const crossed = new Map<string, unknown>();\n // An aggregated view's query names relations in its `where` alone: its\n // `_count: true` counts the source's rows, and the rest names fields.\n crossedRelations(\n facts.source,\n facts.aggregated ? facts.query.where : facts.query,\n relations,\n crossed\n );\n const auto =\n facts.refresh === \"auto\" && migrationDriver.keepsViewsByTriggers();\n const materialized =\n !auto && facts.materialized === true && migrationDriver.materializesViews();\n // A stored view's keys are unique on its stored rows.\n const keys = () =>\n getModelKeyCatalog(view).addressableKeys.map((key) => key.fields);\n const identity = JSON.stringify(\n {\n revision: VIEW_REVISION,\n source: facts.source[\"~\"].names.sql,\n query: JSON.stringify(identityValue(facts.query)),\n shape: body.shape,\n relations: [...crossed].sort(([left], [right]) =>\n left < right ? -1 : 1\n ),\n // Last and only when true: every ordinary view keeps its hash. A\n // materialized view holds its keys too, each of which is a unique\n // index on its stored rows: one its source gains would be built on the\n // rows of the last refresh, which the source's new constraint says\n // nothing of. Creating the view again computes them first. A view\n // kept by triggers holds them for the same reason, and the revision\n // of the triggers that keep it.\n ...(auto\n ? { auto: AUTO_REVISION, keys: keys() }\n : materialized\n ? { materialized, keys: keys() }\n : {}),\n },\n relationValue\n );\n return {\n sql: body.sql,\n hash: domainHash(HASH_DOMAIN.view, utf8Bytes(identity)).slice(0, 40),\n dependsOn,\n materialized,\n auto,\n };\n}\n\n/**\n * The fields of the source a filter names, read off its identity value: each\n * key that is a scalar of the source, and each field a reference names\n * (`$field`), however deep. A literal that spells one adds a field: the\n * set holds every field the filter reads, and may hold more.\n */\nfunction filterFields(\n scalars: Readonly<Record<string, unknown>>,\n value: unknown,\n into: Set<string>\n): void {\n if (Array.isArray(value)) {\n for (const member of value) filterFields(scalars, member, into);\n return;\n }\n if (!isRecord(value)) return;\n for (const [key, member] of Object.entries(value)) {\n if (key === \"$field\" && typeof member === \"string\") into.add(member);\n else if (key in scalars) into.add(key);\n filterFields(scalars, member, into);\n }\n}\n\n/**\n * The columns of its source a view of one table reads, sorted: each it\n * selects, groups by or aggregates, and each its filter names. A write that\n * changes none of them changes none of its rows.\n */\nexport function viewSourceReads(view: AnyModel): string[] {\n const { source, query, columns, aggregated } = viewFacts(view)!;\n const scalars = source[\"~\"].state.scalars;\n const fields = new Set<string>();\n for (const column of columns) {\n const field = aggregated ? aggregated.origins[column]?.field : column;\n if (field !== undefined) fields.add(field);\n }\n filterFields(scalars, identityValue(query.where), fields);\n return [...fields]\n .filter((field) => field in scalars)\n .map((field) => source[\"~\"].getFieldName(field).sql)\n .sort();\n}\n","import { selectManagedSnapshot } from \"./target\";\n/**\n * Model-to-SchemaSnapshot Serializer\n *\n * Converts VibORM model definitions into a database-agnostic SchemaSnapshot\n * that can be compared with the current database state.\n *\n * Database-specific logic is delegated to the MigrationDriver:\n * - Type mapping (mapScalarType)\n * - Default expressions (getDefaultExpression)\n * - Enum handling (capabilities.supportsNativeEnums, getEnumColumnType)\n */\n\nimport type { Dialect } from \"../drivers/types\";\nimport {\n MigrationError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport { lightModels } from \"../schema/json/light\";\nimport {\n type AnyModel,\n getModelKeyCatalog,\n getTableName as getModelTableName,\n isTotalIndex,\n type ModelState,\n} from \"../schema/model\";\nimport type { RelationSlot } from \"../schema/relation\";\nimport { automaticForeignKeyIndexName } from \"../schema/relation/helpers\";\nimport type { Scalar } from \"../schema/scalars/base\";\nimport { sqliteDateTimePhysicalForm } from \"../schema/scalars/datetime/physical\";\nimport {\n describeDecimalProviderLimitRefusal,\n findDecimalProviderLimitRefusal,\n} from \"../schema/scalars/decimal/provider-limits\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n foreignKeyOnDelete,\n junctionOnDelete,\n type ResolvedRelationEdge,\n type ResolvedRelationIndex,\n type ResolvedVariantJunctionEdge,\n type ResolvedVariantJunctionMember,\n type ResolvedVariantRowEdge,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { heldField, viewFacts } from \"../schema/view/facts\";\nimport type { MigrationDriver } from \"./drivers\";\nimport { declaredRawIndex, RAW_INDEX_TEMPLATE_KEY } from \"./raw-index\";\nimport type {\n AutoViewStorage,\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PolymorphicSnapshotStorage,\n PolymorphicToManySnapshotMember,\n PolymorphicToOneSnapshotMember,\n PolymorphicToOneStorageRegistryEntry,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n ViewDef,\n} from \"./types\";\nimport { viewDefinition, viewSourceReads } from \"./view-definition\";\n\n// =============================================================================\n// SERIALIZER\n// =============================================================================\n\nexport interface SerializeOptions {\n migrationDriver: MigrationDriver;\n}\n\n/** Translate the shared pure refusal into the migration boundary's error. */\nexport function assertMigrationDecimalDomainsFitProvider(\n models: Record<string, AnyModel>,\n dialect: Dialect\n): void {\n const refusal = findDecimalProviderLimitRefusal(models, dialect);\n if (refusal === undefined) return;\n throw new MigrationError(\n describeDecimalProviderLimitRefusal(refusal),\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\n/** One model's edges, bucketed at their anchors in declaration order. */\ninterface ModelEdges {\n readonly variants: ResolvedVariantEdgeRef[];\n readonly foreignKeys: ResolvedForeignKeyEdge[];\n}\n\ntype ResolvedVariantEdgeRef =\n | ResolvedVariantRowEdge\n | ResolvedVariantJunctionEdge;\ntype ResolvedForeignKeyEdge = Extract<\n ResolvedRelationEdge,\n { kind: \"foreignKey\" }\n>;\ntype ResolvedJunctionEdge = Extract<ResolvedRelationEdge, { kind: \"junction\" }>;\n\n/**\n * Stage the ONE derived edge iterator into the two emission buckets the\n * serializer already had (D4): per-model variant storage and foreign keys for\n * the model phase, and ordinary junctions for the phase that follows it.\n *\n * `resolvedEdges` yields each edge exactly once, at its canonical anchor, in\n * schema/model/field order — which is the order both phases already walked. No\n * topology is stored here and none is re-expanded (§11.5.9).\n */\nfunction stageEdges(index: ResolvedRelationIndex): {\n readonly byModel: ReadonlyMap<AnyModel, ModelEdges>;\n readonly junctions: readonly ResolvedJunctionEdge[];\n} {\n const byModel = new Map<AnyModel, ModelEdges>();\n const junctions: ResolvedJunctionEdge[] = [];\n const bucket = (model: AnyModel): ModelEdges => {\n const held = byModel.get(model);\n if (held) return held;\n const created: ModelEdges = { variants: [], foreignKeys: [] };\n byModel.set(model, created);\n return created;\n };\n for (const edge of resolvedEdges(index)) {\n if (edge.kind === \"junction\") {\n // A declared model's table is that model's: the loop over models owns it,\n // and each side's foreign key arrives as its own edge below.\n if (!edge.topology.declared) junctions.push(edge);\n continue;\n }\n if (edge.kind === \"foreignKey\") {\n bucket(edge.owner.source).foreignKeys.push(edge);\n continue;\n }\n bucket(edge.carrier.source).variants.push(edge);\n }\n return { byModel, junctions };\n}\n\n/** `(model, field)` is the whole contextual identity of a slot. */\nfunction isSlot(one: RelationSlot, other: RelationSlot): boolean {\n return one.source === other.source && one.field === other.field;\n}\n\n/** The endpoint an ordinary edge reaches FROM the given one. */\nfunction partnerOf(\n edge: ResolvedForeignKeyEdge | ResolvedJunctionEdge,\n from: RelationSlot\n): RelationSlot {\n const [first, second] = edge.endpoints;\n return isSlot(first, from) ? second : first;\n}\n\n/**\n * An index declared with `.index()` on a table or a materialized view, named\n * after the relation unless it names itself. `.map()` renames a column, so\n * the DDL names the column and not the TypeScript field, as the compound\n * uniques and the foreign-key columns do.\n */\nfunction declaredIndex(\n model: AnyModel,\n relation: string,\n index: ModelState[\"indexes\"][number]\n): IndexDef {\n return {\n name: index.options.name || `${relation}_${index.fields.join(\"_\")}_idx`,\n columns: index.fields.map((field) => model[\"~\"].getFieldName(field).sql),\n unique: index.options.unique ?? false,\n type: index.options.type,\n where: index.options.where,\n };\n}\n\n/**\n * A materialized view's indexes: a unique one for each key the view derives\n * from its source, named as a table's primary key and uniques are (each is\n * what `findUnique` can name, and one of them is what a concurrent refresh\n * needs), then each declared one. A view holds no constraint, so a key is an\n * index there.\n */\nfunction materializedViewIndexes(view: AnyModel, name: string): IndexDef[] {\n const column = (field: string) => view[\"~\"].getFieldName(field).sql;\n const keys = getModelKeyCatalog(view).addressableKeys.flatMap(\n (key): IndexDef[] =>\n key.fields.length === 0\n ? []\n : [\n {\n name:\n key.kind === \"primary\"\n ? `${name}_pkey`\n : `${name}_${key.name ?? column(key.fields[0]!)}_key`,\n columns: key.fields.map(column),\n unique: true,\n },\n ]\n );\n return [\n ...keys,\n ...view[\"~\"].state.indexes.map((index) => declaredIndex(view, name, index)),\n ];\n}\n\n/**\n * How a view kept by triggers is stored: a table of its columns, keyed by\n * its key (its source's primary key in a view of rows, its grouped columns\n * in a view of groups), and what its triggers read of its source. A column\n * that holds its source's values (a selected or grouped field, a least or a\n * greatest value) is the source's column under the view's name, so a value\n * is stored as its source stores it (an enum in its own type); any other\n * (a count, a sum, an average) is its own scalar's. None takes a default.\n */\nfunction autoViewStorage(\n view: AnyModel,\n name: string,\n columnOf: (\n model: AnyModel,\n tableName: string,\n fieldName: string,\n scalar: Scalar\n ) => ColumnDef\n): AutoViewStorage {\n const facts = viewFacts(view)!;\n const { source, aggregated } = facts;\n const scalars: Record<string, Scalar> = view[\"~\"].state.scalars;\n const sourceScalars: Record<string, Scalar> = source[\"~\"].state.scalars;\n const sourceTable = source[\"~\"].names.sql!;\n const columnName = (field: string) => view[\"~\"].getFieldName(field).sql!;\n const columns = facts.columns\n .filter((field) => scalars[field] !== undefined)\n .map((field): ColumnDef => {\n const scalar = scalars[field]!;\n const held = heldField(facts, field);\n const stored =\n held === undefined\n ? columnOf(view, name, field, scalar)\n : columnOf(source, sourceTable, held, sourceScalars[held]!);\n const column = columnName(field);\n return {\n ...stored,\n name: column,\n // A CHECK naming the source's column names one the view's table\n // holds under another name (SQLite's enum).\n type:\n stored.name === column || !stored.type.includes(\"CHECK(\")\n ? stored.type\n : columnOf(view, name, field, scalar).type,\n nullable: scalar[\"~\"].state.nullable,\n default: undefined,\n autoIncrement: false,\n };\n });\n const key = aggregated\n ? aggregated.by\n : (getModelKeyCatalog(source).addressableKeys.find(\n (candidate) => candidate.kind === \"primary\"\n )?.fields ?? []);\n return {\n source: sourceTable,\n columns,\n key: key.map(columnName),\n sourceKey: key.map((field) => source[\"~\"].getFieldName(field).sql!),\n grouped: aggregated !== undefined,\n reads: viewSourceReads(view),\n };\n}\n\n/**\n * Refuses a view kept by triggers whose stored column (key or indexed) is\n * narrowed relative to its source: MySQL keys or indexes a string column as\n * `VARCHAR(191)` where an unindexed source column is `TEXT`, so a longer\n * value written to the source would fail inside the trigger or initial fill.\n */\nfunction refuseNarrowedColumns(\n view: string,\n model: AnyModel,\n storage: AutoViewStorage,\n tables: readonly TableDef[]\n): void {\n const facts = viewFacts(model)!;\n const source = tables.find(({ name }) => name === storage.source);\n if (source === undefined) return;\n for (const field of facts.columns) {\n const held = heldField(facts, field);\n if (held === undefined) continue;\n const column = model[\"~\"].getFieldName(field).sql;\n const sourceColumn = facts.source[\"~\"].getFieldName(held).sql;\n const target = storage.columns.find(({ name }) => name === column);\n const read = source.columns.find(({ name }) => name === sourceColumn)?.type;\n if (read === undefined || target === undefined || target.type === read)\n continue;\n // Match a narrower source column (e.g. an indexed VARCHAR(191) FK) so a\n // later `.index()` on the view never hits a bare CREATE INDEX on TEXT.\n if (target.type.toUpperCase() === \"TEXT\") {\n target.type = read;\n continue;\n }\n if (!read.toUpperCase().includes(\"TEXT\")) continue;\n throw new UnsupportedOperationError(\n `Auto view '${view}' column '${column}' (${target.type}) narrower than source '${storage.source}.${sourceColumn}' (${read}).`,\n { meta: { model: view, feature: \"auto view\" } }\n );\n }\n}\n\n/**\n * Serializes a collection of VibORM models into a SchemaSnapshot\n */\nexport function serializeModels(\n models: Record<string, AnyModel>,\n options: SerializeOptions\n): SchemaSnapshot {\n hydrateSchemaNames(models);\n assertMigrationDecimalDomainsFitProvider(\n models,\n options.migrationDriver.dialect\n );\n return serializeResolvedModels(\n models,\n options.migrationDriver,\n resolveSchemaOrThrow(models)\n );\n}\n\n/** Internal composition seam for a boundary that already owns resolution. */\nexport function serializeResolvedModels(\n models: Record<string, AnyModel>,\n migrationDriver: MigrationDriver,\n index: ResolvedRelationIndex\n): SchemaSnapshot {\n const { byModel, junctions } = stageEdges(index);\n const tables: TableDef[] = [];\n const enums: EnumDef[] = [];\n const enumsSet = new Set<string>();\n const polymorphicStorage: PolymorphicSnapshotStorage[] = [];\n // One registry for EVERY junction-shaped table — polymorphic member\n // junctions (registered by the model loop below, model iteration order then\n // member declaration order) and ordinary many-to-many junctions (registered\n // by the walk that follows) — so the \"one table name, one definition\"\n // invariant covers both routes through the same map.\n const junctionTables = new Map<string, { def: TableDef; pairKey: string }>();\n // A view holds no table, column, key or foreign key: its definition, and a\n // materialized view its indexes.\n const views: ViewDef[] = [];\n // Each view kept by triggers, whose keepers are known once every table is.\n const autoViews: [ViewDef, AutoViewStorage, AnyModel][] = [];\n\n /**\n * The column of `model`'s scalar `fieldName` in its table `tableName`: a\n * table's, or the column a view kept by triggers stores the source's in.\n */\n const columnOf = (\n model: AnyModel,\n tableName: string,\n fieldName: string,\n scalar: Scalar\n ): ColumnDef => {\n const scalarState = scalar[\"~\"].state;\n // Use model's nameRegistry for column name resolution (supports field reuse)\n const columnName = model[\"~\"].getFieldName(fieldName).sql;\n\n // Handle enum types (only for databases that support native enums)\n let columnType: string;\n // The LIST representation is decided before enum identity is spelled. A\n // dialect with native arrays keeps both — `enumname[]` — while the others\n // store the list in the same container every other list uses, where an\n // element type has no expression at all: an inline `ENUM(...)` or a\n // `TEXT CHECK(col IN ...)` describes ONE member, so spelling it for a\n // list produces a column that refuses every value the field can hold.\n const spellsEnumColumn =\n scalarState.type === \"enum\" &&\n (scalarState.array !== true ||\n migrationDriver.capabilities.supportsNativeArrays);\n if (spellsEnumColumn) {\n const enumScalar = scalar as any;\n const enumValues = enumScalar.enumValues as string[] | undefined;\n\n if (migrationDriver.capabilities.supportsNativeEnums && enumValues) {\n // Use explicit enum name if provided, otherwise auto-generate\n const enumName =\n scalarState.enumName && migrationDriver.dialect === \"postgresql\"\n ? scalarState.enumName\n : migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues\n );\n\n const previousEnum = enums.find((item) => item.name === enumName);\n if (\n previousEnum &&\n JSON.stringify(previousEnum.values) !== JSON.stringify(enumValues)\n )\n throw new MigrationError(\n `Enum type \"${enumName}\" is declared with incompatible values`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n if (!enumsSet.has(enumName)) {\n enums.push({\n name: enumName,\n values: enumValues,\n });\n enumsSet.add(enumName);\n }\n columnType = scalarState.array ? `${enumName}[]` : enumName;\n } else {\n // Fall back to driver's default enum column type\n columnType = migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues || []\n );\n }\n } else {\n // A foreign key's identifier domain is DERIVED from the key it\n // references, so it is read against the model through the same\n // resolved index this serialization is already built from.\n columnType = migrationDriver.mapScalarType(\n scalar,\n scalarState,\n idDomainOf(model, fieldName, index)\n );\n }\n\n const columnDef: ColumnDef = {\n name: columnName,\n type: columnType,\n nullable: scalarState.nullable,\n default: migrationDriver.getDefaultExpression(scalar, scalarState),\n autoIncrement: scalarState.autoGenerate?.kind === \"increment\",\n // Carried by REFERENCE off the resolved scalar, never rebuilt: the\n // frozen descriptor is the one source of truth, and the physical type\n // above is derived from it. On SQLite that type is `INTEGER` or `TEXT`\n // whatever the domain is, so without this the differ would see no\n // change when the domain moved.\n decimal: scalarState.decimal,\n geoPointEncoding:\n migrationDriver.dialect === \"sqlite\" && scalarState.type === \"point\"\n ? \"binary64\"\n : undefined,\n dateTime:\n migrationDriver.dialect === \"sqlite\" &&\n scalarState.type === \"datetime\" &&\n scalarState.array !== true\n ? sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType)\n : undefined,\n };\n\n return columnDef;\n };\n\n for (const [modelName, model] of Object.entries(models)) {\n // Every migration path states its schema here, so this is the one refusal.\n if (lightModels.has(model))\n throw new MigrationError(\n `Model \"${modelName}\" is from a light schema; introspect without light to migrate.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n const modelState = model[\"~\"].state;\n const tableName =\n model[\"~\"].names.sql || modelState.tableName || modelName.toLowerCase();\n if (viewFacts(model) !== undefined) {\n const definition = viewDefinition(model, {\n models,\n relations: index,\n migrationDriver,\n });\n // A view kept by triggers is a table keyed by the view's key: its\n // primary key is that key, and its other keys are unique indexes.\n const storage = definition.auto\n ? autoViewStorage(model, tableName, columnOf)\n : undefined;\n // Through the driver's own pass over a table's indexes, so a view's\n // index is named and typed as a table's would be.\n // Its columns go through it too, as a table's do: MySQL keys a string\n // column it indexes in a VARCHAR.\n const stored =\n definition.materialized || storage\n ? migrationDriver.finalizeTable({\n name: tableName,\n columns: storage?.columns ?? [],\n primaryKey: storage ? { columns: storage.key } : undefined,\n indexes: materializedViewIndexes(model, tableName).filter(\n (index) =>\n index.columns.join(\"\\u0000\") !== storage?.key.join(\"\\u0000\")\n ),\n foreignKeys: [],\n uniqueConstraints: [],\n })\n : undefined;\n const indexes = stored?.indexes ?? [];\n if (storage && stored) storage.columns = stored.columns;\n const def: ViewDef = {\n name: tableName,\n hash: definition.hash,\n sql: definition.sql,\n dependsOn: [...definition.dependsOn],\n ...(definition.materialized ? { materialized: true } : {}),\n ...(indexes.length > 0 ? { indexes } : {}),\n };\n views.push(def);\n if (storage) autoViews.push([def, storage, model]);\n continue;\n }\n\n const columns: ColumnDef[] = [];\n const indexes: IndexDef[] = [];\n const foreignKeys: ForeignKeyDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n const relationStorage: Record<\n string,\n PolymorphicToOneStorageRegistryEntry\n > = {};\n let primaryKey: PrimaryKeyDef | undefined;\n const pkColumns: string[] = [];\n\n // Process scalars\n for (const [fieldName, scalar] of Object.entries<Scalar>(\n modelState.scalars\n )) {\n const scalarState = scalar[\"~\"].state;\n const columnDef = columnOf(model, tableName, fieldName, scalar);\n const columnName = columnDef.name;\n columns.push(columnDef);\n\n // Track primary key columns\n if (scalarState.isId) {\n pkColumns.push(columnName);\n }\n\n // Handle unique constraints on individual fields\n if (scalarState.isUnique && !scalarState.isId) {\n uniqueConstraints.push({\n name: `${tableName}_${columnName}_key`,\n columns: [columnName],\n });\n }\n }\n\n // Handle compound primary key\n if (modelState.compoundId) {\n const firstKey = Object.keys(modelState.compoundId)[0];\n const compoundIdSchema = firstKey\n ? modelState.compoundId[firstKey]\n : undefined;\n if (compoundIdSchema?.entries) {\n pkColumns.push(\n ...Object.keys(compoundIdSchema.entries).map(\n (field) => model[\"~\"].getFieldName(field).sql\n )\n );\n }\n }\n\n // Set primary key. `WITHOUT ROWID` is SQLite's alone, and SQLite's\n // AUTOINCREMENT is a rowid's: the pair is refused here, before any\n // migration names the table, and never on a dialect that ignores it.\n const withoutRowid =\n model[\"~\"].withoutRowid && migrationDriver.dialect === \"sqlite\";\n const incremented = columns.find((column) => column.autoIncrement);\n if (withoutRowid && incremented)\n throw new MigrationError(\n `\"${modelName}\" withoutRowid incompatible with .increment() on \"${incremented.name}\".`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: modelName, field: incremented.name } }\n );\n if (withoutRowid && pkColumns.length === 0)\n throw new MigrationError(\n `\"${modelName}\" withoutRowid requires a primary key.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: modelName } }\n );\n const nullableKey = columns.find(\n (column) => column.nullable && pkColumns.includes(column.name)\n );\n if (nullableKey)\n throw new MigrationError(\n `\"${modelName}.${nullableKey.name}\" PK column must be NOT NULL.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: modelName, field: nullableKey.name } }\n );\n if (pkColumns.length > 0) {\n primaryKey = {\n columns: pkColumns,\n name: `${tableName}_pkey`,\n ...(withoutRowid ? { withoutRowid: true as const } : {}),\n };\n }\n\n // Handle compound unique constraints\n const compoundUniques: ModelState[\"compoundUniques\"] =\n modelState.compoundUniques;\n if (compoundUniques) {\n for (const [constraintName, schema] of Object.entries(compoundUniques)) {\n if (schema?.entries) {\n uniqueConstraints.push({\n name: `${tableName}_${constraintName}_key`,\n columns: Object.keys(schema.entries).map(\n (field) => model[\"~\"].getFieldName(field).sql\n ),\n });\n }\n }\n }\n\n // Process indexes from model state. One resolution of the columns serves\n // both readers: the CREATE INDEX, and the foreign-key index's coverage\n // decision, which has to compare the same names or it emits a duplicate.\n const declaredIndexColumns: string[][] = [];\n for (const indexDef of modelState.indexes) {\n const declared = declaredIndex(model, tableName, indexDef);\n indexes.push(declared);\n if (isTotalIndex(declared)) {\n declaredIndexColumns.push(declared.columns);\n }\n }\n\n // A raw index is never a key and never covers a foreign key: its text may\n // index an expression of the columns it names, or not in their order. It is\n // listed before the foreign-key indexes so that an automatic one yields\n // its name to it. A dialect it has no text for has no such index.\n const templateKey = RAW_INDEX_TEMPLATE_KEY[migrationDriver.dialect];\n for (const rawIndex of model[\"~\"].rawIndexes) {\n const template = templateKey && rawIndex.templates[templateKey];\n if (template === undefined) continue;\n // I002 sees explicit names only; an `.index()` without one takes its\n // name here, and two indexes under one name fail the second CREATE.\n if (indexes.some(({ name }) => name === rawIndex.name))\n throw new MigrationError(\n `Raw index \"${modelName}.${rawIndex.name}\" has the name of another index.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: modelName, indexName: rawIndex.name } }\n );\n indexes.push(\n declaredRawIndex(\n modelName,\n rawIndex.name,\n template,\n migrationDriver.dialect,\n (field) =>\n Object.hasOwn(modelState.scalars, field)\n ? model[\"~\"].getFieldName(field).sql\n : undefined\n )\n );\n }\n\n // Variant storage is relation-owned, so it never appears in the public\n // scalar map. The RESOLVED CARRIER EDGE is the single source for the\n // row-held private columns and index, the collection member junction\n // tables, and generated-file member history.\n const modelEdges = byModel.get(model) ?? { variants: [], foreignKeys: [] };\n for (const edge of modelEdges.variants) {\n if (edge.kind === \"variantJunctionCarrier\") {\n const members: PolymorphicToManySnapshotMember[] = [];\n for (const member of edge.members) {\n const memberDef = serializeMemberJunction(\n model,\n tableName,\n member,\n migrationDriver,\n index\n );\n // pairName is always set for a member junction: the resolved topology\n // is built exclusively by the gate, which passes\n // `${model}.${relation}.${publicType}` — already distinct from every\n // ordinary pairKey spelling.\n const pairKey = member.topology.pairName!;\n const existing = junctionTables.get(memberDef.name);\n if (\n existing &&\n (existing.pairKey !== pairKey ||\n JSON.stringify(existing.def) !== JSON.stringify(memberDef))\n ) {\n throw junctionCollisionError(memberDef.name);\n }\n if (!existing) {\n junctionTables.set(memberDef.name, { def: memberDef, pairKey });\n }\n\n const memberTarget = member.topology.target.model;\n const targetModelName = memberTarget[\"~\"].names.ts;\n members.push({\n publicType: member.variant,\n storedType: member.entry.storedValue,\n targetTable: getModelTableName(\n memberTarget,\n targetModelName?.toLowerCase() ?? \"unknown\"\n ),\n memberJunctionTable: member.topology.table,\n inverseCardinality: member.uniqueTarget ? \"one\" : \"many\",\n });\n }\n polymorphicStorage.push({\n ownerTable: tableName,\n relation: edge.carrier.field,\n kind: \"toMany\",\n members,\n });\n continue;\n }\n const storage = edge.storage;\n const typeScalarState = storage.typeColumn.scalar[\"~\"].state;\n const idScalarState = storage.idColumn.scalar[\"~\"].state;\n columns.push(\n {\n name: storage.typeColumn.name,\n type: migrationDriver.mapScalarType(\n storage.typeColumn.scalar,\n typeScalarState\n ),\n nullable: storage.typeColumn.nullable,\n },\n {\n name: storage.idColumn.name,\n // The carrier's id column holds every variant's KEY, and a key's\n // domain may be DERIVED, so the column names the key it stands in for\n // and that key is resolved against the index. Every variant agrees on\n // the answer or this storage does not exist (P002).\n type: migrationDriver.mapScalarType(\n storage.idColumn.scalar,\n idScalarState,\n storage.idColumn.reference === undefined\n ? undefined\n : idDomainOf(\n storage.idColumn.reference.model,\n storage.idColumn.reference.field,\n index\n )\n ),\n nullable: storage.idColumn.nullable,\n }\n );\n indexes.push({\n name: storage.indexName,\n columns: [storage.typeColumn.name, storage.idColumn.name],\n unique: edge.uniqueTarget,\n });\n // The physical facts stay in the TableDef above where the structural\n // differ owns them; the registry annotates which of those parts are\n // relation-owned, keyed by the storage ref the metadata entry carries.\n relationStorage[storage.typeColumn.name] = {\n kind: \"polymorphicToOne\",\n typeColumn: storage.typeColumn.name,\n idColumn: storage.idColumn.name,\n index: storage.indexName,\n };\n\n const members: PolymorphicToOneSnapshotMember[] = [];\n for (const member of edge.members) {\n const targetModelName = member.targetModel[\"~\"].names.ts;\n members.push({\n publicType: member.variant,\n storedType: member.entry.storedValue,\n targetTable: getModelTableName(\n member.targetModel,\n targetModelName?.toLowerCase() ?? \"unknown\"\n ),\n });\n }\n polymorphicStorage.push({\n ownerTable: tableName,\n relation: edge.carrier.field,\n kind: \"toOne\",\n storageRef: storage.typeColumn.name,\n members,\n });\n }\n\n // A UNIQUE foreign key gets a unique constraint at the bottom of the\n // relation loop, and that constraint is an index — so it covers the\n // foreign-key index exactly as a declared unique does. It is collected HERE,\n // before the loop, because `uniqueConstraints` grows INSIDE it: one model may\n // name the same columns from a plural and from a singular edge (legal, and\n // measured through `serializeModels`), and reading the half-built list made\n // the answer depend on which relation the schema happened to spell first —\n // `many` before `one` emitted the redundant index, `one` before `many` did\n // not. The condition mirrors the branch that pushes the constraint, so this\n // claims coverage only where the constraint follows.\n const oneToOneFkColumns: string[][] = [];\n for (const edge of modelEdges.foreignKeys) {\n if (!edge.unique) continue;\n oneToOneFkColumns.push(\n edge.reference.members.map(\n (member) => model[\"~\"].getFieldName(member.foreignField).sql\n )\n );\n }\n\n // Process foreign keys. ONE edge per stored reference, at its OWNER, in the\n // owner's declaration order — the gate decided which endpoint stores the\n // reference, so there is no family label to test and no inverse to discover.\n for (const edge of modelEdges.foreignKeys) {\n const targetSlot = partnerOf(edge, edge.owner);\n const targetModel = targetSlot.source;\n const targetModelState = targetModel[\"~\"].state;\n const targetTableName =\n targetModel[\"~\"].names.sql ||\n targetModelState.tableName ||\n edge.owner.field.toLowerCase();\n\n // Resolve TS field names to actual column names (.map() support)\n const fkFields = edge.reference.members.map(\n (member) => member.foreignField\n );\n const fkColumns = fkFields.map(\n (field) => model[\"~\"].getFieldName(field).sql\n );\n const referencedColumns = edge.reference.members.map(\n (member) => targetModel[\"~\"].getFieldName(member.referencedField).sql\n );\n\n // Prisma parity: without an explicit .onDelete(), a stored reference whose\n // every local member is nullable defaults to SET NULL and a required one to\n // RESTRICT, so deletes behave identically across databases (MySQL checks\n // self-referencing FKs row-by-row where PG/SQLite validate at statement\n // end). The rule has one owner, `foreignKeyOnDelete`, which the engine's\n // referential requirement reads too.\n foreignKeys.push({\n name: `${tableName}_${fkColumns.join(\"_\")}_fkey`,\n columns: fkColumns,\n referencedTable: targetTableName,\n referencedColumns,\n onDelete: foreignKeyOnDelete(edge),\n onUpdate: edge.reference.onUpdate ?? \"noAction\",\n });\n\n // The inverse of a plural stored reference is to-many: every include,\n // relation filter and nested-write locate reads this table through the FK\n // columns. MySQL/InnoDB indexes an FK constraint by itself;\n // PostgreSQL and SQLite do not, so serialize the index on every\n // dialect — one snapshot shape for the differ, and on MySQL the\n // explicit index takes the place of the implicit one. A UNIQUE FK\n // needs nothing here: the unique constraint below is its index.\n if (edge.unique) {\n // 1:1 FK must be unique at the DB level, or it degrades to N:1\n const fkKey = [...fkColumns].sort().join(\",\");\n const alreadyUnique =\n [...pkColumns].sort().join(\",\") === fkKey ||\n uniqueConstraints.some(\n (u) => [...u.columns].sort().join(\",\") === fkKey\n ) ||\n indexes.some(\n (i) =>\n i.unique &&\n isTotalIndex(i) &&\n [...i.columns].sort().join(\",\") === fkKey\n );\n if (!alreadyUnique) {\n uniqueConstraints.push({\n name: `${tableName}_${fkColumns.join(\"_\")}_key`,\n columns: fkColumns,\n });\n }\n continue;\n }\n\n // The primary key, every unique constraint and every declared index\n // is backed by an index on all three dialects, and an index serves\n // any prefix of its columns — so a FK index over such a prefix\n // would only duplicate one the database already has.\n const coveringColumns = [\n pkColumns,\n ...uniqueConstraints.map((unique) => unique.columns),\n ...oneToOneFkColumns,\n ...declaredIndexColumns,\n ];\n const alreadyIndexed = coveringColumns.some((columns) =>\n fkColumns.every((column, position) => columns[position] === column)\n );\n if (alreadyIndexed) continue;\n // An index the schema declares over exactly these columns but\n // does not cover them — a partial index — auto-names itself the\n // way this one does, and a database keeps one index per name. So\n // the automatic index falls back on the name of the constraint it\n // serves. Only a schema that has no foreign-key index today can\n // take the fallback, so no database that already holds the index\n // is renamed into a drop and a create.\n //\n // A schema may of course have spent BOTH names on indexes of its\n // own — `.index([...], { name: \"<table>_<cols>_fkey_idx\" })` is\n // legal. Then this index has no name left to take, and pushing it\n // anyway put two entries under one name into the snapshot: the\n // differ emitted two `CREATE INDEX` and the second failed the\n // whole push (measured on better-sqlite3: `index\n // zz_fb_kid_ownerId_fkey_idx already exists`). The index is a read\n // optimization, not a correctness requirement, so it yields to the\n // names the schema declared.\n const name = automaticForeignKeyIndexName(\n tableName,\n fkColumns,\n new Set(indexes.map((index) => index.name))\n );\n if (name !== undefined) {\n indexes.push({ name, columns: fkColumns, unique: false });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n // Key omitted when empty so ordinary tables keep their exact shape.\n ...(Object.keys(relationStorage).length > 0 ? { relationStorage } : {}),\n });\n }\n\n // ==========================================================================\n // ORDINARY JUNCTION TABLES\n //\n // One edge per resolved pair, at `endpoints[0]` — the canonically first\n // endpoint, which is the very endpoint the old two-model walk registered from.\n // A member VIEW of a variant carrier never appears here: the gate resolved\n // that slot onto its carrier's edge, so the skip that used to rescan for a\n // compatible binding is now structural.\n // ==========================================================================\n for (const edge of junctions) {\n const sourceSlot = edge.endpoints[0];\n const model = sourceSlot.source;\n const modelName = model[\"~\"].names.ts;\n const sourceTableName =\n model[\"~\"].names.sql ||\n model[\"~\"].state.tableName ||\n (modelName ?? \"\").toLowerCase();\n const targetSlot = partnerOf(edge, sourceSlot);\n const targetModel = targetSlot.source;\n const targetModelName = targetModel[\"~\"].names.ts;\n if (!(modelName && targetModelName)) {\n throw new Error(\n `Target model for relation \"${sourceSlot.field}\" has no name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n const targetTableName = targetModel[\"~\"].names.sql;\n if (!targetTableName) {\n throw new Error(\n `Target model \"${targetModelName}\" has no SQL table name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n\n const topology = edge.topology;\n const [firstKey, secondKey] = topology.sourceIsFirst\n ? [modelName.toLowerCase(), targetModelName.toLowerCase()]\n : [targetModelName.toLowerCase(), modelName.toLowerCase()];\n const junctionDef = buildJunctionTable({\n sourceModel: model,\n sourceTable: sourceTableName,\n targetModel,\n targetTable: targetTableName,\n topology,\n sourceActions: {\n onDelete: junctionOnDelete(topology.source),\n onUpdate: topology.source.onUpdate ?? \"cascade\",\n },\n targetActions: {\n onDelete: junctionOnDelete(topology.target),\n onUpdate: topology.target.onUpdate ?? \"cascade\",\n },\n migrationDriver,\n relations: index,\n });\n\n // Both sides of a pair serialize identically after canonicalization, so\n // a mismatch means two different relation pairs collide on one table.\n // Pair identity (models + relation name) catches collisions even when\n // the column defs happen to be byte-identical.\n const pairKey = `${firstKey}::${secondKey}::${topology.pairName ?? \"\"}`;\n const existing = junctionTables.get(topology.table);\n if (existing) {\n if (\n existing.pairKey !== pairKey ||\n JSON.stringify(existing.def) !== JSON.stringify(junctionDef)\n ) {\n throw junctionCollisionError(topology.table);\n }\n continue;\n }\n junctionTables.set(topology.table, { def: junctionDef, pairKey });\n }\n\n // Append junction tables to the tables array\n for (const { def } of junctionTables.values()) {\n tables.push(migrationDriver.markJunction?.(def) ?? def);\n }\n\n const finalized = tables.map((table) => migrationDriver.finalizeTable(table));\n for (const [view, storage, model] of autoViews) {\n // MySQL keys or indexes a string column in a narrower type than it stores\n // an unindexed one in; elsewhere a column keeps its source's type.\n if (migrationDriver.dialect === \"mysql\")\n refuseNarrowedColumns(view.name, model, storage, finalized);\n const cascades = migrationDriver.autoViewCascades(\n view.name,\n storage,\n finalized\n );\n const kept = cascades?.length ? { ...storage, cascades } : storage;\n view.auto = {\n objects: migrationDriver.autoViewObjects(view.name, kept),\n storage: kept,\n };\n }\n const snapshot: SchemaSnapshot = {\n tables: finalized,\n enums: enums.length > 0 ? enums : undefined,\n ...(polymorphicStorage.length > 0 ? { polymorphicStorage } : {}),\n // Absent without a view, so such a snapshot keeps its bytes and hash.\n ...(views.length > 0\n ? {\n views: views.sort((a, b) =>\n a.name < b.name ? -1 : Number(a.name > b.name)\n ),\n }\n : {}),\n };\n return migrationDriver.target\n ? selectManagedSnapshot(snapshot, migrationDriver.target, true)\n : snapshot;\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nconst junctionCollisionError = (tableName: string) =>\n new Error(\n `Junction table \"${tableName}\" is shared by distinct relation pairs; use distinct .name() or .through().`\n );\n\ntype JunctionActions = {\n readonly onDelete: ForeignKeyDef[\"onDelete\"];\n readonly onUpdate: ForeignKeyDef[\"onUpdate\"];\n};\n\nconst CASCADE_ACTIONS: JunctionActions = {\n onDelete: \"cascade\",\n onUpdate: \"cascade\",\n};\n\nfunction buildJunctionTable({\n sourceModel,\n sourceTable,\n targetModel,\n targetTable,\n topology,\n sourceActions,\n targetActions,\n uniqueTargetName,\n migrationDriver,\n relations,\n}: {\n sourceModel: AnyModel;\n sourceTable: string;\n targetModel: AnyModel;\n targetTable: string;\n topology:\n | ResolvedJunctionEdge[\"topology\"]\n | ResolvedVariantJunctionMember[\"topology\"];\n sourceActions: JunctionActions;\n targetActions: JunctionActions;\n uniqueTargetName?: () => string;\n migrationDriver: MigrationDriver;\n relations: ResolvedRelationIndex;\n}): TableDef {\n const zip = (\n model: AnyModel,\n members: readonly { readonly junctionField: string }[]\n ) => {\n const pks = getPrimaryKeyFieldDefs(model, migrationDriver, relations);\n return members.map((member, index) => ({\n column: member.junctionField,\n pk: pks[index]!,\n }));\n };\n const sourceMembers = zip(sourceModel, topology.source.members);\n const targetMembers = zip(targetModel, topology.target.members);\n const sourceSide = {\n members: sourceMembers,\n table: sourceTable,\n actions: sourceActions,\n };\n const targetSide = {\n members: targetMembers,\n table: targetTable,\n actions: targetActions,\n };\n const [first, second] = topology.sourceIsFirst\n ? [sourceSide, targetSide]\n : [targetSide, sourceSide];\n const firstColumns = first.members.map((member) => member.column);\n const secondColumns = second.members.map((member) => member.column);\n const makeFk = (\n side: typeof first,\n columns: string[],\n role: \"source\" | \"target\"\n ): ForeignKeyDef => ({\n name: topology.foreignKeyName(role),\n columns,\n referencedTable: side.table,\n referencedColumns: side.members.map((member) => member.pk.column),\n onDelete: side.actions.onDelete,\n onUpdate: side.actions.onUpdate,\n });\n return {\n name: topology.table,\n columns: [...first.members, ...second.members].map((member) => ({\n name: member.column,\n type: member.pk.type,\n nullable: false,\n })),\n primaryKey: { columns: [...firstColumns, ...secondColumns] },\n indexes:\n uniqueTargetName && topology.sourceIsFirst\n ? []\n : [\n {\n name: topology.reverseIndexName(),\n columns: secondColumns,\n unique: false,\n },\n ],\n foreignKeys: [\n makeFk(first, firstColumns, topology.sourceIsFirst ? \"source\" : \"target\"),\n makeFk(\n second,\n secondColumns,\n topology.sourceIsFirst ? \"target\" : \"source\"\n ),\n ],\n uniqueConstraints: uniqueTargetName\n ? [\n {\n name: uniqueTargetName(),\n columns: targetMembers.map((member) => member.column),\n },\n ]\n : [],\n };\n}\n\nfunction serializeMemberJunction(\n ownerModel: AnyModel,\n ownerTableName: string,\n member: ResolvedVariantJunctionMember,\n migrationDriver: MigrationDriver,\n relations: ResolvedRelationIndex\n): TableDef {\n const junction = member.topology;\n const targetModel = junction.target.model;\n return buildJunctionTable({\n sourceModel: ownerModel,\n sourceTable: ownerTableName,\n targetModel,\n targetTable: getModelTableName(\n targetModel,\n targetModel[\"~\"].names.ts?.toLowerCase() ?? \"unknown\"\n ),\n topology: junction,\n sourceActions: CASCADE_ACTIONS,\n targetActions: CASCADE_ACTIONS,\n uniqueTargetName: member.uniqueTarget\n ? () => junction.uniqueTargetName()\n : undefined,\n migrationDriver,\n relations,\n });\n}\n\n/**\n * Get every primary-key member in model-key order.\n */\nfunction getPrimaryKeyFieldDefs(\n model: AnyModel,\n migrationDriver: MigrationDriver,\n relations: ResolvedRelationIndex\n): readonly { field: string; column: string; type: string }[] {\n const modelState = model[\"~\"].state;\n const modelName = model[\"~\"].names.ts;\n const rowKey = getModelKeyCatalog(model).rowKey?.fields;\n if (!rowKey || rowKey.length === 0) {\n throw new Error(\n `Model \"${modelName}\" has no primary key. Schema may not be hydrated.`\n );\n }\n return rowKey.map((field) => {\n const scalar = modelState.scalars[field];\n if (!scalar) {\n throw new Error(\n `Primary-key field '${field}' of model \"${modelName}\" is not a scalar.`\n );\n }\n const scalarState = scalar[\"~\"].state;\n return {\n field,\n column: model[\"~\"].getFieldName(field).sql,\n // A junction column holds the referenced primary KEY's values, and that\n // key's identifier domain may be DERIVED — the one-to-one child whose\n // primary key is its parent foreign key is the ordinary case — so it is\n // read against the model through the same resolved index every other\n // column of this serialization is typed from. Reading the scalar's own\n // declaration types the junction column as text beside the sixteen-byte\n // column it references, which PostgreSQL refuses to key at all.\n type: migrationDriver.mapScalarType(\n scalar,\n scalarState,\n idDomainOf(model, field, relations)\n ),\n };\n });\n}\n\nexport { getColumnName } from \"../schema/model\";\n\n/**\n * Gets the SQL table name for a model\n */\nexport function getTableName(model: AnyModel, modelName: string): string {\n return getModelTableName(model, modelName.toLowerCase());\n}\n"],"mappings":"i4CAEA,MAAM,GAAe,mCACf,GAAmB,YACnB,GAAkB,gBAClB,GAAkB,sBAClB,GAAiB,KAevB,SAAgB,GACd,EACA,EACgB,CAChB,MAAO,CACL,GAAG,EACH,OACE,EAAU,OAAS,cACf,GAAY,EAAS,OAAQ,EAAU,KAAM,EAAU,GAAG,CAC1D,GACE,EAAS,OACT,EAAU,UACV,EAAU,KACV,EAAU,GACX,CACR,CAGH,SAAS,GACP,EACA,EACA,EACY,CACZ,OAAO,EAAO,IAAK,IAAW,CAC5B,GAAG,EACH,KAAM,EAAM,OAAS,EAAO,EAAK,EAAM,KACvC,YAAa,EAAM,YA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