viborm 1.14.2 → 1.16.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 (483) hide show
  1. package/dist/adapter-namespace-DwFnfpED.mjs +2 -0
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +26 -10
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/args-7WgBFd_f.mjs +2 -0
  6. package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
  7. package/dist/array-literal-BOzj0E2u.mjs +2 -0
  8. package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
  9. package/dist/base-17NSFtrA.mjs +2 -0
  10. package/dist/base-17NSFtrA.mjs.map +1 -0
  11. package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
  12. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
  13. package/dist/better-auth.d.mts +116 -0
  14. package/dist/better-auth.mjs +6 -0
  15. package/dist/better-auth.mjs.map +1 -0
  16. package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
  17. package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
  18. package/dist/bun-sql.d.mts +1 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/bun-sqlite.mjs.map +1 -1
  24. package/dist/cache/cloudflare-kv.d.mts +1 -1
  25. package/dist/cache/cloudflare-kv.mjs +1 -1
  26. package/dist/cache/cloudflare-kv.mjs.map +1 -1
  27. package/dist/cache/memory.d.mts +1 -1
  28. package/dist/cache/memory.mjs +1 -1
  29. package/dist/cache/memory.mjs.map +1 -1
  30. package/dist/cache.d.mts +2 -2
  31. package/dist/cache.mjs +1 -1
  32. package/dist/cache.mjs.map +1 -1
  33. package/dist/call-0bd_B9Vp.mjs +2 -0
  34. package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
  35. package/dist/cli.mjs +6 -6
  36. package/dist/cli.mjs.map +1 -1
  37. package/dist/client-D7sWgUt2.mjs +2 -0
  38. package/dist/client-D7sWgUt2.mjs.map +1 -0
  39. package/dist/client-DEfFqv4S.mjs +9 -0
  40. package/dist/client-DEfFqv4S.mjs.map +1 -0
  41. package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
  42. package/dist/client.d.mts +3 -3
  43. package/dist/client.mjs +1 -1
  44. package/dist/client.mjs.map +1 -1
  45. package/dist/config.d.mts +2 -2
  46. package/dist/config.mjs +1 -1
  47. package/dist/confine-CyI9IwjC.mjs +2 -0
  48. package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
  49. package/dist/coordination-BxMskOgi.mjs +2 -0
  50. package/dist/coordination-BxMskOgi.mjs.map +1 -0
  51. package/dist/d1.d.mts +2 -30
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
  55. package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
  56. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
  57. package/dist/defaults-DAPb-tJ4.mjs +2 -0
  58. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
  59. package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
  60. package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
  61. package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
  62. package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
  63. package/dist/driver-kiIQS_Fd.mjs +2 -0
  64. package/dist/driver-kiIQS_Fd.mjs.map +1 -0
  65. package/dist/driver-lShUkDmf.mjs +2 -0
  66. package/dist/driver-lShUkDmf.mjs.map +1 -0
  67. package/dist/driver.d.mts +1 -1
  68. package/dist/driver.mjs +1 -1
  69. package/dist/durable-object.d.mts +1 -1
  70. package/dist/durable-object.mjs +2 -2
  71. package/dist/durable-object.mjs.map +1 -1
  72. package/dist/error-mapping-B9rSvgG9.mjs +2 -0
  73. package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
  74. package/dist/every-JpbiHdMb.mjs +2 -0
  75. package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
  76. package/dist/execution-context-couU2tgh.mjs +2 -0
  77. package/dist/execution-context-couU2tgh.mjs.map +1 -0
  78. package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
  79. package/dist/extension-Dh1ddrlA.mjs +2 -0
  80. package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
  81. package/dist/fs-estate-n-QpsFqb.mjs +2 -0
  82. package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
  83. package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
  84. package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
  85. package/dist/id-domain-Cg65TLZ-.mjs +2 -0
  86. package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
  87. package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
  88. package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
  89. package/dist/identifiers-BxOf57qy.mjs +2 -0
  90. package/dist/identifiers-BxOf57qy.mjs.map +1 -0
  91. package/dist/identity-CJlRQA-m.mjs +2 -0
  92. package/dist/identity-CJlRQA-m.mjs.map +1 -0
  93. package/dist/index.d.mts +3 -3
  94. package/dist/index.mjs +1 -1
  95. package/dist/index.mjs.map +1 -1
  96. package/dist/instrumentation.d.mts +1 -1
  97. package/dist/instrumentation.mjs +1 -1
  98. package/dist/instrumentation.mjs.map +1 -1
  99. package/dist/introspect-q3Rf_Xv8.mjs +2 -0
  100. package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
  101. package/dist/json-CsAdz9pg.mjs +2 -0
  102. package/dist/json-CsAdz9pg.mjs.map +1 -0
  103. package/dist/json-number-C09rsm1g.mjs +2 -0
  104. package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
  105. package/dist/json-parameter-D7hDrVKw.mjs +2 -0
  106. package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
  107. package/dist/judge-words-k5GCc4cV.mjs +2 -0
  108. package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
  109. package/dist/key-BDH6oTyC.mjs +2 -0
  110. package/dist/key-BDH6oTyC.mjs.map +1 -0
  111. package/dist/keys-CIal55WQ.mjs +2 -0
  112. package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
  113. package/dist/keys-DZdKAd4n.mjs +2 -0
  114. package/dist/keys-DZdKAd4n.mjs.map +1 -0
  115. package/dist/libsql-DEZ0uhK2.mjs +3 -0
  116. package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
  117. package/dist/libsql.d.mts +2 -20
  118. package/dist/libsql.mjs +1 -1
  119. package/dist/libsql.mjs.map +1 -1
  120. package/dist/light-D2wNSbzY.mjs +2 -0
  121. package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
  122. package/dist/memory-BaGWNdvk.mjs +2 -0
  123. package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
  124. package/dist/methods-part-BaNx3o7b.mjs +2 -0
  125. package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
  126. package/dist/migrations/mysql.d.mts +5 -5
  127. package/dist/migrations/mysql.mjs +1 -1
  128. package/dist/migrations/postgres.d.mts +5 -5
  129. package/dist/migrations/postgres.mjs +1 -1
  130. package/dist/migrations/snowflake.d.mts +5 -5
  131. package/dist/migrations/snowflake.mjs +1 -1
  132. package/dist/migrations/sqlite.d.mts +5 -5
  133. package/dist/migrations/sqlite.mjs +1 -1
  134. package/dist/migrations/storage/durable-object.d.mts +1 -1
  135. package/dist/migrations/storage/durable-object.mjs +1 -1
  136. package/dist/migrations/storage/durable-object.mjs.map +1 -1
  137. package/dist/migrations/storage/fs.d.mts +1 -1
  138. package/dist/migrations/storage/fs.mjs +1 -1
  139. package/dist/migrations/storage/r2.d.mts +1 -1
  140. package/dist/migrations/storage/r2.mjs +1 -1
  141. package/dist/migrations/storage/r2.mjs.map +1 -1
  142. package/dist/migrations/surrealdb.d.mts +5 -5
  143. package/dist/migrations/surrealdb.mjs +1 -1
  144. package/dist/migrations/tenant.d.mts +3 -3
  145. package/dist/migrations/tenant.mjs +1 -1
  146. package/dist/migrations/tenant.mjs.map +1 -1
  147. package/dist/migrations-DIUltjr3.mjs +2 -0
  148. package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
  149. package/dist/migrations.d.mts +5 -5
  150. package/dist/migrations.mjs +1 -1
  151. package/dist/model-Dtd37Sky.mjs +2 -0
  152. package/dist/model-Dtd37Sky.mjs.map +1 -0
  153. package/dist/mysql-BFPF8xyv.mjs +9 -0
  154. package/dist/mysql-BFPF8xyv.mjs.map +1 -0
  155. package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
  156. package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
  157. package/dist/mysql2.d.mts +2 -27
  158. package/dist/mysql2.mjs +1 -1
  159. package/dist/mysql2.mjs.map +1 -1
  160. package/dist/named-statements-CkOOD__I.mjs +2 -0
  161. package/dist/named-statements-CkOOD__I.mjs.map +1 -0
  162. package/dist/named-statements-NF7Iycjk.d.mts +13 -0
  163. package/dist/native-types-1ewJXVks.mjs +2 -0
  164. package/dist/native-types-1ewJXVks.mjs.map +1 -0
  165. package/dist/neon-http.d.mts +1 -1
  166. package/dist/neon-http.mjs +1 -1
  167. package/dist/neon-http.mjs.map +1 -1
  168. package/dist/normalized-result-D7nVkF36.mjs +2 -0
  169. package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
  170. package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
  171. package/dist/object-store-Chq1PMYz.mjs +2 -0
  172. package/dist/object-store-Chq1PMYz.mjs.map +1 -0
  173. package/dist/on-ZkOVmE4-.mjs +2 -0
  174. package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
  175. package/dist/on.d.mts +1 -1
  176. package/dist/on.mjs +1 -1
  177. package/dist/on.mjs.map +1 -1
  178. package/dist/ordering/keys.mjs +1 -1
  179. package/dist/ordering.d.mts +9 -3
  180. package/dist/ordering.mjs +10 -10
  181. package/dist/ordering.mjs.map +1 -1
  182. package/dist/pending-operation-D4gUKMxD.mjs +2 -0
  183. package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
  184. package/dist/permissions.d.mts +1 -1
  185. package/dist/permissions.mjs +1 -1
  186. package/dist/permissions.mjs.map +1 -1
  187. package/dist/pg.d.mts +16 -99
  188. package/dist/pg.mjs +1 -1
  189. package/dist/pg.mjs.map +1 -1
  190. package/dist/pglite.d.mts +3 -1
  191. package/dist/pglite.mjs +1 -1
  192. package/dist/pglite.mjs.map +1 -1
  193. package/dist/physical-DO4PEYcc.mjs +2 -0
  194. package/dist/physical-DO4PEYcc.mjs.map +1 -0
  195. package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
  196. package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
  197. package/dist/planetscale.d.mts +1 -1
  198. package/dist/planetscale.mjs +1 -1
  199. package/dist/planetscale.mjs.map +1 -1
  200. package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
  201. package/dist/postgres-DQQE2ys_.mjs +34 -0
  202. package/dist/postgres-DQQE2ys_.mjs.map +1 -0
  203. package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
  204. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
  205. package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
  206. package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
  207. package/dist/postgres-result-133boRW-.mjs +2 -0
  208. package/dist/postgres-result-133boRW-.mjs.map +1 -0
  209. package/dist/postgres.d.mts +27 -59
  210. package/dist/postgres.mjs +1 -1
  211. package/dist/postgres.mjs.map +1 -1
  212. package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
  213. package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
  214. package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
  215. package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
  216. package/dist/quantized-BKBs0joq.mjs +2 -0
  217. package/dist/quantized-BKBs0joq.mjs.map +1 -0
  218. package/dist/query-BTb6iakn.mjs +2 -0
  219. package/dist/query-BTb6iakn.mjs.map +1 -0
  220. package/dist/query-backend-TisPjCPF.mjs +2 -0
  221. package/dist/query-backend-TisPjCPF.mjs.map +1 -0
  222. package/dist/query-inspection-DwYBKSDG.mjs +2 -0
  223. package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
  224. package/dist/raw-DqEb71JZ.mjs +2 -0
  225. package/dist/raw-DqEb71JZ.mjs.map +1 -0
  226. package/dist/relation-bound-CSNKLyDy.mjs +2 -0
  227. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
  228. package/dist/result-parsing-BbffueEX.mjs +2 -0
  229. package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
  230. package/dist/routed-operations-CcKOdn51.mjs +2 -0
  231. package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
  232. package/dist/rows-of-Bgl9GVtK.mjs +2 -0
  233. package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
  234. package/dist/rule-words-DMbQuvD2.mjs +2 -0
  235. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
  236. package/dist/scalar-Dm9brvAU.mjs +4 -0
  237. package/dist/scalar-Dm9brvAU.mjs.map +1 -0
  238. package/dist/schema/introspect.d.mts +2 -2
  239. package/dist/schema/introspect.mjs +1 -1
  240. package/dist/schema/json.d.mts +6 -4
  241. package/dist/schema/json.mjs +1 -1
  242. package/dist/schema-DDkAUfOb.mjs +2 -0
  243. package/dist/schema-DDkAUfOb.mjs.map +1 -0
  244. package/dist/schema-DqR_Kcje.mjs +2 -0
  245. package/dist/schema-DqR_Kcje.mjs.map +1 -0
  246. package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
  247. package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
  248. package/dist/schema.d.mts +2 -2
  249. package/dist/schema.mjs +1 -1
  250. package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
  251. package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
  252. package/dist/serializer-ettLu5xG.mjs +33 -0
  253. package/dist/serializer-ettLu5xG.mjs.map +1 -0
  254. package/dist/settle-Pui-1tfJ.mjs +2 -0
  255. package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
  256. package/dist/settled-DYYPcaBX.mjs +2 -0
  257. package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
  258. package/dist/snowflake-BfF8xwfP.mjs +2 -0
  259. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
  260. package/dist/snowflake.d.mts +3 -3
  261. package/dist/snowflake.mjs +2 -2
  262. package/dist/snowflake.mjs.map +1 -1
  263. package/dist/soft-delete.d.mts +9 -3
  264. package/dist/soft-delete.mjs +1 -1
  265. package/dist/soft-delete.mjs.map +1 -1
  266. package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
  267. package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
  268. package/dist/sql-Bu63iAfT.mjs +2 -0
  269. package/dist/sql-Bu63iAfT.mjs.map +1 -0
  270. package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
  271. package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
  272. package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
  273. package/dist/sql-tegqTqGq.mjs +2 -0
  274. package/dist/sql-tegqTqGq.mjs.map +1 -0
  275. package/dist/sql.d.mts +1 -1
  276. package/dist/sql.mjs +1 -1
  277. package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
  278. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
  279. package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
  280. package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
  281. package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
  282. package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
  283. package/dist/sqlite3.d.mts +2 -46
  284. package/dist/sqlite3.mjs +1 -1
  285. package/dist/sqlite3.mjs.map +1 -1
  286. package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
  287. package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
  288. package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
  289. package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
  290. package/dist/surrealdb.d.mts +2 -2
  291. package/dist/surrealdb.mjs +1 -1
  292. package/dist/surrealdb.mjs.map +1 -1
  293. package/dist/surrealql-DY74AUeD.mjs +2 -0
  294. package/dist/surrealql-DY74AUeD.mjs.map +1 -0
  295. package/dist/time-step-DJaIhpAz.mjs +2 -0
  296. package/dist/time-step-DJaIhpAz.mjs.map +1 -0
  297. package/dist/transaction-Bv5nyp-U.mjs +2 -0
  298. package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
  299. package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
  300. package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
  301. package/dist/types-Dy33vBdd.mjs +2 -0
  302. package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
  303. package/dist/unit-DUPX5Sdd.mjs +2 -0
  304. package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
  305. package/dist/unit-words-BXpLpyr2.mjs +2 -0
  306. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
  307. package/dist/utils-BHkJsduV.mjs +26 -0
  308. package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
  309. package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
  310. package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
  311. package/dist/validation-ATmgN5RE.mjs +2 -0
  312. package/dist/validation-ATmgN5RE.mjs.map +1 -0
  313. package/dist/validation-BHjx13zG.mjs +2 -0
  314. package/dist/validation-BHjx13zG.mjs.map +1 -0
  315. package/dist/validation.d.mts +1 -1
  316. package/dist/validation.mjs +1 -1
  317. package/dist/validator-DMzH5Tz0.mjs +2 -0
  318. package/dist/validator-DMzH5Tz0.mjs.map +1 -0
  319. package/dist/value-guards-CBVIJXlI.mjs +2 -0
  320. package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
  321. package/dist/values-Ch2cTlss.mjs +2 -0
  322. package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
  323. package/dist/version-0BDwfy7C.mjs +2 -0
  324. package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
  325. package/dist/view-CHgjF2BO.mjs +2 -0
  326. package/dist/view-CHgjF2BO.mjs.map +1 -0
  327. package/dist/write-sinks-Bei5vFHP.mjs +2 -0
  328. package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
  329. package/package.json +50 -37
  330. package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
  331. package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
  332. package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
  333. package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
  334. package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
  335. package/dist/args-764KdWMr.mjs +0 -2
  336. package/dist/array-literal-DHinAnVs.mjs +0 -2
  337. package/dist/base-z-cH5ZBI.mjs +0 -2
  338. package/dist/base-z-cH5ZBI.mjs.map +0 -1
  339. package/dist/batch-refs-C-gx7A4-.mjs +0 -2
  340. package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
  341. package/dist/call-Cz8XUmrl.mjs +0 -2
  342. package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
  343. package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
  344. package/dist/chunk-BuuaeEvq.mjs +0 -1
  345. package/dist/client-DRpX3-vw.mjs +0 -2
  346. package/dist/client-DRpX3-vw.mjs.map +0 -1
  347. package/dist/client-y7TV0PRZ.mjs +0 -9
  348. package/dist/client-y7TV0PRZ.mjs.map +0 -1
  349. package/dist/confine-DqFBTUw6.mjs +0 -2
  350. package/dist/coordination-6qZHx_kl.mjs +0 -2
  351. package/dist/coordination-6qZHx_kl.mjs.map +0 -1
  352. package/dist/current-DBTlPsQg.mjs +0 -2
  353. package/dist/current-DBTlPsQg.mjs.map +0 -1
  354. package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
  355. package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
  356. package/dist/defaults-DwOHWI_M.mjs +0 -2
  357. package/dist/driver-BGVcgnIX.mjs +0 -2
  358. package/dist/driver-BGVcgnIX.mjs.map +0 -1
  359. package/dist/driver-BIXhOH2_.mjs +0 -2
  360. package/dist/driver-BIXhOH2_.mjs.map +0 -1
  361. package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
  362. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  363. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  364. package/dist/every-tOgQmaIE.mjs +0 -2
  365. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  366. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  367. package/dist/extension-CGepsF-p.mjs +0 -2
  368. package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
  369. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  370. package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
  371. package/dist/hydration-A3zffFWP.mjs +0 -2
  372. package/dist/hydration-A3zffFWP.mjs.map +0 -1
  373. package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
  374. package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
  375. package/dist/identifiers-s00pGES8.mjs +0 -2
  376. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  377. package/dist/identity-CtW15WlB.mjs +0 -2
  378. package/dist/identity-CtW15WlB.mjs.map +0 -1
  379. package/dist/introspect-Bm6xnXcG.mjs +0 -2
  380. package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
  381. package/dist/json-DgMc8-GU.mjs +0 -2
  382. package/dist/json-DgMc8-GU.mjs.map +0 -1
  383. package/dist/json-number-AI-SdUUn.mjs +0 -2
  384. package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
  385. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  386. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  387. package/dist/key-hxFFCKed.mjs +0 -2
  388. package/dist/key-hxFFCKed.mjs.map +0 -1
  389. package/dist/keys-BQxM4c_a.mjs +0 -2
  390. package/dist/libsql-DuGR904j.mjs +0 -3
  391. package/dist/libsql-DuGR904j.mjs.map +0 -1
  392. package/dist/light-BkJe3-yW.mjs +0 -2
  393. package/dist/memory-G4cSuc6A.mjs +0 -2
  394. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  395. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  396. package/dist/migrations-BMiRjR-N.mjs +0 -2
  397. package/dist/mysql-BNXWfTOo.mjs +0 -100
  398. package/dist/mysql-BNXWfTOo.mjs.map +0 -1
  399. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  400. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  401. package/dist/native-types-DgjMUikz.mjs +0 -2
  402. package/dist/native-types-DgjMUikz.mjs.map +0 -1
  403. package/dist/normalized-result-B8pifWS0.mjs +0 -2
  404. package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
  405. package/dist/object-store-DS0F0yZX.mjs +0 -2
  406. package/dist/object-store-DS0F0yZX.mjs.map +0 -1
  407. package/dist/on-ylYaKuRu.mjs +0 -2
  408. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  409. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  410. package/dist/physical-CeE2nYmI.mjs +0 -2
  411. package/dist/physical-CeE2nYmI.mjs.map +0 -1
  412. package/dist/pinned-session-DCoAZDOz.mjs +0 -2
  413. package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
  414. package/dist/postgres-CDdh5dSP.mjs +0 -437
  415. package/dist/postgres-CDdh5dSP.mjs.map +0 -1
  416. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  417. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  418. package/dist/postgres-adapter-axapXX8d.mjs +0 -2
  419. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  420. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  421. package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
  422. package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
  423. package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
  424. package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
  425. package/dist/query-BZVHfA0s.mjs +0 -2
  426. package/dist/query-BZVHfA0s.mjs.map +0 -1
  427. package/dist/query-inspection-BoG-yAln.mjs +0 -2
  428. package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
  429. package/dist/raw-Dyq6Y6UX.mjs +0 -2
  430. package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
  431. package/dist/relation-bound-ku_cMdye.mjs +0 -2
  432. package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
  433. package/dist/routed-operations-wytpbYKv.mjs +0 -2
  434. package/dist/rule-words-ZIGm7cDm.mjs +0 -2
  435. package/dist/scalar-BHCh7aUz.mjs +0 -4
  436. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  437. package/dist/schema-BYA-_bpk.mjs +0 -2
  438. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  439. package/dist/schema-CFIaebgi.mjs +0 -2
  440. package/dist/schema-CFIaebgi.mjs.map +0 -1
  441. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  442. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  443. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  444. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  445. package/dist/serializer-rBq3v1xr.mjs +0 -51
  446. package/dist/serializer-rBq3v1xr.mjs.map +0 -1
  447. package/dist/settle-1cy5x_52.mjs +0 -2
  448. package/dist/settled-BjyuA76m.mjs +0 -2
  449. package/dist/snowflake-UOCC820W.mjs +0 -2
  450. package/dist/sql-3o4DOKm9.mjs +0 -2
  451. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  452. package/dist/sql-Dl6nykFV.mjs +0 -2
  453. package/dist/sql-Dl6nykFV.mjs.map +0 -1
  454. package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
  455. package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
  456. package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
  457. package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
  458. package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
  459. package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
  460. package/dist/standard-sql-qLcQyCtK.mjs +0 -6
  461. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  462. package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
  463. package/dist/surrealql-C1dp1sWw.mjs +0 -2
  464. package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
  465. package/dist/to-many-BybuKQM1.mjs +0 -2
  466. package/dist/to-many-BybuKQM1.mjs.map +0 -1
  467. package/dist/transaction-BNomMtme.mjs +0 -2
  468. package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
  469. package/dist/types-DtDnXhwa.mjs +0 -2
  470. package/dist/unit-BhHbZyuJ.mjs +0 -2
  471. package/dist/unit-words-CT0yeqfZ.mjs +0 -2
  472. package/dist/utils-CpAojrCj.mjs +0 -26
  473. package/dist/validation--qS7OPmg.mjs +0 -2
  474. package/dist/validation--qS7OPmg.mjs.map +0 -1
  475. package/dist/validation-CYaJ8ndO.mjs +0 -2
  476. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  477. package/dist/validator-CZLW7aR3.mjs +0 -2
  478. package/dist/validator-CZLW7aR3.mjs.map +0 -1
  479. package/dist/value-guards-CBuxSC66.mjs +0 -2
  480. package/dist/values-B4aj1i1f.mjs +0 -2
  481. package/dist/version-CXGIA82S.mjs +0 -2
  482. package/dist/write-sinks-3IKCDF-S.mjs +0 -2
  483. /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serializer-ettLu5xG.mjs","names":["refuse","entries","WHITESPACE","quote","entries","refuse","epochMilliseconds","quote","refuse","refuse","hex","#view","#model","#columns","#root","#aggregate","tableOf","name"],"sources":["../src/migrations/input-boundary.ts","../src/migrations/limits.ts","../src/adapters/databases/sqlite/storage/sql-lexing.ts","../src/adapters/databases/sqlite/storage/column-constraints.ts","../src/adapters/databases/sqlite/storage/geo-point.ts","../src/adapters/databases/sqlite/storage/decimal.ts","../src/migrations/decimal.ts","../src/adapters/databases/mysql/string-literal.ts","../src/migrations/drivers/type-mapping.ts","../src/migrations/native-rename.ts","../src/migrations/types.ts","../src/migrations/drop-order.ts","../src/migrations/view.ts","../src/migrations/utils.ts","../src/migrations/base64.ts","../src/migrations/v1-parse-dispatch.ts","../src/migrations/v1-parse-control.ts","../src/migrations/raw-index.ts","../src/migrations/v1-parse-snapshot.ts","../src/migrations/v1-parse.ts","../src/migrations/resolver.ts","../src/migrations/push/enum-removals.ts","../src/migrations/differ.ts","../src/migrations/catalog-probes.ts","../src/migrations/invert.ts","../src/migrations/sql-blob.ts","../src/migrations/statement-safety.ts","../src/migrations/compile.ts","../src/migrations/execute-dispatch.ts","../src/migrations/foreign-keys.ts","../src/migrations/pinned-session.ts","../src/migrations/push-fingerprint.ts","../src/migrations/drivers/postgres/catalog-refusal.ts","../src/migrations/control.ts","../src/migrations/target.ts","../src/migrations/binary-conversion.ts","../src/migrations/drivers/base.ts","../src/migrations/drivers/index.ts","../src/adapters/databases/sqlite/storage/datetime.ts","../src/migrations/drivers/utils.ts","../src/migrations/drivers/sqlite/introspect.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":["/** Settles one hostile record into an exact immutable property snapshot. */\n\nimport { errorCause } from \"../errors/diagnostic-safety\";\n\ntype RefuseInput = (message: string, cause?: Error) => never;\n\nexport function snapshotExactRecord(\n value: unknown,\n allowed: readonly string[],\n label: string,\n refuse: RefuseInput\n): Readonly<Record<string, unknown>> {\n let objectValue: object | undefined;\n let keys: readonly PropertyKey[] = [];\n try {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n objectValue = value;\n keys = Reflect.ownKeys(value);\n }\n } catch (failure) {\n return refuse(`${label} could not be inspected`, errorCause(failure));\n }\n if (!objectValue) return refuse(`${label} must be an object`);\n const snapshot: Record<string, unknown> = {};\n for (const key of keys) {\n if (typeof key !== \"string\" || !allowed.includes(key)) {\n return refuse(`${label} contains unknown key ${String(key)}`);\n }\n try {\n snapshot[key] = Reflect.get(objectValue, key);\n } catch (failure) {\n return refuse(`${label}.${key} could not be read`, errorCause(failure));\n }\n }\n return Object.freeze(snapshot);\n}\n\nexport function snapshotExactArray(\n value: unknown,\n label: string,\n refuse: RefuseInput\n): readonly unknown[] {\n let entries: unknown[] | undefined;\n try {\n if (Array.isArray(value)) entries = Array.from(value);\n } catch (failure) {\n return refuse(`${label} could not be read`, errorCause(failure));\n }\n if (!entries) return refuse(`${label} must be an array`);\n return Object.freeze(entries);\n}\n","/**\n * The limits of one migration command (plans S1, T5a): their type, their\n * defaults and the one resolver. Only migration code imports this module, so\n * an application bundle carries none of it.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { snapshotExactRecord } from \"./input-boundary\";\n\n/**\n * The limits of one migration command's pinned session (plan S1), and the\n * table size it may rewrite in-request (plan T5a).\n *\n * Every value but `largeTableRows` is in milliseconds. `lockTimeout`, `statementTimeout` and\n * `idleTimeout` are PostgreSQL server settings, where 0 means \"no limit\";\n * `lockWait` and `connectionWait` are waits VibORM itself bounds. `lockWait`\n * also bounds SQLite's `BEGIN IMMEDIATE`, and `connectionWait` applies to\n * MySQL as well; the others, `largeTableRows` included, are PostgreSQL-only,\n * and MySQL keeps its fixed named-lock wait.\n */\nexport interface MigrationLimits {\n /**\n * `lock_timeout`, for the session and, with `SET LOCAL`, every migration\n * transaction: how long one DDL statement may queue for a table lock.\n */\n readonly lockTimeout?: number;\n /**\n * `statement_timeout`, for every migration transaction and for the session\n * around the lock and stepwise programs. 0, or longer than `lockWait`.\n */\n readonly statementTimeout?: number;\n /**\n * `idle_in_transaction_session_timeout` and, on PostgreSQL 14+,\n * `idle_session_timeout`: how long the server keeps a migration session\n * whose client stopped talking — the one that vanished holding the lock.\n * It also bounds the client's own pauses between two statements of a\n * command, so the default (30 s) frees a dead client's lock within half a\n * minute while a loaded client's pause between parts never ends the\n * session (1 s did, before 1.2.3).\n */\n readonly idleTimeout?: number;\n /** How long the command waits for the migration lock another one holds. */\n readonly lockWait?: number;\n /** How long the command waits for its pinned connection. */\n readonly connectionWait?: number;\n /**\n * A row count, not milliseconds: the planner's estimate above which a\n * statement that rewrites or scans a table under a lock that blocks it (a\n * column type change, `SET NOT NULL`, a volatile `ADD COLUMN` default, a\n * FOREIGN KEY or CHECK added without `NOT VALID`) is refused before any\n * effect, because it would hold that lock longer than a request should.\n * 0 admits every size.\n */\n readonly largeTableRows?: number;\n}\n\nexport type ResolvedMigrationLimits = Readonly<Required<MigrationLimits>>;\n\nexport const DEFAULT_MIGRATION_LIMITS: ResolvedMigrationLimits = Object.freeze({\n lockTimeout: 4000,\n statementTimeout: 600_000,\n idleTimeout: 30_000,\n lockWait: 10_000,\n connectionWait: 10_000,\n largeTableRows: 1_000_000,\n});\n\n/** The largest PostgreSQL timeout setting, and the largest timer delay. */\nconst MAX_TIME_LIMIT_MS = 2_147_483_647;\n\nconst LIMIT_KEYS = [\n \"lockTimeout\",\n \"statementTimeout\",\n \"idleTimeout\",\n \"lockWait\",\n \"connectionWait\",\n \"largeTableRows\",\n] as const satisfies readonly (keyof MigrationLimits)[];\n\n/**\n * The limits a migration client was given, settled once: each key a whole\n * number (milliseconds, rows for `largeTableRows`), the defaults filling in\n * the rest.\n *\n * `lockWait` and `connectionWait` are waits VibORM bounds and must be\n * positive; the server settings accept 0 (\"no limit\"). Every key stops at\n * {@link MAX_TIME_LIMIT_MS}, the most both PostgreSQL's settings and a timer\n * hold. A `statementTimeout` must outlast `lockWait`, which runs as one\n * statement under it.\n */\nexport function resolveMigrationLimits(\n input: unknown\n): ResolvedMigrationLimits {\n if (input === undefined) return DEFAULT_MIGRATION_LIMITS;\n const record = snapshotExactRecord(\n input,\n LIMIT_KEYS,\n \"migration limits\",\n refuseLimits\n );\n const limits: Record<(typeof LIMIT_KEYS)[number], number> = {\n ...DEFAULT_MIGRATION_LIMITS,\n };\n for (const key of LIMIT_KEYS) {\n const value = record[key];\n if (value === undefined) continue;\n const least = key === \"lockWait\" || key === \"connectionWait\" ? 1 : 0;\n if (\n typeof value !== \"number\" ||\n !Number.isInteger(value) ||\n value < least ||\n value > MAX_TIME_LIMIT_MS\n ) {\n refuseLimits(\n `migration limit ${key} must be an integer (${least}..${MAX_TIME_LIMIT_MS}).`\n );\n }\n limits[key] = value;\n }\n if (\n limits.statementTimeout !== 0 &&\n limits.statementTimeout <= limits.lockWait\n ) {\n refuseLimits(\n `statementTimeout (${limits.statementTimeout}ms) must be 0 or > lockWait (${limits.lockWait}ms).`\n );\n }\n return Object.freeze(limits);\n}\n\nfunction refuseLimits(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n","/** SQLite token boundaries shared by stored-DDL readers. */\n\n/** An identifier token and where it ends. */\nexport interface SqliteIdentifierToken {\n readonly value: string;\n readonly quoted: boolean;\n readonly end: number;\n}\n\nconst IDENTIFIER_CLOSERS: Readonly<Record<string, string>> = {\n '\"': '\"',\n \"`\": \"`\",\n \"[\": \"]\",\n};\n\nconst BARE_IDENTIFIER_CHARACTER = /[A-Za-z0-9_$]/;\nconst WHITESPACE = /\\s/;\n\n/** Whether one character can occur in SQLite's bare identifier spelling. */\nexport function isSqliteBareIdentifierCharacter(character: string): boolean {\n return BARE_IDENTIFIER_CHARACTER.test(character);\n}\n\n/**\n * Read the identifier at or after `index`, in any of SQLite's four spellings.\n *\n * A doubled quote inside a `\"…\"` or a `` `…` `` token is an escaped one.\n */\nexport function readSqliteIdentifier(\n text: string,\n index: number\n): SqliteIdentifierToken | undefined {\n let cursor = index;\n while (cursor < text.length) {\n while (cursor < text.length && WHITESPACE.test(text.charAt(cursor))) {\n cursor++;\n }\n const isComment =\n (text[cursor] === \"-\" && text[cursor + 1] === \"-\") ||\n (text[cursor] === \"/\" && text[cursor + 1] === \"*\");\n if (!isComment) break;\n cursor = skipSqlNonStructuralRegion(text, cursor);\n }\n const opener = text[cursor];\n if (opener === undefined) return undefined;\n\n const closer = IDENTIFIER_CLOSERS[opener];\n if (closer !== undefined) {\n let value = \"\";\n cursor++;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n if (text[cursor + 1] === closer && closer !== \"]\") {\n value += closer;\n cursor += 2;\n continue;\n }\n return { value, quoted: true, end: cursor + 1 };\n }\n value += text[cursor];\n cursor++;\n }\n return undefined;\n }\n\n const start = cursor;\n while (\n cursor < text.length &&\n isSqliteBareIdentifierCharacter(text.charAt(cursor))\n ) {\n cursor++;\n }\n if (cursor === start) return undefined;\n return { value: text.slice(start, cursor), quoted: false, end: cursor };\n}\n\n/**\n * The offset just past the quoted token or SQL comment starting at `index`, or\n * `index` itself when structural SQL starts there.\n */\nexport function skipSqlNonStructuralRegion(\n text: string,\n index: number\n): number {\n const opener = text[index];\n if (opener === undefined) return index;\n if (opener === \"-\" && text[index + 1] === \"-\") {\n const end = text.indexOf(\"\\n\", index + 2);\n return end === -1 ? text.length : end;\n }\n if (opener === \"/\" && text[index + 1] === \"*\") {\n const end = text.indexOf(\"*/\", index + 2);\n return end === -1 ? text.length : end + 2;\n }\n const closer = opener === \"'\" ? \"'\" : IDENTIFIER_CLOSERS[opener];\n if (closer === undefined) return index;\n\n let cursor = index + 1;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n // A doubled quote is an escaped one, not the end of the token. `]` has\n // no escape in SQLite's bracket spelling.\n if (text[cursor + 1] === closer && closer !== \"]\") {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n cursor++;\n }\n return text.length;\n}\n","import {\n isSqliteBareIdentifierCharacter,\n readSqliteIdentifier,\n skipSqlNonStructuralRegion,\n} from \"./sql-lexing\";\n\n/** One top-level entry of a `CREATE TABLE` definition list. */\nexport interface SqliteTableDefinition {\n readonly text: string;\n /** The column this entry defines, or `undefined` for a table constraint. */\n readonly columnName: string | undefined;\n}\n\n/** A `CONSTRAINT <name>` at the top level of one definition. */\nexport interface SqliteConstraintClause {\n readonly name: string;\n /** Where the `CONSTRAINT` keyword starts inside the definition text. */\n readonly offset: number;\n}\n\n/** Keywords that open a table constraint rather than a column definition. */\nconst TABLE_CONSTRAINT_KEYWORDS = new Set([\n \"CONSTRAINT\",\n \"PRIMARY\",\n \"UNIQUE\",\n \"CHECK\",\n \"FOREIGN\",\n]);\n\n/**\n * Every top-level entry of the definition list, with the column each one\n * defines. Quoted tokens and comments are skipped before structural commas and\n * parentheses are interpreted.\n */\nexport function sqliteTableDefinitions(sql: string): SqliteTableDefinition[] {\n let open = -1;\n let scan = 0;\n while (scan < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, scan);\n if (skipped !== scan) {\n scan = skipped;\n continue;\n }\n if (sql[scan] === \"(\") {\n open = scan;\n break;\n }\n scan++;\n }\n if (open === -1) return [];\n\n const definitions: SqliteTableDefinition[] = [];\n let depth = 1;\n let start = open + 1;\n let cursor = start;\n while (cursor < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = sql[cursor];\n if (char === \"(\") depth++;\n else if (char === \")\") {\n depth--;\n if (depth === 0) break;\n } else if (char === \",\" && depth === 1) {\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n start = cursor + 1;\n }\n cursor++;\n }\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n return definitions;\n}\n\nfunction describeDefinition(raw: string): SqliteTableDefinition {\n const text = raw.trim();\n const first = readSqliteIdentifier(text, 0);\n if (first === undefined) return { text, columnName: undefined };\n if (first.quoted) return { text, columnName: first.value };\n return {\n text,\n columnName: TABLE_CONSTRAINT_KEYWORDS.has(first.value.toUpperCase())\n ? undefined\n : first.value,\n };\n}\n\n/** Every structural `CONSTRAINT <name>` at depth zero of one definition. */\nexport function sqliteConstraintClauses(\n definition: string\n): SqliteConstraintClause[] {\n const clauses: SqliteConstraintClause[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = definition.charAt(cursor);\n const word = isSqliteBareIdentifierCharacter(char)\n ? readSqliteIdentifier(definition, cursor)\n : undefined;\n if (word !== undefined) {\n if (depth === 0 && word.value.toUpperCase() === \"CONSTRAINT\") {\n const name = readSqliteIdentifier(definition, word.end);\n if (name) {\n clauses.push({ name: name.value, offset: cursor });\n cursor = name.end;\n continue;\n }\n }\n cursor = word.end;\n continue;\n }\n if (char === \"(\") depth++;\n else if (char === \")\") depth--;\n cursor++;\n }\n return clauses;\n}\n\n/** Structural keywords outside expression bodies, quoted tokens and comments. */\nexport function sqliteDefinitionKeywords(definition: string): string[] {\n const words: string[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const word = readSqliteIdentifier(definition, cursor);\n if (word && !word.quoted) {\n if (depth === 0) words.push(word.value.toUpperCase());\n cursor = word.end;\n continue;\n }\n if (definition[cursor] === \"(\") depth++;\n else if (definition[cursor] === \")\") depth--;\n cursor++;\n }\n return words;\n}\n","import { MigrationError, VibORMErrorCode } from \"../../../../errors\";\nimport {\n GEO_LATITUDE_MAX,\n GEO_LATITUDE_MIN,\n GEO_LONGITUDE_MAX,\n GEO_LONGITUDE_MIN,\n} from \"../../../../validation/primitives/geo-values\";\nimport { sqliteBinary64JsonNumber } from \"./json-number\";\n\ninterface PhysicalColumn {\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n}\n\nimport {\n sqliteConstraintClauses,\n sqliteTableDefinitions,\n} from \"./column-constraints\";\n\n/** TEXT-affinity spelling reserved for VibORM's canonical GeoPoint carrier. */\nexport const SQLITE_GEO_POINT_TYPE = \"VIBORM_GEO_TEXT\";\n\n/** Fixed so a native column rename cannot stale the constraint identity. */\nconst SQLITE_GEO_POINT_CONSTRAINT = \"viborm_geo\";\n\n/** The complete writer-owned column constraint for one GeoPoint carrier. */\nexport function sqliteGeoPointCheck(\n column: Pick<PhysicalColumn, \"name\" | \"nullable\">,\n escapeIdentifier: (name: string) => string,\n encoding: \"legacy\" | \"binary64\" = \"binary64\"\n): string {\n const col = escapeIdentifier(column.name);\n const longitude = `json_extract(${col}, '$.longitude')`;\n const latitude = `json_extract(${col}, '$.latitude')`;\n const valid =\n `CASE WHEN typeof(${col}) = 'text' AND json_valid(${col}) THEN (` +\n `json_type(${col}) = 'object' AND ` +\n `json_type(${col}, '$.longitude') IN ('integer', 'real') AND ` +\n `json_type(${col}, '$.latitude') IN ('integer', 'real') AND ` +\n `${longitude} > ${GEO_LONGITUDE_MIN} AND ${longitude} <= ${GEO_LONGITUDE_MAX} AND ` +\n `${latitude} >= ${GEO_LATITUDE_MIN} AND ${latitude} <= ${GEO_LATITUDE_MAX} AND ` +\n `${col} = ${sqliteGeoPointCarrier(col, encoding)}` +\n \") ELSE 0 END\";\n const body = column.nullable ? `${col} IS NULL OR (${valid})` : valid;\n return `CONSTRAINT ${escapeIdentifier(SQLITE_GEO_POINT_CONSTRAINT)} CHECK (${body})`;\n}\n\n/**\n * Proves that SQLite's reserved declared type is paired with the exact\n * writer-owned constraint. A reserved type without its proof is refused rather\n * than published as a GeoPoint or silently normalized into one.\n */\nexport function readSqliteGeoPointColumn(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): \"legacy\" | \"binary64\" | undefined {\n if (column.type.toUpperCase() !== SQLITE_GEO_POINT_TYPE) return undefined;\n const expected = sqliteGeoPointCheck(column, escapeIdentifier);\n const legacy = sqliteGeoPointCheck(column, escapeIdentifier, \"legacy\");\n let encoding: \"legacy\" | \"binary64\" = \"binary64\";\n let matching = 0;\n for (const definition of sqliteTableDefinitions(tableSql ?? \"\")) {\n if (definition.columnName !== column.name) continue;\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (clause.name !== SQLITE_GEO_POINT_CONSTRAINT) continue;\n if (definition.text.startsWith(expected, clause.offset))\n encoding = \"binary64\";\n else if (definition.text.startsWith(legacy, clause.offset))\n encoding = \"legacy\";\n else refuseUnprovenGeoPoint(column);\n matching++;\n }\n }\n if (matching !== 1) refuseUnprovenGeoPoint(column);\n return encoding;\n}\n\nfunction refuseUnprovenGeoPoint(\n column: Pick<PhysicalColumn, \"name\" | \"type\">\n): never {\n throw new MigrationError(\n `SQLite column \"${column.name}\" uses reserved GeoPoint type \"${column.type}\" without canonical GeoPoint CHECK.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"sqlite\",\n column: column.name,\n type: column.type,\n },\n }\n );\n}\n\n/** Copying legacy storage preserves the double still present, not earlier lost digits. */\nexport function sqliteGeoPointCarrier(\n source: string,\n encoding: \"legacy\" | \"binary64\" = \"binary64\"\n): string {\n const longitude = `json_extract(${source}, '$.longitude')`;\n const latitude = `json_extract(${source}, '$.latitude')`;\n return `json_object('longitude', ${encoding === \"legacy\" ? longitude : sqliteBinary64JsonNumber(longitude)}, 'latitude', ${encoding === \"legacy\" ? latitude : sqliteBinary64JsonNumber(latitude)})`;\n}\n\n/** Format-1 snapshots predating the precision annotation describe the legacy CHECK. */\nexport function sqliteGeoPointEncoding(column: {\n readonly type: string;\n readonly geoPointEncoding?: \"legacy\" | \"binary64\" | undefined;\n}): \"legacy\" | \"binary64\" | undefined {\n return column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE\n ? (column.geoPointEncoding ?? \"legacy\")\n : undefined;\n}\n","/**\n * SQLite fixed-decimal migration storage.\n *\n * SQLite cannot carry a decimal descriptor in its declared storage type, so\n * this module owns the reserved CHECK carrier, its structural reader, and the\n * exact table-rebuild expressions that rescale scalar and list coefficients.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../../errors\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n sameDecimalDescriptor,\n} from \"../../../../validation/primitives/decimal-codec\";\nexport type DecimalStorageKind = \"scalar\" | \"list\";\ninterface PhysicalColumn {\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n readonly decimal?: DecimalDescriptor | undefined;\n}\nexport function sqliteDecimalStorageKind(\n column: Pick<PhysicalColumn, \"type\" | \"decimal\">\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase();\n if (type === decimalColumnType(\"sqlite\", column.decimal)) return \"scalar\";\n return type === \"TEXT\" ? \"list\" : undefined;\n}\n\nimport {\n type SqliteConstraintClause,\n type SqliteTableDefinition,\n sqliteConstraintClauses,\n sqliteTableDefinitions,\n} from \"./column-constraints\";\n\n/**\n * The reserved SQLite constraint name for one decimal column.\n *\n * SQLite's declared type is the wrong carrier twice over: it stores `INTEGER`\n * (or `TEXT` for a list) whatever the domain is, and a CHECK written INTO the\n * type string never reads back — `PRAGMA table_info.type` reports only the\n * `type-name` production, so the desired `TEXT CHECK(...)` can never equal the\n * introspected `TEXT` and a full table recreation is planned on every push,\n * forever. (That is measured behaviour of the enum column type, not a\n * hypothetical.) So the descriptor rides in a NAMED constraint, and\n * introspection recovers it from the name.\n */\nexport function sqliteDecimalConstraintName(\n columnName: string,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${columnName}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/** The namespace VibORM reserves for the constraints it writes itself. */\nconst RESERVED_CONSTRAINT_PREFIX = \"viborm_decimal_\";\n\n/** `<precision>_<scale>`: what follows the column name in a reserved name. */\nconst RESERVED_CONSTRAINT_TAIL = /^(\\d+)_(\\d+)$/;\n\n/**\n * The declared domain of one column, read back out of the `CREATE TABLE` text\n * SQLite stored — or `undefined` when this column carries no reserved\n * constraint. The matching PRAGMA type and nullability travel with the column:\n * the stored clause is owned only when it is the exact writer rendering for\n * those physical facts.\n *\n * This PARSES, it does not search. The name alone is not evidence: SQLite\n * stores the statement verbatim, so any string literal a user can write — an\n * enum value, a string default, an index predicate — appears in the same text\n * and can spell VibORM's reserved prefix. A first-hit substring scan therefore\n * reads a user's data as a descriptor, and with an earlier offset it OVERRIDES\n * the real constraint: the next push plans a conversion between two domains\n * neither side declared and rewrites every stored coefficient. So the reader\n * walks the column-definition list the same quote-aware way\n * `partialIndexPredicate` walks a `CREATE INDEX` (`introspect.ts`), finds real\n * `CONSTRAINT <name> CHECK (…)` clauses, and binds each to the column definition\n * it actually sits in.\n *\n * A reserved name the module could not have written is REFUSED, not ignored.\n * Ignoring it is not the safe reading: the name is in a namespace only this\n * module writes, so its presence means either a corrupted carrier or a\n * collision, and both make every later push either wrong (a conversion between\n * invented domains) or non-convergent (a descriptor the desired side can never\n * match). The refusal names the constraint so the estate can be repaired.\n *\n * Ownership is proved by RE-RENDERING: the clause must be, byte for byte, what\n * {@link sqliteDecimalCheck} would emit for this column at the descriptor the\n * name declares. That is the only test that cannot be forged by a name alone,\n * and it is exact because SQLite re-spells nothing it stores.\n */\nexport function readSqliteDecimalConstraint(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n if (!tableSql) return undefined;\n // The reserved namespace has to appear at all before the statement is worth\n // parsing: introspection reads every column of every table, and the\n // overwhelming majority carry no decimal.\n if (!tableSql.includes(RESERVED_CONSTRAINT_PREFIX)) return undefined;\n\n let found: DecimalDescriptor | undefined;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(RESERVED_CONSTRAINT_PREFIX)) continue;\n // This reader is invoked once for every PRAGMA column. A reserved\n // column constraint is adjudicated when its own physical column is in\n // hand, because only that invocation knows the type and nullability the\n // database actually reported. TABLE constraints have no such invocation\n // and are always namespace squatters.\n if (\n definition.columnName !== undefined &&\n definition.columnName !== column.name\n ) {\n continue;\n }\n const descriptor = ownedDescriptor(\n definition,\n clause,\n column,\n escapeIdentifier\n );\n if (descriptor === undefined) {\n throw new MigrationError(\n `Constraint \"${clause.name}\" uses reserved fixed-decimal namespace with unrecognized definition.`,\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: {\n constraint: clause.name,\n // Absent for a TABLE constraint, which belongs to no column.\n ...(definition.columnName === undefined\n ? {}\n : { column: definition.columnName }),\n },\n }\n );\n }\n if (found !== undefined) {\n throw new MigrationError(\n `Column \"${column.name}\" has multiple fixed-decimal descriptors: ${describeDecimalDomain(found)} and ${describeDecimalDomain(descriptor)}.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { column: column.name } }\n );\n }\n found = descriptor;\n }\n }\n return found;\n}\n\n/**\n * Whether one catalog column is the checked scaled-integer storage VibORM\n * writes for `descriptor`: INTEGER (TEXT for a list) carrying exactly that\n * descriptor's reserved CHECK. Typed queries never ask; `viborm check --db`\n * does, for a table VibORM did not create.\n */\nexport function isSqliteDecimalStorage(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n descriptor: DecimalDescriptor,\n kind: DecimalStorageKind,\n escapeIdentifier: (name: string) => string\n): boolean {\n const stored = readSqliteDecimalConstraint(\n tableSql,\n column,\n escapeIdentifier\n );\n return (\n sameDecimalDescriptor(stored, descriptor) &&\n sqliteDecimalStorageKind({ type: column.type, decimal: stored }) === kind\n );\n}\n\n/** One top-level entry of a `CREATE TABLE`'s parenthesized definition list. */\n/**\n * The reserved constraint this clause carries, or `undefined` when the clause\n * is one this module could not have written.\n *\n * Three things must hold together, and each is a way the namespace gets\n * squatted: the clause sits in a COLUMN definition (never a table constraint,\n * which VibORM never writes); its name is this column's name followed by the\n * two numbers; and the whole clause re-renders byte for byte.\n */\nfunction ownedDescriptor(\n definition: SqliteTableDefinition,\n clause: SqliteConstraintClause,\n physicalColumn: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n const column = definition.columnName;\n if (column === undefined) return undefined;\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${column}_`;\n if (!clause.name.startsWith(prefix)) return undefined;\n const match = RESERVED_CONSTRAINT_TAIL.exec(clause.name.slice(prefix.length));\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"sqlite\");\n if (descriptor === undefined) return undefined;\n // PRAGMA owns the physical type and nullability. Re-render ONLY the shape\n // those facts permit; trying all four writer spellings lets an impossible\n // INTEGER/list or nullable/non-null carrier masquerade as a valid domain.\n const kind = sqliteDecimalStorageKind({\n ...physicalColumn,\n decimal: descriptor,\n });\n if (kind === undefined) return undefined;\n const rendered = sqliteDecimalCheck(\n physicalColumn,\n descriptor,\n kind,\n escapeIdentifier\n );\n if (definition.text.startsWith(rendered, clause.offset)) {\n return descriptor;\n }\n return undefined;\n}\n\n/**\n * Whether one generated table definition carries this column's reserved\n * decimal descriptor name in the structural column clause that owns it.\n *\n * Apply uses this only after it has proved the surrounding statement sequence\n * is VibORM's exact generated table-recreation program. It distinguishes the\n * decimal-column rename variant, whose copy expression needs no conversion\n * sentinel, from an unrelated recreation of a table that merely contains some\n * other decimal column.\n */\nexport function sqliteColumnDefinitionCarriesDecimalDescriptor(\n tableSql: string,\n columnName: string\n): boolean {\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${columnName}_`;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n if (definition.columnName !== columnName) continue;\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(prefix)) continue;\n const match = RESERVED_CONSTRAINT_TAIL.exec(\n clause.name.slice(prefix.length)\n );\n if (\n match &&\n readStoredDecimalDescriptor(match[1], match[2], \"sqlite\") !== undefined\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/** `10^precision - 1`: the widest coefficient the domain can hold. */\nfunction maxCoefficient(precision: number): bigint {\n return 10n ** BigInt(precision) - 1n;\n}\n\n/**\n * The reserved CHECK a SQLite decimal column carries, as a complete column\n * constraint (`CONSTRAINT <name> CHECK (<body>)`).\n *\n * A scalar is the signed integer coefficient. A list is TEXT holding a JSON\n * array of coefficient strings. NULL passes only for a nullable column.\n */\nexport function sqliteDecimalCheck(\n column: { readonly name: string; readonly nullable: boolean },\n descriptor: DecimalDescriptor,\n kind: DecimalStorageKind,\n escapeIdentifier: (name: string) => string\n): string {\n const col = escapeIdentifier(column.name);\n const name = escapeIdentifier(\n sqliteDecimalConstraintName(column.name, descriptor)\n );\n const bound = maxCoefficient(descriptor.precision).toString();\n const body =\n kind === \"list\"\n ? `typeof(${col}) = 'text' AND json_valid(${col}) AND json_type(${col}) = 'array'`\n : `typeof(${col}) = 'integer' AND ${col} BETWEEN -${bound} AND ${bound}`;\n const guarded = column.nullable ? `${col} IS NULL OR (${body})` : body;\n return `CONSTRAINT ${name} CHECK (${guarded})`;\n}\n\n/**\n * The value a row lands in the rebuilt table when it does not fit the target\n * domain. It fails the target column's own reserved CHECK and aborts the whole\n * recreation atomically.\n */\nconst SCALAR_SENTINEL = \"'viborm:decimal-out-of-domain'\";\nconst LIST_SENTINEL = \"'viborm:decimal-list-out-of-domain'\";\n\ninterface Rescale {\n /** `10^|scale delta|`, as an integer literal. */\n readonly factor: string;\n readonly direction: \"up\" | \"down\" | \"none\";\n /** The inclusive absolute bound the SOURCE coefficient must satisfy. */\n readonly bound: string;\n}\n\n/** The one arithmetic decision behind every SQLite conversion expression. */\nfunction rescale(\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor\n): Rescale {\n const targetMax = maxCoefficient(to.precision);\n const sourceMax = from ? maxCoefficient(from.precision) : targetMax;\n const delta = to.scale - (from?.scale ?? 0);\n if (delta === 0) {\n return {\n factor: \"1\",\n direction: \"none\",\n bound: min(sourceMax, targetMax).toString(),\n };\n }\n if (delta > 0) {\n const factor = 10n ** BigInt(delta);\n return {\n factor: factor.toString(),\n direction: \"up\",\n bound: min(sourceMax, targetMax / factor).toString(),\n };\n }\n const factor = 10n ** BigInt(-delta);\n return {\n factor: factor.toString(),\n direction: \"down\",\n bound: min(sourceMax, targetMax * factor).toString(),\n };\n}\n\nfunction min(a: bigint, b: bigint): bigint {\n return a < b ? a : b;\n}\n\n/**\n * The per-column source expression used by SQLite table recreation. It\n * converts stored values from `from`'s physical spelling to `to`'s without a\n * REAL intermediate and routes every malformed or out-of-domain value to the\n * target CHECK's sentinel.\n */\nexport function sqliteDecimalCopyExpression(\n source: string,\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor,\n kind: DecimalStorageKind\n): string {\n const { factor, direction, bound } = rescale(from, to);\n const exact = direction === \"down\" ? ` AND ${source} % ${factor} = 0` : \"\";\n if (kind === \"scalar\") {\n const converted = convertedCoefficient(source, direction, factor);\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'integer' ` +\n `AND ${source} BETWEEN -${bound} AND ${bound}${exact} THEN ${converted} ` +\n `ELSE ${SCALAR_SENTINEL} END`\n );\n }\n return listCopyExpression(source, direction, factor, bound);\n}\n\nfunction convertedCoefficient(\n operand: string,\n direction: Rescale[\"direction\"],\n factor: string\n): string {\n if (direction === \"up\") return `${operand} * ${factor}`;\n if (direction === \"down\") return `${operand} / ${factor}`;\n return operand;\n}\n\n/** Convert a SQLite JSON coefficient-string list without losing order. */\nfunction listCopyExpression(\n source: string,\n direction: Rescale[\"direction\"],\n factor: string,\n bound: string\n): string {\n const member = `\"m\".\"value\"`;\n const asInteger = `CAST(${member} AS INTEGER)`;\n const exact = direction === \"down\" ? ` AND ${asInteger} % ${factor} = 0` : \"\";\n const admissible =\n `\"m\".\"type\" = 'text' AND CAST(${asInteger} AS TEXT) = ${member} ` +\n `AND ${asInteger} BETWEEN -${bound} AND ${bound}${exact}`;\n const converted = `CAST(${convertedCoefficient(`CAST(\"value\" AS INTEGER)`, direction, factor)} AS TEXT)`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'text' AND json_valid(${source}) = 1 THEN ` +\n `CASE WHEN json_type(${source}) = 'array' THEN CASE WHEN ` +\n `(SELECT count(*) FROM json_each(${source}) AS \"m\" WHERE NOT (${admissible})) = 0 THEN ` +\n `(SELECT json_group_array(${converted}) FROM (SELECT \"value\" FROM json_each(${source}) AS \"m\" ORDER BY \"m\".\"key\")) ` +\n `ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END`\n );\n}\n","/**\n * The migration layer's decimal renders.\n *\n * `@validation/primitives/decimal-codec` owns everything VALUE-shaped: the\n * grammar, canonical text, the logical <-> coefficient conversion, and the two\n * DDL renderings (`decimalColumnType`, `decimalDefaultText`). This module owns\n * what only a MIGRATION asks — the questions whose subject is a pair of\n * descriptors or a stored column rather than a value:\n *\n * - whether two snapshots describe the same domain, whether a change narrows\n * it, and which scalar/list storage shape a decimal column carries;\n * - the MySQL column-comment marker for a JSON-backed list; and\n * - the shared validation predicates used by native-decimal migration drivers.\n *\n * Everything here is PURE and connection-free: migration DDL is generated into\n * durable artifacts, so none of it may consult a database.\n *\n * Nothing here re-derives a precision or a scale. Every entry takes the frozen\n * descriptor its caller already holds (plan §1.1: no migration component stores\n * an independent precision or scale decision).\n */\n\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n readStoredDecimalDescriptor,\n sameDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { ColumnDef } from \"./types\";\n\n/**\n * Whether moving from `from` to `to` SHRINKS the set of representable values —\n * the destructive half of a descriptor change.\n *\n * Two independent limits move: the fractional digits (`scale`) and the integer\n * digits (`precision - scale`). A change that lowers either one can find a\n * stored value it cannot hold, and the conversion then refuses; a change that\n * raises both is exact for every existing row. Widening the scale while keeping\n * the precision therefore counts as narrowing, because it takes an integer\n * digit away — `NUMERIC(10,2)` holds 99999999.99 and `NUMERIC(10,5)` does not.\n */\nexport function decimalDomainNarrows(\n from: DecimalDescriptor,\n to: DecimalDescriptor\n): boolean {\n const integerDigitsLost =\n to.precision - to.scale < from.precision - from.scale;\n return integerDigitsLost || to.scale < from.scale;\n}\n\n/**\n * Whether this alteration moves stored values INTO a declared decimal domain —\n * the ONE signal every provider's conversion route reads.\n *\n * Only the TARGET has to declare a domain. An absent source descriptor does not\n * make the change descriptor-free: it means the stored values were written\n * under some other reading, and adopting them under this one is exactly the\n * transition §7.3 governs. Skipping the conversion there is what silently\n * reinterprets a PostgreSQL `numeric` by rounding it through the `USING` cast,\n * and what copies a SQLite integer into a coefficient column at a scale it was\n * never written at. Each provider answers the absent source in its own terms —\n * PostgreSQL's target-domain CHECK is a complete proof on its own, and the\n * SQLite copy reads an untyped `INTEGER` as the logical integer it is — but the\n * QUESTION is one, so this is one predicate.\n *\n * The physical type is part of it beside the descriptor, because a scalar that\n * becomes a list keeps its precision and scale while changing storage class\n * completely. It is compared case-insensitively, the same reading the differ\n * takes: one snapshot side is the serializer's spelling and the other is\n * whatever the catalog answered.\n */\nexport function decimalConversionRequired(\n from: ColumnDef,\n to: ColumnDef\n): boolean {\n if (to.decimal === undefined) return false;\n return (\n !sameDecimalDescriptor(from.decimal, to.decimal) ||\n from.type.toUpperCase() !== to.type.toUpperCase()\n );\n}\n\n/**\n * Whether this alteration can lose data because the target domain is smaller.\n * The migration differ's destructive classifier is the sole consumer-facing\n * decision owner; this function owns only the decimal-domain question it asks.\n */\nexport function decimalChangeNarrows(from: ColumnDef, to: ColumnDef): boolean {\n if (from.decimal === undefined || to.decimal === undefined) return false;\n return decimalDomainNarrows(from.decimal, to.decimal);\n}\n\n/**\n * A storage shape, spelled for a refusal MESSAGE.\n *\n * `undefined` is a real answer here and it has to say so: it means the column's\n * declared type is neither of the two spellings this layer writes, which is a\n * different fact from \"the domain moved\" and must not be reported as one.\n */\nexport function describeDecimalStorageKind(\n kind: DecimalStorageKind | undefined\n): string {\n return kind ?? \"unrecognized\";\n}\n\n// =============================================================================\n// THE MYSQL DESCRIPTOR CARRIER\n// =============================================================================\n\n/**\n * The deterministic VibORM-owned column-comment marker for a JSON-backed MySQL\n * decimal list.\n *\n * A `DECIMAL(p,s)` column spells its own domain, but a decimal LIST is stored\n * as `JSON` (MySQL has no array type), and JSON carries nothing. The marker is\n * that column's descriptor, and it is the whole comment: introspection\n * recognizes only the exact marker (§6.2), so a hand-written comment that\n * merely mentions a decimal is not a descriptor.\n */\nexport function mysqlDecimalListMarker(descriptor: DecimalDescriptor): string {\n return `viborm:decimal(${descriptor.precision},${descriptor.scale})`;\n}\n\nconst MYSQL_LIST_MARKER = /^viborm:decimal\\((\\d+),(\\d+)\\)$/;\n\n/**\n * The domain a MySQL column comment declares, or `undefined` when it is not the\n * reserved marker. A marker-shaped comment with an invalid domain refuses.\n */\nexport function readMysqlDecimalListMarker(\n comment: string | null | undefined\n): DecimalDescriptor | undefined {\n if (!comment) return undefined;\n const match = MYSQL_LIST_MARKER.exec(comment);\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"mysql\");\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n \"MySQL column comment has invalid reserved decimal-list marker.\",\n VibORMErrorCode.INVALID_INPUT\n );\n}\n\n// =============================================================================\n// THE DIALECT STORAGE SHAPES\n// =============================================================================\n\n/**\n * How one dialect physically holds a decimal: one value, or a container of\n * them. The migration layer reads it off the column rather than the model,\n * because a snapshot side may have come from introspection.\n */\nexport type { DecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\nimport {\n type DecimalStorageKind,\n sqliteDecimalStorageKind,\n} from \"../adapters/databases/sqlite/storage/decimal\";\n\nexport {\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nexport { sqliteDecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\n/**\n * The storage shape of a MySQL decimal column, or `undefined` when the column\n * holds no decimal.\n *\n * A scalar spells its own domain in `DECIMAL(p,s)` — introspection reads it\n * back lowercased, so the comparison is case-insensitive — and a list is the\n * `JSON` container every MySQL list gets, carrying its domain in the\n * column-comment marker instead.\n *\n * A MODIFIER after the domain does not change the storage shape.\n * `decimal(10,2) unsigned` and `decimal(10,2) zerofill` are the same physical\n * decimal, introspected verbatim through `formatColumnType`'s modifier arm, and\n * a shape of `undefined` for them would refuse the very ALTER that normalizes\n * them — an estate that could never converge. The domain token itself still has\n * to match the descriptor EXACTLY, so `DECIMAL(10,20)` is not `DECIMAL(10,2)`\n * with a modifier.\n */\nexport function mysqlDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \" \").trim();\n const scalar = decimalColumnType(\"mysql\", column.decimal);\n if (type === scalar || type.startsWith(`${scalar} `)) return \"scalar\";\n return type === MYSQL_DECIMAL_LIST_TYPE ? \"list\" : undefined;\n}\n\n/** PostgreSQL's native scalar and native-array decimal storage shapes. */\nexport function postgresDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \"\").trim();\n const scalar = decimalColumnType(\"pg\", column.decimal);\n if (type === scalar) return \"scalar\";\n return type === `${scalar}[]` ? \"list\" : undefined;\n}\n\n/**\n * The provider-independent scalar/list identity of a migration decimal.\n *\n * Rename detection needs the shape, not typmod equality: changing a decimal\n * descriptor necessarily changes PostgreSQL/MySQL's physical type spelling,\n * while it keeps the same value/container identity and can still be a native\n * column rename followed by one exact conversion.\n */\nexport function migrationDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n return (\n postgresDecimalStorageKind(column) ??\n mysqlDecimalStorageKind(column) ??\n sqliteDecimalStorageKind(column)\n );\n}\n\n/** MySQL has no array type; every list is JSON, decimal lists included. */\nexport const MYSQL_DECIMAL_LIST_TYPE = \"JSON\";\n\n/**\n * TEXT, not the blanket `JSON` every other SQLite list gets: the list's\n * reserved CHECK asserts `typeof = 'text'`, and `JSON` has NUMERIC affinity\n * under SQLite's rules (it contains none of INT/CHAR/CLOB/TEXT/BLOB/REAL/FLOA/\n * DOUB), which would try to convert a numeric-looking container on the way in.\n */\nexport const SQLITE_DECIMAL_LIST_TYPE = \"TEXT\";\n\n// =============================================================================\n// THE PostgreSQL / MySQL VALIDATION PREDICATE\n// =============================================================================\n\n/**\n * The transient constraint a native-decimal conversion validates through.\n *\n * It is added, kept live ACROSS the type change, and dropped after. That\n * ordering is the whole design: the constraint proves every EXISTING row\n * already fits the target domain, and — because it stays — no concurrent write\n * can land a value the target would have to round while the conversion runs.\n * It is how \"while writes are excluded\" is spelled on MySQL, whose `LOCK\n * TABLES` the artifact classifier refuses as a transaction leader.\n */\n/**\n * The compact identity of one transient conversion proof.\n *\n * The table and column deliberately stay out of this identity: MySQL can\n * publish a different table-name spelling through `lower_case_table_names`,\n * while an interrupted proof must authenticate before the original spelling\n * is available again. The exact catalog CHECK authenticates its table and\n * column instead. Kind, precision and scale are already a small, bounded,\n * collision-free identity, so spelling them directly is both shorter and\n * stronger than hashing them: recovery can authenticate the declared proof\n * without searching or trusting a lossy digest.\n */\nexport function decimalConversionConstraintName(\n kind: DecimalStorageKind,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${kind === \"scalar\" ? \"s\" : \"l\"}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/**\n * \"The target domain admits this value UNCHANGED\", as a CHECK body.\n *\n * One idea, spelled in each dialect's cast syntax: a cast to the target type\n * rounds a value with too many fractional digits and refuses one with too many\n * integer digits, so a value that survives the cast intact is exactly a value\n * the conversion does not have to change. That is §7.3's rule — \"convert only\n * when every value fits\", and \"no descriptor change rounds existing data\" —\n * without a per-digit predicate. PostgreSQL's `numeric` also admits special\n * non-finite values, and `NaN` compares equal to itself, so finiteness is an\n * independent part of the proof. Arrays prove it for every member beside the\n * existing NULL-member refusal, while the outer `column IS NULL` continues to\n * admit a nullable whole list.\n *\n * The type token is the one `decimalColumnType` produced for the target column,\n * array suffix included; nothing here re-spells it.\n */\nexport function postgresDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n const unchanged = `${column} = ${column}::${targetType}`;\n if (targetType.endsWith(\"[]\")) {\n const hasNoNonFiniteMember = [\"NaN\", \"Infinity\", \"-Infinity\"]\n .map((value) => `array_position(${column}, '${value}'::numeric) IS NULL`)\n .join(\" AND \");\n return `${column} IS NULL OR (array_position(${column}, NULL) IS NULL AND ${hasNoNonFiniteMember} AND ${unchanged})`;\n }\n const hasFiniteValue = `${column} NOT IN ('NaN'::numeric, 'Infinity'::numeric, '-Infinity'::numeric)`;\n return `${column} IS NULL OR (${hasFiniteValue} AND ${unchanged})`;\n}\n\n/** {@link postgresDecimalFitsCheck}'s MySQL spelling. */\nexport function mysqlDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n return `${column} IS NULL OR ${column} = CAST(${column} AS ${targetType})`;\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalFitsCheck}. */\nexport function mysqlDecimalFitsCatalogCheck(\n column: string,\n targetType: string\n): string {\n return `((${column} is null) or (${column} = cast(${column} as ${targetType})))`;\n}\n\nfunction mysqlDecimalListCheckParts(\n column: string,\n descriptor: DecimalDescriptor\n): { readonly rendered: string; readonly normalizedContainer: string } {\n const coefficient = `(\"0\"|\"-?[1-9][0-9]{0,${descriptor.precision - 1}}\")`;\n return {\n rendered: `CAST(${column} AS CHAR CHARACTER SET utf8mb4)`,\n normalizedContainer: `^.(${coefficient}(, ${coefficient})*)?.$`,\n };\n}\n\n/**\n * A MySQL JSON decimal list is already in the target domain without changing\n * one stored byte.\n *\n * MySQL CHECK expressions cannot contain a subquery, so this validates the\n * provider's own normalized JSON rendering as one anchored language. Every\n * member must be a JSON string carrying the canonical coefficient grammar,\n * and the digit bound comes from the narrower descriptor that must remain true\n * across the marker change. `LEFT` and `RIGHT` prove the two brackets while\n * the anchored regular expression uses one character for each. That avoids a\n * backslash whose SQL meaning would depend on `NO_BACKSLASH_ESCAPES`.\n */\nexport function mysqlDecimalListFitsCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n return (\n `${column} IS NULL OR (` +\n `LEFT(${rendered}, 1) = '[' AND RIGHT(${rendered}, 1) = ']' AND ` +\n `REGEXP_LIKE(${rendered}, '${normalizedContainer}', 'c'))`\n );\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalListFitsCheck}. */\nexport function mysqlDecimalListFitsCatalogCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n const catalogRendered = rendered.replace(\n \"CHAR CHARACTER SET\",\n \"char charset\"\n );\n return (\n `((${column} is null) or (` +\n `(${`LEFT(${catalogRendered}, 1)`} = '[') and ` +\n `(${`RIGHT(${catalogRendered}, 1)`} = ']') and ` +\n `${`REGEXP_LIKE(${catalogRendered}, '${normalizedContainer}', 'c')`}))`\n );\n}\n","/**\n * MySQL's string literal: one spelling for every statement VibORM writes a\n * value into, the DDL of a migration (`migrations/drivers/type-mapping.ts`\n * re-exports it for both snapshot producers) and the body of a view\n * (`adapters/inline-literals.ts`).\n */\n\n/**\n * THE characters MySQL's string literals carry as an escape — the one table\n * both directions read.\n *\n * MySQL reads `\\` inside a string literal as an escape introducer (only\n * `NO_BACKSLASH_ESCAPES` stops it, a mode this estate never sets and the\n * pinned session does not promise), so doubling `'` alone spells a DIFFERENT\n * value: `DEFAULT ('a\\b')` stored a BACKSPACE and `DEFAULT ('end\\')` did not\n * even parse. The four control characters are escaped for the same reason\n * they cannot be written raw: a generated statement is also the review blob,\n * which is UTF-8/LF with no carriage returns (`sql-blob.ts`).\n *\n * `information_schema` prints an expression default with exactly these escapes\n * plus `\\'` (measured on 8.4.11 — every other character, tab and backspace\n * included, is printed raw), so `mysql/introspect.ts` undoes this same table\n * before re-spelling the value through `mysqlStringLiteral` below.\n */\nexport const MYSQL_LITERAL_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"\\\\\", \"\\\\\\\\\"],\n [\"\\n\", \"\\\\n\"],\n [\"\\r\", \"\\\\r\"],\n [\"\\0\", \"\\\\0\"],\n [\"\\u001a\", \"\\\\Z\"],\n]);\n\n/**\n * THE MySQL string literal — one spelling, both snapshot producers.\n *\n * The desired side writes it (`MySQLMigrationDriver.escapeValue`) and the live\n * side re-spells the value it read out of the catalog through the very same\n * function (`mysql/introspect.ts`), because two spellings of ONE value read as\n * a changed column on every push and as the mismatch the final push\n * attestation refuses.\n */\nexport function mysqlStringLiteral(value: string): string {\n let escaped = \"\";\n for (const character of value) {\n escaped += MYSQL_LITERAL_ESCAPES.get(character) ?? character;\n }\n return `'${escaped.replace(/'/g, \"''\")}'`;\n}\n","/**\n * Centralized Type Mapping for Migration Drivers\n *\n * Maps VibORM scalar types to native database column types.\n * Uses constants from native-types.ts to ensure consistency.\n */\n\nimport { PG, SQLITE } from \"@schema/scalars/native-types\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n} from \"@validation/primitives/decimal-codec\";\nimport {\n MYSQL_LITERAL_ESCAPES,\n mysqlStringLiteral,\n} from \"../../adapters/databases/mysql/string-literal\";\nimport { SQLITE_GEO_POINT_TYPE } from \"../../adapters/databases/sqlite/storage/geo-point\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { SQLITE_DECIMAL_LIST_TYPE } from \"../decimal\";\n\n// =============================================================================\n// TYPE MAPPING CONSTANTS\n// =============================================================================\n\n/**\n * Default PostgreSQL type mappings for each VibORM scalar type.\n * Uses the same type names as defined in native-types.ts.\n */\nexport const PG_TYPE_DEFAULTS = {\n string: PG.STRING.TEXT.type,\n int: PG.INT.INTEGER.type,\n number: PG.FLOAT.DOUBLE_PRECISION.type,\n boolean: PG.BOOLEAN.BOOLEAN.type,\n datetime: PG.DATETIME.TIMESTAMP(3).type,\n datetimetz: PG.DATETIME.TIMESTAMPTZ(3).type,\n date: PG.DATETIME.DATE.type,\n time: PG.DATETIME.TIME(3).type,\n timetz: PG.DATETIME.TIMETZ(3).type,\n bigint: PG.BIGINT.BIGINT.type,\n json: PG.JSON.JSONB.type,\n blob: PG.BLOB.BYTEA.type,\n vector: \"vector\",\n point: \"geography(Point,4326)\",\n enum: PG.STRING.TEXT.type,\n} as const;\n\n/**\n * Default SQLite type mappings for each VibORM scalar type.\n * SQLite has limited type affinity - most types map to TEXT, INTEGER, REAL, or BLOB.\n */\nexport const SQLITE_TYPE_DEFAULTS = {\n string: SQLITE.STRING.TEXT.type,\n int: SQLITE.INT.INTEGER.type,\n number: SQLITE.FLOAT.REAL.type,\n boolean: SQLITE.BOOLEAN.INTEGER.type,\n datetime: SQLITE.DATETIME.TEXT.type,\n date: SQLITE.DATETIME.TEXT.type,\n time: SQLITE.DATETIME.TEXT.type,\n bigint: SQLITE.BIGINT.INTEGER.type,\n json: \"JSON\", // SQLite JSON functions work with TEXT but JSON is more semantic\n blob: SQLITE.BLOB.BLOB.type,\n vector: \"JSON\", // Store as JSON array in SQLite\n point: SQLITE_GEO_POINT_TYPE,\n enum: SQLITE.STRING.TEXT.type,\n} as const;\n\n/**\n * Default MySQL type mappings for each VibORM scalar type.\n * MySQL has full type support but uses TINYINT(1) for booleans\n * and doesn't support native arrays (use JSON instead).\n */\nexport const MYSQL_TYPE_DEFAULTS = {\n string: \"TEXT\",\n int: \"INT\",\n number: \"DOUBLE\",\n boolean: \"TINYINT(1)\", // MySQL uses TINYINT(1) for boolean\n datetime: \"DATETIME(3)\", // Use DATETIME(3) to preserve JavaScript Date millisecond precision\n datetimetz: \"DATETIME(3)\", // MySQL DATETIME can store with timezone via application\n date: \"DATE\",\n time: \"TIME(3)\", // Use TIME(3) to preserve millisecond precision\n timetz: \"TIME(3)\", // MySQL TIME doesn't have timezone variant\n bigint: \"BIGINT\",\n json: \"JSON\",\n blob: \"BLOB\",\n vector: \"JSON\", // No native vector support, use JSON\n point: \"POINT SRID 4326\",\n enum: \"TEXT\", // Default for unspecified enums; usually use inline ENUM()\n} as const;\n\n/**\n * THE MySQL inline enum type — one spelling, both snapshot producers.\n *\n * MySQL has no standalone enum object: the values ARE the column type, so this\n * text is also the enum's identity in a snapshot. The desired side spells it\n * (`MySQLMigrationDriver.getEnumColumnType`) and the live side re-spells the\n * catalog's `COLUMN_TYPE` through the very same function\n * (`mysql/introspect.ts`), because `information_schema` prints its own\n * canonical rendering — `enum('a','b')`, no space after the comma, and an\n * identity of its own invention — and two spellings of ONE type read as a\n * changed column on every push and as the mismatch the final push attestation\n * refuses.\n *\n * A member IS a MySQL string literal, so it is spelled by the one function that\n * spells those (`mysqlStringLiteral` below) rather than by a second rule of its\n * own. Doubling `'` alone was that second rule: `ENUM('a\\b')` declared a member\n * holding a BACKSPACE, `ENUM('end\\')` did not parse at all, and once the\n * default beside such a member went through the shared spelling the two\n * disagreed and MySQL refused the CREATE/MODIFY with errno 1067 (all measured).\n */\nexport function mysqlEnumType(values: readonly string[]): string {\n return `ENUM(${values.map((value) => mysqlStringLiteral(value)).join(\", \")})`;\n}\n\nconst ENUM_VALUES_REGEX = /enum\\((.+)\\)/i;\n\n/**\n * What MySQL's printer writes, read backwards: the WRITE table\n * (`mysqlStringLiteral`) inverted, plus the apostrophe, which MySQL prints as\n * `\\'` although the DDL spelling doubles it instead. Every other character —\n * tab, backspace, `\"` — is printed raw (measured on 8.4.11), so an escape\n * outside this table is one this inverse does not own.\n *\n * ONE table, both catalog vocabularies, because both are MySQL printing a\n * string literal it parsed: the expression default below, and an ENUM's members\n * inside `COLUMN_TYPE`. The enum printer writes a strict SUBSET of it (`\\\\`,\n * `\\n`, `\\r`, `\\0`; it doubles `'` and prints ctrl-Z raw, measured), so reading\n * one table backwards covers both and leaves the same remainder unowned.\n */\nexport const MYSQL_PRINTED_CHARACTERS: ReadonlyMap<string, string> = new Map([\n [\"'\", \"'\"],\n ...[...MYSQL_LITERAL_ESCAPES].map(\n ([character, sequence]) =>\n [sequence.slice(1), character] as [string, string]\n ),\n]);\n\n/**\n * Parse enum values from MySQL COLUMN_TYPE string, or `null` when the catalog\n * spelled one this inverse does not own.\n *\n * Handles values containing commas, doubled single quotes (''), and the\n * backslash escapes MySQL's printer writes (`MYSQL_PRINTED_CHARACTERS`).\n * Example: \"enum('a,b','it''s','c')\" -> ['a,b', \"it's\", 'c']\n * Example: String.raw`enum('a\\\\b','line1\\nline2')` -> [\"a\\\\b\", \"line1\\nline2\"]\n *\n * Reading `\\x` as a bare `x` — which is what \"skip the backslash\" does — turned\n * the printed `\\n` of a declared NEWLINE into the letter `n`, a value the\n * declaration never held. An escape outside the table is not one this server\n * printed for a member the estate spelled, so inverting it would be a guess:\n * the column keeps MySQL's own `COLUMN_TYPE` instead and the push fails at the\n * final attestation, the same fail-closed direction the string inverse takes.\n */\nexport function parseMySqlEnumValues(columnType: string): string[] | null {\n const match = columnType.match(ENUM_VALUES_REGEX);\n if (!match?.[1]) return null;\n\n const content = match[1];\n const values: string[] = [];\n let i = 0;\n\n while (i < content.length) {\n // Skip whitespace and commas\n while (i < content.length && (content[i] === \" \" || content[i] === \",\")) {\n i++;\n }\n if (i >= content.length) break;\n\n // Expect opening quote\n if (content[i] !== \"'\") {\n i++;\n continue;\n }\n i++; // Skip opening quote\n\n // Collect value until closing quote (handle escaped quotes '' and \\')\n let value = \"\";\n while (i < content.length) {\n if (content[i] === \"\\\\\" && i + 1 < content.length) {\n // Backslash escape - the character MySQL's printer wrote it for\n const printed = MYSQL_PRINTED_CHARACTERS.get(content[i + 1] ?? \"\");\n if (printed === undefined) return null;\n value += printed;\n i += 2;\n } else if (content[i] === \"'\" && content[i + 1] === \"'\") {\n // Doubled quote escape - add single quote and skip both\n value += \"'\";\n i += 2;\n } else if (content[i] === \"'\") {\n // Closing quote\n i++;\n break;\n } else {\n value += content[i];\n i++;\n }\n }\n values.push(value);\n }\n\n return values.length > 0 ? values : null;\n}\n\n// =============================================================================\n// TYPE MAPPING FUNCTIONS\n// =============================================================================\n\nexport interface ScalarTypeContext {\n type: string;\n array?: boolean;\n withTimezone?: boolean;\n dimension?: number | undefined;\n /**\n * The declared fixed-decimal domain, for a `decimal` scalar. Every decimal\n * type on every dialect is DERIVED from it — there is no unconstrained\n * `numeric`, no `DECIMAL(65,30)`, and no TEXT decimal to fall back to.\n */\n decimal?: DecimalDescriptor | undefined;\n}\n\n/**\n * The declared domain of a decimal context.\n *\n * A decimal column with no descriptor has no physical type at all: the numbers\n * cannot be inferred from storage, a value, a driver, or an operation (plan\n * §1.1), so the alternative to refusing is inventing a second precision — which\n * is exactly the `DECIMAL(65,30)` this program deletes. The public decimal\n * factory cannot produce such a state; a hand-built or externally-deserialized\n * scalar state can, and this is where it stops.\n */\nfunction requireDecimalDomain(context: ScalarTypeContext): DecimalDescriptor {\n if (context.decimal) return context.decimal;\n throw new MigrationError(\n \"A decimal column has no declared precision and scale. \" +\n \"The fixed-decimal domain is declared once, on the scalar, and every physical type is derived from it.\",\n VibORMErrorCode.INVALID_INPUT,\n { meta: { scalarType: \"decimal\" } }\n );\n}\n\n/**\n * The tables own ordinary defaults. Their timezone aliases are selected by\n * withTimezone, not admitted as independent scalar kinds. Unknown and inherited\n * keys retain the string fallback.\n */\nfunction defaultType(\n defaults: Readonly<Record<string, string>> & { readonly string: string },\n type: string\n): string {\n return type !== \"datetimetz\" &&\n type !== \"timetz\" &&\n Object.hasOwn(defaults, type)\n ? defaults[type]!\n : defaults.string;\n}\n\n/** PostgreSQL keeps native lists, exact decimal typmods and vector dimensions. */\nexport function getPostgresType(context: ScalarTypeContext): string {\n const type = context.type;\n let baseType: string;\n if (type === \"decimal\")\n baseType = decimalColumnType(\"pg\", requireDecimalDomain(context));\n else if (type === \"datetime\" && context.withTimezone)\n baseType = PG_TYPE_DEFAULTS.datetimetz;\n else if (type === \"time\" && context.withTimezone)\n baseType = PG_TYPE_DEFAULTS.timetz;\n else if (type === \"vector\" && context.dimension !== undefined)\n baseType = `${PG_TYPE_DEFAULTS.vector}(${context.dimension})`;\n else baseType = defaultType(PG_TYPE_DEFAULTS, type);\n return context.array ? `${baseType}[]` : baseType;\n}\n/** SQLite lists use JSON, except the checked decimal TEXT container. */\nexport function getSQLiteType(context: ScalarTypeContext): string {\n if (context.array)\n return context.type === \"decimal\" ? SQLITE_DECIMAL_LIST_TYPE : \"JSON\";\n const type = context.type;\n return type === \"decimal\"\n ? decimalColumnType(\"sqlite\", requireDecimalDomain(context))\n : defaultType(SQLITE_TYPE_DEFAULTS, type);\n}\n\n/** MySQL lists use JSON; scalar decimals retain their declared precision/scale. */\nexport function getMySQLType(context: ScalarTypeContext): string {\n if (context.array) return \"JSON\";\n const type = context.type;\n if (type === \"decimal\")\n return decimalColumnType(\"mysql\", requireDecimalDomain(context));\n if (type === \"datetime\")\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.datetimetz\n : MYSQL_TYPE_DEFAULTS.datetime;\n if (type === \"time\")\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.timetz\n : MYSQL_TYPE_DEFAULTS.time;\n return defaultType(MYSQL_TYPE_DEFAULTS, type);\n}\n","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","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 * The order in which tables are dropped: children before parents.\n *\n * Two callers need it, with different premises. A generated program\n * (`orderTableDrops`, reached through `prepareSchemaProgram`) still has live\n * foreign keys when it drops a table, so an order that violates one fails,\n * and a cycle is broken only where a key's delete action allows it. A\n * namespace reset (`live-reset.ts`) has already dropped every key it can see,\n * so its order is defence and a cycle falls back to inventory order.\n * `childrenBeforeParents` is the one rule they share; what a cycle means stays\n * with each caller.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { DiffOperation, ReferentialAction, SchemaSnapshot } from \"./types\";\n\n/** `from` holds a foreign key that references `to`. */\nexport interface TableReference {\n readonly from: string;\n readonly to: string;\n}\n\n/**\n * Orders `items` so that no item comes after a table it is referenced by.\n *\n * Each round takes every item no remaining item references, in input order, so\n * independent tables keep their given order. What a cycle leaves unordered is\n * returned as `blocked`, in input order; a reference from an item to itself\n * blocks that item.\n */\nexport function childrenBeforeParents<T>(\n items: readonly T[],\n nameOf: (item: T) => string,\n references: readonly TableReference[]\n): { ordered: T[]; blocked: T[] } {\n const referencedBy = new Map<string, string[]>();\n for (const { from, to } of references) {\n const children = referencedBy.get(to);\n if (children) {\n children.push(from);\n } else {\n referencedBy.set(to, [from]);\n }\n }\n\n let remaining = [...items];\n const ordered: T[] = [];\n for (;;) {\n const names = new Set(remaining.map(nameOf));\n const isFree = (item: T) =>\n !referencedBy.get(nameOf(item))?.some((child) => names.has(child));\n const free = remaining.filter(isFree);\n if (free.length === 0) {\n return { ordered, blocked: remaining };\n }\n ordered.push(...free);\n remaining = remaining.filter((item) => !isFree(item));\n }\n}\n\ntype DropTable = Extract<DiffOperation, { type: \"dropTable\" }>;\n\nconst tableOf = (drop: DropTable) => drop.tableName;\n\n/** A key still active when its tables are dropped. */\ninterface ActiveKey extends TableReference {\n readonly columns: readonly string[];\n readonly onDelete: ReferentialAction | undefined;\n}\n\n/**\n * Orders a prepared program's `dropTable` operations from the foreign keys\n * the CURRENT snapshot says exist, children first wherever the keys allow.\n *\n * A key matters while it is still active when its tables are dropped: both of\n * its tables are dropped, and the program does not remove it with an explicit\n * `dropForeignKey`. PostgreSQL and MySQL remove every such key first\n * (`materializeDroppedTableForeignKeys`), so their drops keep the order they\n * were given. A retained table never references a dropped one: the desired\n * schema cannot, so the differ removes that key, and `sortOperations` runs\n * every `dropForeignKey` before every `dropTable`.\n *\n * SQLite holds keys inline and drops with enforcement on. `DROP TABLE` first\n * deletes every row, applying each key's delete action (`refusalOf`), so a\n * cycle is broken at a table whose drop no key can refuse, and refused before\n * any statement exists when no such table remains. The drops replace the band\n * of drops `sortOperations` emitted, where that band begins.\n */\nexport function orderTableDrops(\n operations: DiffOperation[],\n current: SchemaSnapshot\n): DiffOperation[] {\n const drops = operations.filter(\n (operation): operation is DropTable => operation.type === \"dropTable\"\n );\n if (drops.length === 0) {\n return operations;\n }\n\n const dropped = new Set(drops.map(tableOf));\n const removedKeys = new Set<string>();\n for (const operation of operations) {\n if (operation.type === \"dropForeignKey\") {\n removedKeys.add(`${operation.tableName} ${operation.fkName}`);\n }\n }\n const keys: ActiveKey[] = [];\n for (const table of current.tables) {\n for (const fk of table.foreignKeys) {\n const active =\n dropped.has(table.name) &&\n dropped.has(fk.referencedTable) &&\n !removedKeys.has(`${table.name} ${fk.name}`);\n if (active) {\n keys.push({\n from: table.name,\n to: fk.referencedTable,\n columns: fk.columns,\n onDelete: fk.onDelete,\n });\n }\n }\n }\n // Children first: every key between two tables, and a self-reference that\n // refuses even its own table's delete.\n const childFirst = keys.filter(\n (key) => key.from !== key.to || key.onDelete === \"restrict\"\n );\n\n const ordered: DropTable[] = [];\n let remaining = drops;\n for (;;) {\n const step = childrenBeforeParents(remaining, tableOf, childFirst);\n ordered.push(...step.ordered);\n if (step.blocked.length === 0) {\n break;\n }\n const left = new Set(step.blocked.map(tableOf));\n const next = step.blocked.find(\n (drop) => !refusalOf(drop.tableName, keys, left)\n );\n if (!next) {\n throw cyclicDropRefusal(step.blocked.map(tableOf), keys);\n }\n ordered.push(next);\n remaining = step.blocked.filter((drop) => drop !== next);\n }\n\n const first = operations.findIndex(\n (operation) => operation.type === \"dropTable\"\n );\n const rest = operations.filter((operation) => operation.type !== \"dropTable\");\n return [...rest.slice(0, first), ...ordered, ...rest.slice(first)];\n}\n\n/**\n * The key that may refuse dropping `table` while the `existing` tables,\n * `table` among them, remain, if any.\n *\n * The implicit delete removes every row of `table`, and CASCADE extends it to\n * the rows of each remaining table that cascades from a deleted one. A\n * remaining key into a deleted table then decides: CASCADE deleted its rows\n * too and SET NULL clears them; RESTRICT refuses at once; NO ACTION and SET\n * DEFAULT are settled when the statement ends, by when a key held by `table`\n * has lost every row, while one held by another table may still point at\n * nothing. Measured on better-sqlite3 over random populated rows, for every\n * pair of actions on a two-table cycle in both orders and for each action on\n * a self-reference.\n */\nfunction refusalOf(\n table: string,\n keys: readonly ActiveKey[],\n existing: ReadonlySet<string>\n): ActiveKey | undefined {\n const deleted = new Set([table]);\n for (const name of deleted) {\n for (const key of keys) {\n if (\n key.to === name &&\n key.onDelete === \"cascade\" &&\n existing.has(key.from)\n ) {\n deleted.add(key.from);\n }\n }\n }\n return keys.find(\n (key) =>\n deleted.has(key.to) &&\n existing.has(key.from) &&\n key.onDelete !== \"cascade\" &&\n key.onDelete !== \"setNull\" &&\n (key.onDelete === \"restrict\" || key.from !== table)\n );\n}\n\nconst ACTION_SQL: Record<ReferentialAction, string> = {\n cascade: \"CASCADE\",\n setNull: \"SET NULL\",\n restrict: \"RESTRICT\",\n noAction: \"NO ACTION\",\n setDefault: \"SET DEFAULT\",\n};\n\n/**\n * Names every blocked table and a key that refuses its drop, by columns:\n * SQLite introspection cannot read a key's name back.\n */\nfunction cyclicDropRefusal(\n blocked: readonly string[],\n keys: readonly ActiveKey[]\n): MigrationError {\n const left = new Set(blocked);\n const reasons = blocked.flatMap((table) => {\n const key = refusalOf(table, keys, left);\n return key\n ? [\n `dropping \"${table}\" is refused by ${key.from}(${key.columns.join(\", \")}) -> ${key.to} ON DELETE ${ACTION_SQL[key.onDelete ?? \"noAction\"]}`,\n ]\n : [];\n });\n return new MigrationError(\n `Cannot drop tables ${blocked.map((name) => `\"${name}\"`).join(\", \")} in FK-safe order: ${reasons.join(\"; \")}. Remove a relation or set ON DELETE SET NULL first.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { type: \"cyclic-table-drop\" } }\n );\n}\n","/**\n * Views (`s.view`): a read of the schema's tables that the database keeps\n * under a name, which migrations create, replace and drop.\n *\n * A view's identity is its hash, never its text: every catalog rewrites the\n * statement it is given. The database holds that identity in the statement\n * itself: the body is wrapped as `SELECT * FROM (<body>) AS <marker>`, and the\n * marker alias `viborm_view_<hash>` is the last token of what PostgreSQL's\n * `pg_get_viewdef`, MySQL's `VIEW_DEFINITION` and SQLite's `sqlite_master.sql`\n * give back (measured on PostgreSQL 18, PGlite, MySQL 8.4 and SQLite 3.53;\n * each planner flattens the wrapper). It is lowercase because MySQL lowercases\n * an alias where a column names it. A view without the marker is not VibORM's.\n * A materialized view's definition ends with it the same way (measured on\n * PostgreSQL 18 and PGlite).\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n autoViewBodyName,\n autoViewObjectName,\n} from \"../schema/view/auto-names\";\nimport { childrenBeforeParents, type TableReference } from \"./drop-order\";\nimport type {\n AutoViewObject,\n AutoViewStorage,\n DiffOperation,\n IndexDef,\n SchemaSnapshot,\n ViewDef,\n} from \"./types\";\n\nconst VIEW_HASH = /^[0-9a-f]{40}$/;\nconst byName = (a: string, b: string): number => (a < b ? -1 : Number(a > b));\nconst MARKER_PREFIX = \"viborm_view_\";\n\n/**\n * The marker at the end of a view's definition, as every catalog prints it:\n * the closing parenthesis of the wrapped body, an optional `AS` (SQLite keeps\n * it, PostgreSQL and MySQL drop it), the alias bare or quoted, and an optional\n * `;` (PostgreSQL's). Anchored at the end of the text, so a string literal in\n * the body that spells a marker is never read as one. The same text is a\n * PostgreSQL regular expression, which the catalog digest applies in SQL.\n */\nexport const VIEW_MARKER_PATTERN = String.raw`\\)\\s*(?:[Aa][Ss]\\s+)?[\"\\x60]?${MARKER_PREFIX}([0-9a-f]{40})[\"\\x60]?\\s*;?\\s*$`;\nconst VIEW_MARKER = new RegExp(VIEW_MARKER_PATTERN);\n\n/** Whether `value` has a view hash's form: 40 lowercase hex characters. */\nexport function isViewHash(value: unknown): value is string {\n return typeof value === \"string\" && VIEW_HASH.test(value);\n}\n\n/** The alias that carries a view's identity in the database. */\nexport function viewMarker(hash: string): string {\n return `${MARKER_PREFIX}${hash}`;\n}\n\n/**\n * The objects a `refresh: \"auto\"` view needs on a dialect whose triggers are\n * named apart from a function, beside `extra`: its three triggers on its\n * source and the view that holds its body, sorted by kind then name.\n */\nexport function autoViewObjects(\n view: string,\n storage: AutoViewStorage,\n extra: readonly AutoViewObject[] = []\n): AutoViewObject[] {\n const triggers = [\"_d\", \"_i\", \"_u\"].map(\n (suffix): AutoViewObject => ({\n kind: \"trigger\",\n name: autoViewObjectName(view, suffix),\n table: storage.source,\n })\n );\n return sortAutoViewObjects([\n ...extra,\n ...triggers,\n { kind: \"view\", name: autoViewBodyName(view) },\n ]);\n}\n\n/** Objects sorted by kind then name, the order a snapshot and its introspection hold them in. */\nexport function sortAutoViewObjects(\n objects: readonly AutoViewObject[]\n): AutoViewObject[] {\n const order = (object: AutoViewObject) =>\n `${object.kind}\\u0000${object.name}`;\n return [...objects].sort((a, b) => byName(order(a), order(b)));\n}\n\n/** Whether two snapshots hold one view's keepers alike: one missing or moved replaces the view. */\nexport function sameAutoViewObjects(\n current: ViewDef | undefined,\n desired: ViewDef\n): boolean {\n const key = (view: ViewDef | undefined) =>\n JSON.stringify(\n view?.auto?.objects.map(({ kind, name, table }) => [kind, name, table])\n );\n return key(current) === key(desired);\n}\n\n/** A table of the live namespace whose marker says it holds a view kept by triggers. */\nexport interface LiveAutoTable {\n readonly name: string;\n readonly hash: string;\n /** Its indexes beside its primary key, read as a table's. */\n readonly indexes: readonly IndexDef[];\n}\n\n/** A trigger or a function of the live namespace that carries a marker. */\nexport interface LiveAutoKeeper extends AutoViewObject {\n readonly kind: \"function\" | \"trigger\";\n /** The hash its marker names. */\n readonly hash: string;\n /** Disabled in the catalog (PostgreSQL `tgenabled = 'D'`): counts as drift while kept in `objects` so its drop removes it cleanly. */\n readonly disabled?: true;\n}\n\n/** The hash a keeper's text names in its marker, wherever it stands in it. */\nexport function readKeeperMarker(\n text: string | null | undefined\n): string | undefined {\n return text?.match(KEEPER_MARKER)?.[1];\n}\nconst KEEPER_MARKER = new RegExp(`${MARKER_PREFIX}([0-9a-f]{40})`);\n\n/** The name a view kept by triggers gives the view of its body ends so. */\nconst BODY_SUFFIX = \"_viborm_body\";\n\n/** A keeper name whose view prefix is never truncated (view names <= 51 bytes). */\nconst KEEPER_VIEW_NAME = /^(.+)_viborm(?:_[iudk])?$/;\n\n/**\n * Whether a namespace whose marked views are `views` may hold what is left\n * of a view kept by triggers whose table a hand dropped: the view of its\n * body, marked. Its triggers are read then too.\n */\nexport const holdsAutoViewBody = (views: readonly ViewDef[]): boolean =>\n views.some(({ name }) => name.endsWith(BODY_SUFFIX));\n\n/**\n * A sentinel marker hash no declaration can produce: written on a MySQL\n * table before its initial fill completes, and reported for tableless\n * leftovers or views with a disabled trigger so the differ replaces or\n * drops them cleanly.\n */\nexport const AUTO_VIEW_PENDING_HASH = \"0\".repeat(40);\n\n/**\n * The views kept by triggers of a live namespace, each a marked table with\n * the objects that carry its marker under the names its view gives them\n * (two views of one declaration share a hash, never a name), its body's\n * view taken out of `views`. One missing is missing from its objects, which\n * the declared view then does not match. What is left of one whose table a\n * hand dropped (a marked view of its body with its triggers, or orphan\n * marked triggers/functions without table or body) is read as a view with\n * no table, of no declaration's hash: the next program drops its objects,\n * and leaves alone whatever now holds its name.\n */\nexport function readAutoViews(\n tables: readonly LiveAutoTable[],\n keepers: readonly LiveAutoKeeper[],\n views: ViewDef[]\n): ViewDef[] {\n const kept = new Set(tables.map(({ name }) => name));\n const seen = new Set(kept);\n // A view of that name is what is left only beside a trigger of its marker\n // and of its view's name: an ordinary view may end so too.\n const left: LiveAutoTable[] = [];\n for (const view of views) {\n const name = view.name.slice(0, -BODY_SUFFIX.length);\n const trigger = (keeper: LiveAutoKeeper) =>\n keeper.kind === \"trigger\" &&\n keeper.hash === view.hash &&\n [\"_i\", \"_u\", \"_d\"].some(\n (suffix) => keeper.name === autoViewObjectName(name, suffix)\n );\n if (\n view.name.endsWith(BODY_SUFFIX) &&\n !seen.has(name) &&\n autoViewBodyName(name) === view.name &&\n keepers.some(trigger)\n ) {\n seen.add(name);\n left.push({ name, hash: view.hash, indexes: [] });\n }\n }\n // Orphan triggers or functions left after both table and body view were dropped.\n for (const keeper of keepers) {\n const name = KEEPER_VIEW_NAME.exec(keeper.name)?.[1];\n if (name === undefined || seen.has(name)) continue;\n seen.add(name);\n left.push({ name, hash: keeper.hash, indexes: [] });\n }\n return [...tables, ...left].map(({ name, hash, indexes }) => {\n const pending = hash === AUTO_VIEW_PENDING_HASH;\n const objects: AutoViewObject[] = [];\n const names = new Set(\n [\"\", \"_i\", \"_u\", \"_d\", \"_k\"].map((suffix) =>\n autoViewObjectName(name, suffix)\n )\n );\n let hasDisabled = false;\n for (const keeper of keepers)\n if (\n (pending || keeper.hash === hash) &&\n (names.has(keeper.name) ||\n (keeper.table !== undefined &&\n keeper.name === autoViewObjectName(name, `_on_${keeper.table}`)))\n ) {\n if (keeper.disabled) hasDisabled = true;\n objects.push({\n kind: keeper.kind,\n name: keeper.name,\n ...(keeper.table === undefined ? {} : { table: keeper.table }),\n });\n }\n const at = views.findIndex(\n (view) =>\n view.name === autoViewBodyName(name) && (pending || view.hash === hash)\n );\n const [body] = at < 0 ? [] : views.splice(at, 1);\n if (body) objects.push({ kind: \"view\", name: body.name });\n const tableless = !kept.has(name);\n return {\n name,\n hash: tableless || hasDisabled ? AUTO_VIEW_PENDING_HASH : hash,\n dependsOn: body?.dependsOn ?? [],\n ...(indexes.length > 0 ? { indexes: [...indexes] } : {}),\n auto: {\n objects: sortAutoViewObjects(objects),\n ...(tableless ? { tableless: true as const } : {}),\n },\n };\n });\n}\n\n/** The drop of `view`, as the snapshot that holds it says it is stored. */\nexport function dropViewOperation(view: ViewDef): DropViewOperation {\n return {\n type: \"dropView\",\n viewName: view.name,\n ...(view.materialized ? { materialized: true } : {}),\n ...(view.auto ? { auto: view.auto } : {}),\n };\n}\n\n/**\n * The tables whose change a view kept by triggers does not survive, beside\n * what its body reads: each table a trigger of it fires on (its source, and\n * on MySQL each parent of a cascade) and each child such a trigger changes.\n * Its triggers name their columns, and none of them follows a change: a\n * plpgsql body is checked when it runs, MySQL keeps a trigger's text as\n * written, and SQLite drops a table's triggers when it rebuilds it.\n */\nfunction watchedTables(view: ViewDef | undefined): string[] {\n const auto = view?.auto;\n if (auto === undefined) return [];\n return [\n ...auto.objects.flatMap(({ table }) => (table ? [table] : [])),\n ...(auto.storage?.cascades ?? []).flatMap(({ children }) =>\n children.map(({ table }) => table)\n ),\n ];\n}\n\n/** A view's body, to create it with: a view read from the database has none. */\nexport function declaredViewSql(view: ViewDef): string {\n if (view.sql === undefined)\n throw new MigrationError(\n `View \"${view.name}\" was read from DB and is not declared in schema.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { relation: view.name, feature: \"view\" } }\n );\n return view.sql;\n}\n\n/** How to create a view kept by triggers: a view read from the database has none. */\nexport function declaredAutoViewStorage(view: ViewDef): AutoViewStorage {\n const storage = view.auto?.storage;\n if (storage === undefined) declaredViewSql({ ...view, sql: undefined });\n return storage!;\n}\n\n/**\n * What follows `CREATE VIEW <name> AS`: the body wrapped so that the marker\n * is its last token. `quote` is the dialect's identifier quoting.\n */\nexport function wrappedViewBody(\n view: ViewDef,\n quote: (name: string) => string,\n columns = \"*\"\n): string {\n return `SELECT ${columns} FROM (${declaredViewSql(view)}) AS ${quote(viewMarker(view.hash))}`;\n}\n\n/**\n * The hash a view definition's marker names, or undefined when the definition\n * does not end with one (a view VibORM did not create).\n */\nexport function readViewMarker(\n definition: string | null | undefined\n): string | undefined {\n if (definition === null || definition === undefined) return;\n return VIEW_MARKER.exec(definition)?.[1];\n}\n\n/**\n * The hash a view table's comment names, where SurrealDB keeps the marker\n * (`DEFINE TABLE … AS SELECT … COMMENT \"<marker>\"`, which `INFO FOR DB`\n * reports apart from the body): the marker alone, or undefined.\n */\nexport function readViewComment(\n comment: string | null | undefined\n): string | undefined {\n const hash = comment?.startsWith(MARKER_PREFIX)\n ? comment.slice(MARKER_PREFIX.length)\n : undefined;\n return isViewHash(hash) ? hash : undefined;\n}\n\n/** A program operation on a view. */\ntype ViewOperation = Extract<\n DiffOperation,\n { type: \"createView\" } | { type: \"dropView\" }\n>;\ntype DropViewOperation = Extract<DiffOperation, { type: \"dropView\" }>;\n\nfunction isViewOperation(operation: DiffOperation): operation is ViewOperation {\n return operation.type === \"createView\" || operation.type === \"dropView\";\n}\n\n/**\n * The tables an operation changes in a way a view reading them does not\n * survive. Everywhere: a table renamed, dropped or created again, a column\n * dropped, renamed or given another type (PostgreSQL refuses a type change\n * and a drop under a view, and its enum recreation retypes columns; MySQL's\n * view breaks on a rename; SQLite rewrites a view's text on a rename), and a\n * primary key added or dropped: no database refuses that under a view, but a\n * body orders its rows, and the rows of a relation it reads, by the key\n * (which row a `take` or a `distinct` keeps), so the view would stay as the\n * old key wrote it. Where the dialect `rebuilds` a table to change it\n * (SQLite: a column, a unique or a foreign key), every other change to the\n * table too, since it refuses to rebuild a table a view reads. Where a\n * foreign key's column holds `links` (SurrealDB stores a record link there,\n * and the plain value without the key), a foreign key added or dropped too:\n * a view's filter on the column was written for the other form, and would\n * match no row (measured). There a column changed in any way replaces the\n * view as well: its body is not SQL's, where a filter means the same under a\n * nullable column, but a filter lowered for the column as it was (a column\n * that becomes nullable needs a guard its filter did not have, without\n * which every write of `NULL` to the table fails; measured), and the view's\n * hash holds neither the body nor a column the query only filters by. And there a table's rename changes\n * every table holding a foreign key to it: the rename rewrites each link\n * held as a record of the new table, and a view's filter on that column,\n * written with a record of the old one, would match no row (measured). An index's creation or drop leaves\n * every view as it was, on every dialect. A materialized view is refused and\n * survives the same changes as an ordinary one (measured on PostgreSQL 18),\n * and keeps the rows it stored through the ones it survives.\n */\nfunction changedTables(\n operations: readonly DiffOperation[],\n current: SchemaSnapshot,\n rebuilds: boolean,\n links: boolean\n): Set<string> {\n const names = new Set<string>();\n for (const operation of operations) {\n switch (operation.type) {\n case \"renameTable\":\n names.add(operation.from).add(operation.to);\n if (links)\n for (const table of current.tables)\n if (\n table.foreignKeys.some(\n (key) => key.referencedTable === operation.from\n )\n )\n names.add(table.name);\n break;\n case \"createTable\":\n names.add(operation.table.name);\n break;\n case \"alterEnum\":\n case \"dropEnum\":\n for (const column of operation.dependentColumns ?? [])\n names.add(column.tableName);\n break;\n case \"dropTable\":\n case \"dropColumn\":\n case \"renameColumn\":\n case \"addPrimaryKey\":\n case \"dropPrimaryKey\":\n names.add(operation.tableName);\n break;\n case \"alterColumn\":\n if (rebuilds || links || operation.from.type !== operation.to.type)\n names.add(operation.tableName);\n break;\n case \"addForeignKey\":\n case \"dropForeignKey\":\n if (rebuilds || links) names.add(operation.tableName);\n break;\n case \"createIndex\":\n case \"dropIndex\":\n case \"createEnum\":\n case \"createView\":\n case \"dropView\":\n break;\n default:\n if (rebuilds) names.add(operation.tableName);\n }\n }\n return names;\n}\n\n/**\n * The views of `views` named in `names`, each before every one it reads when\n * `dependentsFirst` (the order their drops need), after them otherwise (the\n * order their creations need). A cycle, which no database admits, keeps name\n * order.\n */\nexport function orderViews(\n names: ReadonlySet<string>,\n views: readonly ViewDef[],\n dependentsFirst: boolean\n): string[] {\n const reads = new Map(views.map((view) => [view.name, view.dependsOn]));\n const references: TableReference[] = [];\n for (const name of names)\n for (const read of reads.get(name) ?? [])\n if (read !== name && names.has(read))\n references.push({ from: name, to: read });\n const { ordered, blocked } = childrenBeforeParents(\n [...names].sort(byName),\n (name) => name,\n references\n );\n const dependents = [...ordered, ...blocked];\n return dependentsFirst ? dependents : dependents.reverse();\n}\n\n/**\n * A prepared program with its views where they must run. The differ plans a\n * view's drop and creation when its hash changes or it is declared on one\n * side only; this adds the one rule the program decides: a view is dropped\n * and created again when a table it reads is changed by the program in a\n * way it does not survive on this dialect (see `changedTables`; `rebuilds`\n * says the dialect rebuilds tables, `links` that a foreign key's column holds\n * record links), or a view it reads is dropped,\n * transitively. Every drop\n * runs first, dependents before what they read, and every creation last,\n * after what it reads: no table or enum operation runs under a view. A\n * replaced materialized view is created with its indexes, so an index\n * operation the differ planned on it goes.\n */\nexport function withViewReplacements(\n operations: readonly DiffOperation[],\n current: SchemaSnapshot,\n desired: SchemaSnapshot,\n rebuilds: boolean,\n links = false\n): DiffOperation[] {\n const dropped = new Map<string, DropViewOperation>();\n const created = new Map<string, ViewDef>();\n for (const operation of operations) {\n if (operation.type === \"dropView\")\n dropped.set(operation.viewName, operation);\n if (operation.type === \"createView\")\n created.set(operation.view.name, operation.view);\n }\n const declared = new Map(\n (desired.views ?? []).map((view) => [view.name, view])\n );\n const tableOperations = operations.filter(\n (operation) => !isViewOperation(operation)\n );\n const changed = changedTables(tableOperations, current, rebuilds, links);\n // What a view kept by triggers does not survive: any change but an index's.\n const rebuilt = changedTables(tableOperations, current, true, links);\n const live = current.views ?? [];\n for (let grew = true; grew; ) {\n grew = false;\n for (const view of live) {\n if (dropped.has(view.name)) continue;\n const kept = declared.get(view.name);\n const reads = [...view.dependsOn, ...(kept?.dependsOn ?? [])];\n const watched = [...watchedTables(view), ...watchedTables(kept)];\n if (\n !(\n reads.some((name) => changed.has(name) || dropped.has(name)) ||\n watched.some((name) => rebuilt.has(name))\n )\n )\n continue;\n dropped.set(view.name, dropViewOperation(view));\n if (kept) created.set(kept.name, kept);\n grew = true;\n }\n }\n const rest = operations.filter(\n (operation) =>\n !(\n isViewOperation(operation) ||\n ((operation.type === \"createIndex\" || operation.type === \"dropIndex\") &&\n created.has(operation.tableName) &&\n dropped.has(operation.tableName))\n )\n );\n if (dropped.size === 0 && created.size === 0) return rest;\n return [\n ...orderViews(new Set(dropped.keys()), live, true).map(\n (name) => dropped.get(name)!\n ),\n ...rest,\n ...orderViews(new Set(created.keys()), [...created.values()], false).map(\n (name): DiffOperation => ({\n type: \"createView\",\n view: created.get(name)!,\n })\n ),\n ];\n}\n\n/**\n * The relations a view takes in the namespace: its name, and a view kept by\n * triggers the view of its body too, which a relation VibORM did not create\n * must not hold (its creation would take it over).\n */\nexport function viewRelationNames(view: ViewDef): string[] {\n return view.auto ? [view.name, autoViewBodyName(view.name)] : [view.name];\n}\n\n/** One relation of the live namespace, as a dialect's preflight reads it. */\nexport interface LiveRelation {\n readonly name: string;\n readonly kind: \"table\" | \"view\" | \"materialized view\";\n /** A view's definition as its catalog prints it, materialized or not. */\n readonly definition?: string | null | undefined;\n /**\n * A view table's comment, where SurrealDB keeps the marker, and a table's\n * where it holds a view kept by triggers (SQLite's marker opening its\n * column list, as the comment it is).\n */\n readonly comment?: string | undefined;\n}\n\n/**\n * Refuses, before any effect, a name the snapshots declare that the database\n * holds as something VibORM cannot take over: a declared table that is a\n * view, materialized or not, without VibORM's marker, and a declared view\n * that is a table no snapshot declares, or a view without the marker. A\n * marked view of either kind is VibORM's: the program drops or keeps it. A\n * table a snapshot declares is the history's: it drops it before the view.\n */\nexport function refuseRelationCollision(\n database: string,\n snapshots: readonly SchemaSnapshot[],\n relations: readonly LiveRelation[]\n): void {\n const tables = new Set(\n snapshots.flatMap((snapshot) => snapshot.tables.map(({ name }) => name))\n );\n const views = new Set(\n snapshots.flatMap((snapshot) =>\n (snapshot.views ?? []).flatMap(viewRelationNames)\n )\n );\n for (const relation of relations) {\n const foreignView =\n relation.kind !== \"table\" &&\n (readViewMarker(relation.definition) ??\n readViewComment(relation.comment)) === undefined;\n if (tables.has(relation.name) && foreignView)\n throw new MigrationError(\n `${database} \"${relation.name}\" unmanaged ${relation.kind} conflicts with table.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: relation.name, feature: \"view\" } }\n );\n const foreignTable =\n relation.kind === \"table\" &&\n readViewComment(relation.comment) === undefined;\n if (\n views.has(relation.name) &&\n !tables.has(relation.name) &&\n (foreignTable || foreignView)\n )\n throw new MigrationError(\n `${database} \"${relation.name}\" unmanaged ${relation.kind === \"table\" ? \"table\" : `${relation.kind} (${relation.definition ? \"not VibORM\" : \"unreadable; grant SHOW VIEW\"})`} conflicts with view.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { relation: relation.name, feature: \"view\" } }\n );\n }\n}\n","/**\n * Shared migration helpers that do not own a V1 command.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationDriver } from \"./drivers\";\nimport { orderTableDrops } from \"./drop-order\";\nimport { sha256Hex, utf8Bytes } from \"./identity\";\nimport type { Dialect, DiffOperation, SchemaSnapshot } from \"./types\";\nimport { withViewReplacements } from \"./view\";\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// DIALECT UTILITIES\n// =============================================================================\n\n/**\n * Validates and normalizes the database dialect for migrations.\n * Throws if the dialect is not supported.\n */\nexport function normalizeDialect(dialect: string): Dialect {\n if (dialect === \"postgresql\" || dialect === \"postgres\") {\n return \"postgresql\";\n }\n if (\n dialect === \"sqlite\" ||\n dialect === \"mysql\" ||\n dialect === \"surrealql\" ||\n dialect === \"snowflake\"\n ) {\n return dialect;\n }\n throw new MigrationError(\n `Unsupported dialect for migrations: \"${dialect}\". ` +\n \"Supported dialects: postgresql, sqlite, mysql.\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH,\n { meta: { dialect } }\n );\n}\n\n// QUERY EXECUTOR\n// =============================================================================\n\n/**\n * Type for executing SQL queries and returning rows.\n */\nexport type QueryExecutor = (\n sql: string,\n params?: unknown[]\n) => Promise<unknown[]>;\n\n/**\n * Creates a query executor from a driver.\n * Extracts rows from the QueryResult.\n */\nexport function createQueryExecutor(driver: AnyDriver): QueryExecutor {\n return async (sql: string, params?: unknown[]) => {\n const result = await driver._executeRaw<Record<string, unknown>>(\n sql,\n params\n );\n return result.rows;\n };\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","/** Runtime-neutral canonical Base64 for persisted migration parameters. */\nconst CANONICAL_SHAPE =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nexport function encodeBase64(bytes: Uint8Array): string {\n // Indexed reads preserve the byte view and ignore an overridden iterator;\n // spreading a large array into fromCharCode can overflow the call stack.\n let binary = \"\";\n // biome-ignore lint/style/useForOf: preserve indexed reads if the caller overrides iteration.\n for (let index = 0; index < bytes.length; index++)\n binary += String.fromCharCode(bytes[index]!);\n return btoa(binary);\n}\nexport function decodeCanonicalBase64(text: string): Uint8Array | undefined {\n if (!CANONICAL_SHAPE.test(text)) return;\n const binary = atob(text);\n const decoded = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++)\n decoded[index] = binary.charCodeAt(index);\n // atob also accepts nonzero padding bits; persisted parameters do not.\n return encodeBase64(decoded) === text ? decoded : undefined;\n}\n","/**\n * Dispatch identity and hostile parameter admission.\n * Reset-plan and state parsers share this owner; they do not import each other.\n */\n\nimport { canonicalizeDecimal } from \"../validation/primitives/decimal-codec\";\nimport { isNumber, isRecord, isString } from \"../validation/value-guards\";\nimport { decodeCanonicalBase64 } from \"./base64\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport {\n corrupt,\n exactKeys,\n ks,\n parseArray,\n parseBoolean,\n parseFiniteInteger,\n parseString,\n refuse,\n} from \"./v1-parse-shared\";\nimport type { MigrationDispatchV1, MigrationParameterV1 } from \"./v1-types\";\n\nconst DISPATCH_KEYS = ks(\"dispatchId length offset parameters sqlHash\");\nconst KIND_ONLY = [\"kind\"];\nconst KIND_VALUE = ks(\"kind value\");\n\nconst CANONICAL_BIGINT = /^(?:0|-?[1-9]\\d*)$/;\n\nexport function encodeDispatchIdentity(\n sqlHash: Sha256,\n offset: number,\n length: number,\n parameters: readonly MigrationParameterV1[]\n): Sha256 {\n return domainHash(\n HASH_DOMAIN.dispatch,\n canonicalizeJson({ sqlHash, offset, length, parameters })\n );\n}\n\nexport function parseDispatch(\n value: unknown,\n label: string\n): MigrationDispatchV1 {\n const record = exactKeys(value, DISPATCH_KEYS, label);\n const offset = parseFiniteInteger(record.offset, `${label}.offset`);\n const length = parseFiniteInteger(record.length, `${label}.length`);\n if (offset < 0 || length < 0) refuse(`${label} range must be non-negative`);\n const parameters = parseArray(\n record.parameters,\n `${label}.parameters`,\n parseParameter\n );\n const sqlHash = parseSha256(record.sqlHash, `${label}.sqlHash`);\n const dispatchId = parseSha256(record.dispatchId, `${label}.dispatchId`);\n if (\n dispatchId !== encodeDispatchIdentity(sqlHash, offset, length, parameters)\n )\n corrupt(`${label}.dispatchId mismatch`);\n return { dispatchId, sqlHash, offset, length, parameters };\n}\n\nconst VALUE_PARAM_KINDS = new Set(\n \"boolean string number bigint bytes date-time decimal json\".split(\" \")\n);\n\nfunction parseParameter(value: unknown, label: string): MigrationParameterV1 {\n if (!(isRecord(value) && isString(value.kind)))\n refuse(`${label} invalid parameter`);\n const { kind } = value;\n if (kind === \"null\" || kind === \"target-namespace\") {\n exactKeys(value, KIND_ONLY, label);\n return { kind };\n }\n if (!VALUE_PARAM_KINDS.has(kind)) refuse(`${label}.kind invalid`);\n const v = exactKeys(value, KIND_VALUE, label).value;\n switch (kind) {\n case \"boolean\":\n return { kind, value: parseBoolean(v, `${label}.value`) };\n case \"string\":\n return { kind, value: parseString(v, `${label}.value`) };\n case \"number\":\n if (!(isNumber(v) && Number.isFinite(v)))\n refuse(`${label}.value must be finite number`);\n return { kind, value: v };\n case \"bigint\":\n case \"bytes\":\n case \"date-time\":\n case \"decimal\":\n if (!(isString(v) && isCanonicalParameterText(kind, v)))\n refuse(`${label}.value invalid ${kind}`);\n return { kind, value: v };\n case \"json\":\n return { kind, value: v };\n default:\n refuse(`${label}.kind invalid`);\n }\n}\n\nfunction isCanonicalParameterText(\n kind: \"bigint\" | \"bytes\" | \"date-time\" | \"decimal\",\n value: string\n): boolean {\n if (kind === \"bigint\") return CANONICAL_BIGINT.test(value);\n if (kind === \"bytes\") return decodeCanonicalBase64(value) !== undefined;\n if (kind === \"decimal\") return canonicalizeDecimal(value) === value;\n try {\n return new Date(value).toISOString() === value;\n } catch {\n return false;\n }\n}\n","/**\n * Hostile parsers and hash owner for Migration V1 marker and ledger rows.\n *\n * Path identity lives next to the marker it authenticates. Reset-plan\n * admission lives next to the ledger event that carries it.\n */\n\nimport { isRecord, isString } from \"../validation/value-guards\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport { parseDispatch } from \"./v1-parse-dispatch\";\nimport {\n corrupt,\n exactKeys,\n ks,\n nullableField,\n parseArray,\n parseBoolean,\n parseFiniteInteger,\n parseFormat,\n parseItems,\n parseMember,\n parseRequiredString,\n refuse,\n reqStr,\n} from \"./v1-parse-shared\";\nimport type {\n LedgerEffectStateV1,\n LedgerEventKindV1,\n LedgerEventV1,\n MarkerIndexPredicateV1,\n MarkerPathEdgeV1,\n MigrationMarkerV1,\n ResetPlanV1,\n} from \"./v1-types\";\n\nexport function encodePathHash(path: readonly MarkerPathEdgeV1[]): Sha256 {\n return domainHash(HASH_DOMAIN.path, canonicalizeJson(path));\n}\n\nexport function eventIdFor(event: Omit<LedgerEventV1, \"eventId\">): Sha256 {\n return domainHash(HASH_DOMAIN.event, canonicalizeJson(event));\n}\n\nconst sha = (record: Record<string, unknown>, key: string, label: string) =>\n parseSha256(record[key], `${label}.${key}`);\nconst nullSha = (record: Record<string, unknown>, key: string, label: string) =>\n nullableField(record[key], parseSha256, `${label}.${key}`);\nconst nullStr = (record: Record<string, unknown>, key: string, label: string) =>\n nullableField(record[key], parseRequiredString, `${label}.${key}`);\n\nconst MARKER_KEYS = ks(\n \"estateHash format path pathHash revision snapshotHash stateId updatedAt\"\n);\nconst PATH_EDGE_KEYS = ks(\"baselineBoundary stateId transitionHash\");\n\nexport function parseMarkerRow(value: unknown): MigrationMarkerV1 {\n const record = exactKeys(value, MARKER_KEYS, \"migration marker\");\n const path = parseArray(record.path, \"marker.path\", (edge, edgeLabel) => {\n const item = exactKeys(edge, PATH_EDGE_KEYS, edgeLabel);\n return {\n stateId: sha(item, \"stateId\", edgeLabel),\n transitionHash: sha(item, \"transitionHash\", edgeLabel),\n baselineBoundary: parseBoolean(\n item.baselineBoundary,\n `${edgeLabel}.baselineBoundary`\n ),\n };\n });\n const pathHash = sha(record, \"pathHash\", \"marker\");\n if (pathHash !== encodePathHash(path)) corrupt(\"marker.pathHash mismatch\");\n if (!isString(record.updatedAt) || record.updatedAt.length === 0)\n refuse(\"marker.updatedAt invalid\");\n return {\n format: parseFormat(record.format, \"marker\"),\n estateHash: sha(record, \"estateHash\", \"marker\"),\n stateId: nullSha(record, \"stateId\", \"marker\"),\n snapshotHash: sha(record, \"snapshotHash\", \"marker\"),\n path,\n pathHash,\n revision: parseFiniteInteger(record.revision, \"marker.revision\"),\n updatedAt: record.updatedAt,\n };\n}\n\nconst PREDICATE_KEYS = ks(\"deparsed index table\");\n\n/**\n * The marker row: the marker and, beside it, the partial-index predicates an\n * apply on PostgreSQL recorded as the server deparsed them (`casMarker`).\n */\nexport function parseMarkerPayload(value: unknown): {\n readonly marker: MigrationMarkerV1;\n readonly predicates: readonly MarkerIndexPredicateV1[];\n} {\n if (!(isRecord(value) && \"predicates\" in value)) {\n return { marker: parseMarkerRow(value), predicates: [] };\n }\n const { predicates, ...marker } = value;\n return {\n marker: parseMarkerRow(marker),\n predicates: parseArray(predicates, \"marker predicates\", (item, label) => {\n const record = exactKeys(item, PREDICATE_KEYS, label);\n return {\n table: reqStr(record, \"table\", label),\n index: reqStr(record, \"index\", label),\n deparsed: reqStr(record, \"deparsed\", label),\n };\n }),\n };\n}\n\nconst LEDGER_KINDS: readonly LedgerEventKindV1[] = [\n \"started\",\n \"step-confirmed\",\n \"applied\",\n \"failed\",\n \"rolled-back\",\n \"baselined\",\n \"reanchored\",\n \"resolved\",\n \"reset-started\",\n \"reset-step-confirmed\",\n \"reset-applied\",\n];\nconst EFFECT_STATES: readonly LedgerEffectStateV1[] = [\n \"none\",\n \"committed\",\n \"partial\",\n \"may-have-committed\",\n];\nconst DIRECTIONS: readonly LedgerEventV1[\"direction\"][] = [\n \"forward\",\n \"rollback\",\n \"reset\",\n \"baseline\",\n \"resolve\",\n];\nconst LEDGER_KEYS = ks(\n \"attemptId direction dispatchId effectState estateHash eventId failure finishedAt format fromState kind operationId snapshotHash sqlHash startedAt toState toolVersion transitionHash\"\n);\nconst RESET_LEDGER_KEYS = [...LEDGER_KEYS, \"resetPlan\"];\nconst RESET_PLAN_KEYS = ks(\n \"clearDispatches estateHash referencedStates replayPath resetPlanHash sourceFingerprint sourceRevision targetIdentity\"\n);\n\nexport function parseLedgerEvent(value: unknown): LedgerEventV1 {\n if (!isRecord(value)) refuse(\"ledger event must be an object\");\n const kind = parseMember(\n value.kind,\n LEDGER_KINDS,\n \"ledger event.kind invalid\"\n );\n const record = exactKeys(\n value,\n kind === \"reset-started\" ? RESET_LEDGER_KEYS : LEDGER_KEYS,\n \"ledger event\"\n );\n const event = {\n format: parseFormat(record.format, \"ledger event\"),\n eventId: sha(record, \"eventId\", \"ledger\"),\n attemptId: sha(record, \"attemptId\", \"ledger\"),\n kind,\n estateHash: sha(record, \"estateHash\", \"ledger\"),\n snapshotHash: sha(record, \"snapshotHash\", \"ledger\"),\n sqlHash: nullSha(record, \"sqlHash\", \"ledger\"),\n fromState: nullSha(record, \"fromState\", \"ledger\"),\n toState: nullSha(record, \"toState\", \"ledger\"),\n transitionHash: nullSha(record, \"transitionHash\", \"ledger\"),\n direction: parseMember(\n record.direction,\n DIRECTIONS,\n \"ledger event.direction invalid\"\n ),\n operationId: nullStr(record, \"operationId\", \"ledger\"),\n dispatchId: nullSha(record, \"dispatchId\", \"ledger\"),\n effectState: parseMember(\n record.effectState,\n EFFECT_STATES,\n \"ledger event.effectState invalid\"\n ),\n startedAt: reqStr(record, \"startedAt\", \"ledger\"),\n finishedAt: nullStr(record, \"finishedAt\", \"ledger\"),\n toolVersion: reqStr(record, \"toolVersion\", \"ledger\"),\n failure: nullStr(record, \"failure\", \"ledger\"),\n };\n const admitted =\n kind === \"reset-started\"\n ? { ...event, resetPlan: parseResetPlan(record.resetPlan) }\n : event;\n const { eventId, ...body } = admitted;\n if (eventId !== eventIdFor(body)) corrupt(\"ledger eventId mismatch\");\n return admitted;\n}\n\nfunction parseResetPlan(value: unknown): ResetPlanV1 {\n const record = exactKeys(value, RESET_PLAN_KEYS, \"reset plan\");\n if (\n !(\n Array.isArray(record.replayPath) &&\n Array.isArray(record.clearDispatches) &&\n Array.isArray(record.referencedStates)\n )\n )\n refuse(\"reset plan arrays malformed\");\n const plan: ResetPlanV1 = {\n estateHash: sha(record, \"estateHash\", \"resetPlan\"),\n targetIdentity: reqStr(record, \"targetIdentity\", \"resetPlan\"),\n sourceRevision: parseFiniteInteger(\n record.sourceRevision,\n \"resetPlan.sourceRevision\"\n ),\n sourceFingerprint: sha(record, \"sourceFingerprint\", \"resetPlan\"),\n replayPath: parseItems(\n record.replayPath,\n \"resetPlan.replayPath\",\n parseSha256\n ),\n clearDispatches: parseItems(\n record.clearDispatches,\n \"resetPlan.clearDispatches\",\n parseDispatch\n ),\n referencedStates: parseItems(\n record.referencedStates,\n \"resetPlan.referencedStates\",\n parseSha256\n ),\n resetPlanHash: sha(record, \"resetPlanHash\", \"resetPlan\"),\n };\n const { resetPlanHash, ...body } = plan;\n if (\n resetPlanHash !== domainHash(HASH_DOMAIN.resetPlan, canonicalizeJson(body))\n )\n corrupt(\"resetPlanHash mismatch\");\n return plan;\n}\n","/**\n * Raw indexes: an index written in a database's own language\n * (`Model.rawIndex`), for what the index declaration cannot say.\n *\n * A template is held as written. `{name}` and `{table}` are the index and its\n * table; any other `{identifier}` is a scalar field of the model, and the\n * fields a template names, in the order they first appear, are the index's\n * `columns`: rendering puts the i-th of them where the i-th field stands, so a\n * snapshot needs no field-to-column map. Its identity is `rawIndexHash` of the\n * text; the database holds the rendered text and a marker beside it (the\n * columns, the name, the hash) that introspection reads back, since no catalog\n * can say which text a statement was rendered from.\n */\n\nimport type { Dialect } from \"../drivers/types\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { RawIndexTemplates } from \"../schema/model\";\nimport { isRecord, isString } from \"../validation/value-guards\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport {\n domainHash,\n HASH_DOMAIN,\n isSha256,\n type Sha256,\n utf8Bytes,\n} from \"./identity\";\nimport type { IndexDef } from \"./types\";\n\n/**\n * The template a dialect reads, by its key in `.rawIndex()`. Snowflake has\n * none: VibORM writes no DDL there. Every other dialect is stated, checked by\n * the type alone: one added to `Dialect` does not compile until it is here.\n */\nexport const RAW_INDEX_TEMPLATE_KEY: Readonly<\n Partial<Record<Dialect, keyof RawIndexTemplates>>\n> = {\n postgresql: \"pg\",\n mysql: \"mysql\",\n sqlite: \"sqlite\",\n surrealql: \"surrealdb\",\n} satisfies Record<Exclude<Dialect, \"snowflake\">, keyof RawIndexTemplates>;\n\n/** What a SQL database's catalog comment starts with when VibORM wrote it. */\nexport const RAW_INDEX_MARKER_PREFIX = \"viborm:raw:\";\n\nconst PLACEHOLDER = /\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g;\nconst RESERVED_PLACEHOLDERS: ReadonlySet<string> = new Set([\"name\", \"table\"]);\nconst SQL_HEADER =\n /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+\\{name\\}\\s+ON\\s+\\{table\\}/i;\nconst SURREAL_HEADER =\n /^\\s*DEFINE\\s+INDEX\\s+\\{name\\}\\s+ON\\s+(?:TABLE\\s+)?\\{table\\}/i;\n/** A word read after the text: it ends the only statement unless a `;` or an open comment came first. */\nconst END = \"VIBORM_END\";\n\n/** The fields a template names, each once, in the order they first appear. */\nexport function rawIndexFields(template: string): string[] {\n const fields: string[] = [];\n for (const [, name] of template.matchAll(PLACEHOLDER)) {\n if (!(RESERVED_PLACEHOLDERS.has(name!) || fields.includes(name!)))\n fields.push(name!);\n }\n return fields;\n}\n\nexport function rawIndexHash(template: string): Sha256 {\n return domainHash(HASH_DOMAIN.rawIndex, utf8Bytes(template));\n}\n\n/**\n * One model's raw index as the serializer records it for `dialect`: its header\n * read, each field it names resolved to its column. `columnOf` answers a\n * scalar field's column, or undefined for anything else.\n */\nexport function declaredRawIndex(\n model: string,\n name: string,\n template: string,\n dialect: Dialect,\n columnOf: (field: string) => string | undefined\n): IndexDef {\n if (name === \"\")\n throw new MigrationError(\n `Raw index of \"${model}\" needs a name.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model } }\n );\n const header = dialect === \"surrealql\" ? SURREAL_HEADER : SQL_HEADER;\n if (!header.test(template))\n throw new MigrationError(\n `Raw index \"${model}.${name}\" must start with ${dialect === \"surrealql\" ? \"DEFINE INDEX {name} ON [TABLE] {table}\" : \"CREATE [UNIQUE] INDEX {name} ON {table}\"}.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model, indexName: name } }\n );\n const fields = rawIndexFields(template);\n if (fields.length === 0)\n throw new MigrationError(\n `Raw index \"${model}.${name}\" names no field ({field}).`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model, indexName: name } }\n );\n const columns = fields.map((field) => {\n const column = columnOf(field);\n if (column === undefined)\n throw new MigrationError(\n `Raw index \"${model}.${name}\" names {${field}}, which is not a scalar field of \"${model}\".`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model, indexName: name, field } }\n );\n return column;\n });\n return {\n name,\n columns,\n unique: false,\n raw: { hash: rawIndexHash(template), template },\n };\n}\n\n/** How a driver spells the parts a template leaves to it. */\nexport interface RawIndexSpelling {\n readonly name: string;\n readonly table: string;\n readonly column: (column: string) => string;\n}\n\n/** The statement a raw index's template renders to, its marker not included. */\nexport function renderRawIndex(\n index: IndexDef,\n spelling: RawIndexSpelling\n): string {\n const template = index.raw?.template;\n if (template === undefined)\n throw new MigrationError(\n `Raw index \"${index.name}\" undeclared in schema; declare via .rawIndex() or drop first.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { indexName: index.name } }\n );\n const fields = rawIndexFields(template);\n return template.replace(PLACEHOLDER, (_, placeholder: string) => {\n if (placeholder === \"name\") return spelling.name;\n if (placeholder === \"table\") return spelling.table;\n return spelling.column(index.columns[fields.indexOf(placeholder)]!);\n });\n}\n\nexport function refuseRawIndexStatement(\n index: IndexDef,\n rendered: string,\n read: (text: string) => readonly (readonly string[])[],\n refused: readonly string[]\n): void {\n const statements = read(`${rendered}\\n${END}`);\n if (statements.length !== 1 || statements[0]!.at(-1)?.toUpperCase() !== END)\n throw new MigrationError(\n `Raw index \"${index.name}\" must be one statement with no semicolon or open comment.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { indexName: index.name } }\n );\n const word = refused.find((candidate) => statements[0]!.includes(candidate));\n if (word !== undefined)\n throw new MigrationError(\n `Raw index \"${index.name}\" says ${word}; remove it from the template.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { indexName: index.name } }\n );\n}\n\n/**\n * What a database holds beside a raw index: canonical JSON of its columns,\n * name and hash, which is exactly the projection `fingerprintSnapshot` hashes.\n */\nexport function rawIndexMarker(index: IndexDef): string {\n return canonicalizeJsonText({\n columns: index.columns,\n name: index.name,\n raw: index.raw!.hash,\n });\n}\n\n/**\n * A raw index from the marker beside index `name`, or undefined when the text\n * is not one VibORM wrote for that index (an index renamed by hand keeps a\n * marker naming its old name, and is no longer the declared one).\n */\nexport function readRawIndexMarker(\n text: string,\n name: string\n): IndexDef | undefined {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (!isRecord(value)) return undefined;\n const keys = Object.keys(value).sort();\n if (keys.join() !== \"columns,name,raw\") return undefined;\n const { columns, raw } = value;\n if (\n value.name !== name ||\n !isSha256(raw) ||\n !Array.isArray(columns) ||\n columns.length === 0 ||\n !columns.every((column) => isString(column) && column !== \"\")\n )\n return undefined;\n return {\n name,\n columns: [...columns],\n unique: false,\n raw: { hash: raw },\n };\n}\n","/**\n * Hostile parser and hash owner for Migration V1 schema snapshots.\n *\n * Snapshot bytes are admitted only after exact-key validation,\n * re-canonicalization against the original bytes, and hash recomputation.\n */\n\nimport type { DecimalDescriptor } from \"../validation/primitives/decimal-codec\";\nimport { isNumber, isRecord, isString } from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport { rawIndexFields, rawIndexHash } from \"./raw-index\";\nimport type {\n AutoViewCascade,\n AutoViewDef,\n AutoViewObject,\n AutoViewStorage,\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PolymorphicSnapshotStorage,\n PolymorphicToManySnapshotMember,\n PolymorphicToOneSnapshotMember,\n PolymorphicToOneStorageRegistryEntry,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n ViewDef,\n} from \"./types\";\nimport {\n corrupt,\n exactKeys,\n exactObject,\n ks,\n parseArray,\n parseBoolean,\n parseMember,\n parseNonEmptyArray,\n parseString,\n parseStringArray,\n refuse,\n reqIds,\n reqStr,\n} from \"./v1-parse-shared\";\nimport { isViewHash, sortAutoViewObjects } from \"./view\";\n\nconst SNAPSHOT_KEYS = ks(\"enums polymorphicStorage tables views\");\nconst TABLE_KEYS = ks(\n \"columns foreignKeys indexes junction name primaryKey relationStorage uniqueConstraints\"\n);\nconst TABLE_REQUIRED_KEYS = ks(\n \"columns foreignKeys indexes name uniqueConstraints\"\n);\nconst COLUMN_KEYS = ks(\n \"autoIncrement dateTime geoPointEncoding decimal default name nullable type\"\n);\nconst DECIMAL_KEYS = ks(\"precision scale\");\nconst PRIMARY_KEY_KEYS = ks(\"columns name withoutRowid\");\nconst INDEX_KEYS = ks(\"columns name raw type unique where\");\nconst RAW_INDEX_KEYS = ks(\"hash template\");\nconst FOREIGN_KEY_KEYS = ks(\n \"columns name onDelete onUpdate referencedColumns referencedTable\"\n);\nconst UNIQUE_CONSTRAINT_KEYS = ks(\"columns name\");\nconst ENUM_KEYS = ks(\"name values\");\nconst VIEW_KEYS = ks(\"auto dependsOn hash indexes materialized name sql\");\nconst AUTO_VIEW_KEYS = ks(\"objects storage\");\nconst AUTO_OBJECT_KEYS = ks(\"kind name table\");\nconst AUTO_OBJECT_KINDS = [\"function\", \"trigger\", \"view\"] as const;\nconst AUTO_STORAGE_KEYS = ks(\n \"cascades columns grouped key reads source sourceKey\"\n);\nconst AUTO_CASCADE_KEYS = ks(\"children table trigger\");\nconst AUTO_CHILD_KEYS = ks(\"action columns referencedColumns table\");\nconst AUTO_ACTIONS = [\"cascade\", \"setNull\"] as const;\nconst VIEW_REQUIRED_KEYS = ks(\"dependsOn hash name sql\");\nconst RELATION_STORAGE_KEYS = ks(\"idColumn index kind typeColumn\");\nconst POLYMORPHIC_TO_ONE_KEYS = ks(\n \"kind members ownerTable relation storageRef\"\n);\nconst POLYMORPHIC_TO_MANY_KEYS = ks(\"kind members ownerTable relation\");\nconst POLYMORPHIC_TO_ONE_MEMBER_KEYS = ks(\"publicType storedType targetTable\");\nconst POLYMORPHIC_TO_MANY_MEMBER_KEYS = ks(\n \"inverseCardinality memberJunctionTable publicType storedType targetTable\"\n);\nconst DATETIME_PHYSICAL: Readonly<Record<string, string>> = {\n text: \"TEXT\",\n epochMillis: \"INTEGER\",\n julianDay: \"REAL\",\n};\n\nfunction parseColumn(value: unknown, label: string): ColumnDef {\n const record = exactObject(\n value,\n COLUMN_KEYS,\n ks(\"name nullable type\"),\n label\n );\n const column: ColumnDef = {\n name: reqStr(record, \"name\", label),\n type: reqStr(record, \"type\", label),\n nullable: parseBoolean(record.nullable, `${label}.nullable`),\n };\n if (\"default\" in record)\n column.default = parseString(record.default, `${label}.default`);\n if (\"autoIncrement\" in record)\n column.autoIncrement = parseBoolean(\n record.autoIncrement,\n `${label}.autoIncrement`\n );\n if (\"decimal\" in record)\n column.decimal = parseDecimalDescriptor(record.decimal, `${label}.decimal`);\n if (\"geoPointEncoding\" in record) {\n if (\n (record.geoPointEncoding !== \"legacy\" &&\n record.geoPointEncoding !== \"binary64\") ||\n column.type.toUpperCase() !== \"VIBORM_GEO_TEXT\" ||\n column.decimal !== undefined ||\n \"dateTime\" in record\n )\n refuse(`${label}.geoPointEncoding invalid`);\n column.geoPointEncoding = record.geoPointEncoding;\n }\n if (\"dateTime\" in record) {\n if (\n !isString(record.dateTime) ||\n (record.dateTime !== \"text\" &&\n record.dateTime !== \"epochMillis\" &&\n record.dateTime !== \"julianDay\")\n )\n refuse(`${label}.dateTime invalid`);\n if (column.type.toUpperCase() !== DATETIME_PHYSICAL[record.dateTime])\n refuse(`${label}.dateTime contradicts type`);\n if (column.decimal !== undefined)\n refuse(`${label} cannot be both dateTime and decimal`);\n column.dateTime = record.dateTime;\n }\n return column;\n}\n\nfunction parseDecimalDescriptor(\n value: unknown,\n label: string\n): DecimalDescriptor {\n const record = exactKeys(value, DECIMAL_KEYS, label);\n if (\n !(isNumber(record.precision) && Number.isSafeInteger(record.precision)) ||\n record.precision < 1\n )\n refuse(`${label}.precision invalid`);\n if (\n !(isNumber(record.scale) && Number.isSafeInteger(record.scale)) ||\n Object.is(record.scale, -0) ||\n record.scale < 0 ||\n record.scale > record.precision\n )\n refuse(`${label}.scale invalid`);\n return { precision: record.precision, scale: record.scale };\n}\n\nfunction parsePrimaryKey(value: unknown, label: string): PrimaryKeyDef {\n const record = exactObject(value, PRIMARY_KEY_KEYS, [\"columns\"], label);\n const primaryKey: PrimaryKeyDef = {\n columns: reqIds(record, \"columns\", label),\n };\n if (\"name\" in record) primaryKey.name = reqStr(record, \"name\", label);\n if (\"withoutRowid\" in record) {\n if (record.withoutRowid !== true)\n refuse(`${label}.withoutRowid must be true`);\n primaryKey.withoutRowid = true;\n }\n return primaryKey;\n}\n\nfunction parseIndex(value: unknown, label: string): IndexDef {\n const record = exactObject(\n value,\n INDEX_KEYS,\n ks(\"columns name unique\"),\n label\n );\n const index: IndexDef = {\n name: reqStr(record, \"name\", label),\n columns: reqIds(record, \"columns\", label),\n unique: parseBoolean(record.unique, `${label}.unique`),\n };\n if (\"type\" in record)\n index.type = parseMember(\n record.type,\n [\"btree\", \"hash\", \"gin\", \"gist\", \"fulltext\", \"spatial\"] as const,\n `${label}.type invalid`\n );\n if (\"where\" in record)\n index.where = parseString(record.where, `${label}.where`);\n if (\"raw\" in record) {\n const raw = exactKeys(record.raw, RAW_INDEX_KEYS, `${label}.raw`);\n const template = parseString(raw.template, `${label}.raw.template`);\n if (raw.hash !== rawIndexHash(template))\n refuse(`${label}.raw.hash mismatch`);\n if (index.unique || index.type !== undefined || index.where !== undefined)\n refuse(`${label} raw index cannot be unique, typed, or partial`);\n if (rawIndexFields(template).length !== index.columns.length)\n refuse(`${label}.columns mismatch template`);\n index.raw = { hash: raw.hash, template };\n }\n return index;\n}\n\nconst REFERENTIAL_ACTIONS: readonly ReferentialAction[] = [\n \"cascade\",\n \"setNull\",\n \"restrict\",\n \"noAction\",\n \"setDefault\",\n];\n\nfunction parseForeignKey(value: unknown, label: string): ForeignKeyDef {\n const record = exactObject(\n value,\n FOREIGN_KEY_KEYS,\n ks(\"columns name referencedColumns referencedTable\"),\n label\n );\n const foreignKey: ForeignKeyDef = {\n name: reqStr(record, \"name\", label),\n columns: reqIds(record, \"columns\", label),\n referencedTable: reqStr(record, \"referencedTable\", label),\n referencedColumns: reqIds(record, \"referencedColumns\", label),\n };\n if (\"onDelete\" in record)\n foreignKey.onDelete = parseMember(\n record.onDelete,\n REFERENTIAL_ACTIONS,\n `${label}.onDelete invalid`\n );\n if (\"onUpdate\" in record)\n foreignKey.onUpdate = parseMember(\n record.onUpdate,\n REFERENTIAL_ACTIONS,\n `${label}.onUpdate invalid`\n );\n return foreignKey;\n}\n\nfunction parseUniqueConstraint(\n value: unknown,\n label: string\n): UniqueConstraintDef {\n const record = exactKeys(value, UNIQUE_CONSTRAINT_KEYS, label);\n return {\n name: reqStr(record, \"name\", label),\n columns: reqIds(record, \"columns\", label),\n };\n}\n\nfunction parseRelationStorage(\n value: unknown,\n label: string\n): Readonly<Record<string, PolymorphicToOneStorageRegistryEntry>> {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n const entries: Record<string, PolymorphicToOneStorageRegistryEntry> = {};\n for (const [storageRef, rawEntry] of Object.entries(value)) {\n const entryLabel = `${label}.${storageRef}`;\n const record = exactKeys(rawEntry, RELATION_STORAGE_KEYS, entryLabel);\n if (record.kind !== \"polymorphicToOne\")\n refuse(`${entryLabel}.kind must be polymorphicToOne`);\n Object.defineProperty(entries, storageRef, {\n configurable: true,\n enumerable: true,\n value: {\n kind: \"polymorphicToOne\",\n typeColumn: reqStr(record, \"typeColumn\", entryLabel),\n idColumn: reqStr(record, \"idColumn\", entryLabel),\n index: reqStr(record, \"index\", entryLabel),\n },\n writable: true,\n });\n }\n return entries;\n}\n\nfunction parseTable(value: unknown, label: string): TableDef {\n const record = exactObject(value, TABLE_KEYS, TABLE_REQUIRED_KEYS, label);\n const name = reqStr(record, \"name\", label);\n for (const key of [\n \"columns\",\n \"indexes\",\n \"foreignKeys\",\n \"uniqueConstraints\",\n ] as const) {\n if (!Array.isArray(record[key])) refuse(`${label}.${key} must be an array`);\n }\n const table: TableDef = {\n name,\n columns: parseArray(record.columns, `${label}.columns`, parseColumn),\n indexes: parseArray(record.indexes, `${label}.indexes`, parseIndex),\n foreignKeys: parseArray(\n record.foreignKeys,\n `${label}.foreignKeys`,\n parseForeignKey\n ),\n uniqueConstraints: parseArray(\n record.uniqueConstraints,\n `${label}.uniqueConstraints`,\n parseUniqueConstraint\n ),\n };\n if (\"primaryKey\" in record)\n table.primaryKey = parsePrimaryKey(\n record.primaryKey,\n `${label}.primaryKey`\n );\n if (\"relationStorage\" in record)\n table.relationStorage = parseRelationStorage(\n record.relationStorage,\n `${label}.relationStorage`\n );\n if (record.junction === true) table.junction = true;\n return table;\n}\n\nfunction parseEnum(value: unknown, label: string): EnumDef {\n const record = exactKeys(value, ENUM_KEYS, label);\n return {\n name: reqStr(record, \"name\", label),\n values: parseStringArray(record.values, `${label}.values`),\n };\n}\n\n/** Strictly ascending: each once, in the one order a snapshot writes them. */\nfunction ascending(names: readonly string[]): boolean {\n return names.every((name, index) => index === 0 || names[index - 1]! < name);\n}\n\n/** What keeps a view kept by triggers, as the serializer writes it: every member, its objects sorted. */\nfunction parseAutoView(value: unknown, label: string): AutoViewDef {\n const record = exactKeys(value, AUTO_VIEW_KEYS, label);\n const objects = parseNonEmptyArray(\n record.objects,\n `${label}.objects`,\n (item, itemLabel): AutoViewObject => {\n const object = exactObject(\n item,\n AUTO_OBJECT_KEYS,\n ks(\"kind name\"),\n itemLabel\n );\n return {\n kind: parseMember(\n object.kind,\n AUTO_OBJECT_KINDS,\n `${itemLabel}.kind invalid`\n ),\n name: reqStr(object, \"name\", itemLabel),\n ...(\"table\" in object\n ? { table: reqStr(object, \"table\", itemLabel) }\n : {}),\n };\n }\n );\n if (JSON.stringify(sortAutoViewObjects(objects)) !== JSON.stringify(objects))\n refuse(`${label}.objects not sorted`);\n const storageLabel = `${label}.storage`;\n const storage = exactObject(\n record.storage,\n AUTO_STORAGE_KEYS,\n ks(\"columns grouped key reads source sourceKey\"),\n storageLabel\n );\n const grouped = parseBoolean(storage.grouped, `${storageLabel}.grouped`);\n const reads = reqIds(storage, \"reads\", storageLabel);\n if (!ascending(reads)) refuse(`${storageLabel}.reads not sorted/unique`);\n const parsed: AutoViewStorage = {\n source: reqStr(storage, \"source\", storageLabel),\n columns: parseNonEmptyArray(\n storage.columns,\n `${storageLabel}.columns`,\n parseColumn\n ),\n key: reqIds(storage, \"key\", storageLabel),\n sourceKey: reqIds(storage, \"sourceKey\", storageLabel),\n grouped,\n reads,\n };\n if (\"cascades\" in storage) {\n parsed.cascades = parseNonEmptyArray(\n storage.cascades,\n `${storageLabel}.cascades`,\n (item, itemLabel): AutoViewCascade => {\n const cascade = exactKeys(item, AUTO_CASCADE_KEYS, itemLabel);\n return {\n table: reqStr(cascade, \"table\", itemLabel),\n trigger: reqStr(cascade, \"trigger\", itemLabel),\n children: parseNonEmptyArray(\n cascade.children,\n `${itemLabel}.children`,\n (child, childLabel) => {\n const entry = exactKeys(child, AUTO_CHILD_KEYS, childLabel);\n return {\n table: reqStr(entry, \"table\", childLabel),\n columns: reqIds(entry, \"columns\", childLabel),\n referencedColumns: reqIds(\n entry,\n \"referencedColumns\",\n childLabel\n ),\n action: parseMember(\n entry.action,\n AUTO_ACTIONS,\n `${childLabel}.action invalid`\n ),\n };\n }\n ),\n };\n }\n );\n }\n return { objects, storage: parsed };\n}\n\nfunction parseView(value: unknown, label: string): ViewDef {\n const record = exactObject(value, VIEW_KEYS, VIEW_REQUIRED_KEYS, label);\n if (!isViewHash(record.hash)) refuse(`${label}.hash invalid`);\n const dependsOn = reqIds(record, \"dependsOn\", label);\n if (!ascending(dependsOn)) refuse(`${label}.dependsOn not sorted/unique`);\n const view: ViewDef = {\n name: reqStr(record, \"name\", label),\n hash: record.hash,\n sql: reqStr(record, \"sql\", label),\n dependsOn,\n };\n if (\"materialized\" in record) {\n if (record.materialized !== true)\n refuse(`${label}.materialized must be true`);\n view.materialized = true;\n }\n if (\"auto\" in record) {\n if (view.materialized)\n refuse(`${label} cannot be both materialized and auto`);\n view.auto = parseAutoView(record.auto, `${label}.auto`);\n }\n if (\"indexes\" in record) {\n if (!(view.materialized || view.auto))\n refuse(`${label}.indexes requires materialized/auto view`);\n view.indexes = parseNonEmptyArray(\n record.indexes,\n `${label}.indexes`,\n parseIndex\n );\n }\n return view;\n}\n\nfunction parseToOneMember(\n value: unknown,\n label: string\n): PolymorphicToOneSnapshotMember {\n const record = exactKeys(value, POLYMORPHIC_TO_ONE_MEMBER_KEYS, label);\n return {\n publicType: reqStr(record, \"publicType\", label),\n storedType: reqStr(record, \"storedType\", label),\n targetTable: reqStr(record, \"targetTable\", label),\n };\n}\n\nfunction parseToManyMember(\n value: unknown,\n label: string\n): PolymorphicToManySnapshotMember {\n const record = exactKeys(value, POLYMORPHIC_TO_MANY_MEMBER_KEYS, label);\n if (\n record.inverseCardinality !== \"one\" &&\n record.inverseCardinality !== \"many\"\n )\n refuse(`${label}.inverseCardinality invalid`);\n return {\n publicType: reqStr(record, \"publicType\", label),\n storedType: reqStr(record, \"storedType\", label),\n targetTable: reqStr(record, \"targetTable\", label),\n memberJunctionTable: reqStr(record, \"memberJunctionTable\", label),\n inverseCardinality: record.inverseCardinality,\n };\n}\n\nfunction parsePolymorphicStorage(\n value: unknown,\n label: string\n): PolymorphicSnapshotStorage {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n if (value.kind === \"toOne\") {\n const record = exactKeys(value, POLYMORPHIC_TO_ONE_KEYS, label);\n return {\n ownerTable: reqStr(record, \"ownerTable\", label),\n relation: reqStr(record, \"relation\", label),\n kind: \"toOne\",\n storageRef: reqStr(record, \"storageRef\", label),\n members: parseArray(record.members, `${label}.members`, parseToOneMember),\n };\n }\n if (value.kind === \"toMany\") {\n const record = exactKeys(value, POLYMORPHIC_TO_MANY_KEYS, label);\n return {\n ownerTable: reqStr(record, \"ownerTable\", label),\n relation: reqStr(record, \"relation\", label),\n kind: \"toMany\",\n members: parseArray(\n record.members,\n `${label}.members`,\n parseToManyMember\n ),\n };\n }\n refuse(`${label}.kind must be toOne or toMany`);\n}\n\nexport function parseSnapshotDocument(\n bytes: Uint8Array,\n expectedHash: Sha256\n): SchemaSnapshot {\n const parsed = parseJsonBytes(bytes, `snapshots/${expectedHash}.json`);\n const record = exactObject(parsed, SNAPSHOT_KEYS, [\"tables\"], \"snapshot\");\n const snapshot: SchemaSnapshot = {\n tables: parseArray(record.tables, \"snapshot.tables\", parseTable),\n };\n if (\"enums\" in record)\n snapshot.enums = parseArray(record.enums, \"snapshot.enums\", parseEnum);\n if (\"polymorphicStorage\" in record)\n snapshot.polymorphicStorage = parseArray(\n record.polymorphicStorage,\n \"snapshot.polymorphicStorage\",\n parsePolymorphicStorage\n );\n if (\"views\" in record) {\n const views = parseNonEmptyArray(record.views, \"snapshot.views\", parseView);\n if (!ascending(views.map(({ name }) => name)))\n refuse(\"snapshot.views not sorted/unique\");\n snapshot.views = views;\n }\n assertCanonicalBytes(bytes, snapshot, `snapshots/${expectedHash}.json`);\n if (domainHash(HASH_DOMAIN.snapshot, bytes) !== expectedHash)\n corrupt(\"snapshot hash mismatch\");\n return snapshot;\n}\n\nexport function encodeSnapshot(snapshot: SchemaSnapshot): {\n bytes: Uint8Array;\n snapshotHash: Sha256;\n} {\n const bytes = canonicalizeJson(omitUndefinedKeys(snapshot));\n return { bytes, snapshotHash: domainHash(HASH_DOMAIN.snapshot, bytes) };\n}\n\nexport function omitUndefinedKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(omitUndefinedKeys);\n if (!isRecord(value)) return value;\n const admitted: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n const item = value[key];\n if (item !== undefined) admitted[key] = omitUndefinedKeys(item);\n }\n return admitted;\n}\n","import { isRecord, isString } from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport {\n domainHash,\n HASH_ALGORITHM,\n HASH_DOMAIN,\n parseSha256,\n type Sha256,\n} from \"./identity\";\nimport { normalizeManagedTables } from \"./target\";\nimport type { MigrationTarget } from \"./types\";\nimport { parseDispatch } from \"./v1-parse-dispatch\";\nimport {\n corrupt,\n exactKeys,\n exactObject,\n ks,\n parseArray,\n parseBoolean,\n parseFormat,\n parseMember,\n parseNonEmptyArray,\n parseRequiredString,\n refuse,\n reqStr,\n} from \"./v1-parse-shared\";\nimport type {\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationEstateDescriptorV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationRollbackV1,\n MigrationStateManifestV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport {\n encodePathHash,\n eventIdFor,\n parseLedgerEvent,\n parseMarkerRow,\n} from \"./v1-parse-control\";\nexport { encodeDispatchIdentity, parseDispatch } from \"./v1-parse-dispatch\";\nexport {\n encodeSnapshot,\n parseSnapshotDocument,\n} from \"./v1-parse-snapshot\";\n\nconst ESTATE_KEYS = ks(\"format hash target\");\nconst PG_TARGET_KEYS = ks(\"dialect namespace tables\");\nconst DIALECT_ONLY_TARGET_KEYS = ks(\"dialect tables\");\nconst CHECK_KEYS = ks(\"equals id kind query\");\nconst PROVEN_STEP_KEYS = ks(\"execute postcheck precheck retry\");\nconst OPAQUE_STEP_KEYS = ks(\"execute retry\");\nconst OPERATION_KEYS = ks(\"id label origin risk steps\");\nconst SCHEMA_ROLLBACK_KEYS = ks(\"kind operations\");\nconst MANUAL_ROLLBACK_KEYS = ks(\"kind operations requestedBoundary\");\nconst IRREVERSIBLE_KEYS = ks(\"kind reason\");\nconst TRANSITION_HASH_KEYS = [\n \"adopts\",\n \"approvals\",\n \"fromState\",\n \"operations\",\n \"originChecks\",\n \"requestedForwardBoundary\",\n \"rollback\",\n] as const;\nconst PARENT_KEYS = [...TRANSITION_HASH_KEYS, \"transitionHash\"];\nconst PARENT_REQUIRED_KEYS = PARENT_KEYS.filter(\n (key) => key !== \"adopts\" && key !== \"approvals\"\n);\nconst STATE_HASH_KEYS = [\n \"destinationChecks\",\n \"estateHash\",\n \"format\",\n \"name\",\n \"parents\",\n \"snapshotHash\",\n \"sqlHash\",\n] as const;\nconst STATE_KEYS = [...STATE_HASH_KEYS, \"stateId\"];\nconst STATE_ALLOWED_KEYS = [...STATE_KEYS, \"snapshotArtifactHash\"];\nconst APPROVAL_KEYS = ks(\"column operation table\");\nconst APPROVAL_OPERATIONS: readonly MigrationApprovalV1[\"operation\"][] = [\n \"addColumn\",\n \"alterColumn\",\n \"dropColumn\",\n \"dropTable\",\n];\n\nfunction parseManagedTables(value: unknown, label: string): readonly string[] {\n try {\n const tables = normalizeManagedTables(value);\n if (tables !== undefined) return tables;\n } catch {\n refuse(`${label}.tables invalid`);\n }\n return refuse(`${label}.tables must be an array`);\n}\n\nexport function parseMigrationTarget(\n value: unknown,\n label: string\n): MigrationTarget {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n const dialect = value.dialect;\n if (dialect === \"postgresql\") {\n const record = exactObject(\n value,\n PG_TARGET_KEYS,\n ks(\"dialect namespace\"),\n label\n );\n return {\n dialect: \"postgresql\",\n namespace: reqStr(record, \"namespace\", label),\n ...(value.tables === undefined\n ? {}\n : { tables: parseManagedTables(value.tables, label) }),\n };\n }\n if (dialect === \"mysql\" || dialect === \"sqlite\" || dialect === \"surrealql\") {\n exactObject(value, DIALECT_ONLY_TARGET_KEYS, [\"dialect\"], label);\n return {\n dialect,\n ...(value.tables === undefined\n ? {}\n : { tables: parseManagedTables(value.tables, label) }),\n };\n }\n refuse(`${label}.dialect invalid`);\n}\n\nexport function parseEstateDescriptor(bytes: Uint8Array): {\n descriptor: MigrationEstateDescriptorV1;\n estateHash: Sha256;\n} {\n const parsed = parseJsonBytes(bytes, \"estate.json\");\n const record = exactKeys(parsed, ESTATE_KEYS, \"estate.json\");\n if (record.hash !== HASH_ALGORITHM)\n refuse('estate.json hash must be \"sha256\"');\n const descriptor: MigrationEstateDescriptorV1 = {\n format: parseFormat(record.format, \"estate.json\"),\n target: parseMigrationTarget(record.target, \"estate.json.target\"),\n hash: \"sha256\",\n };\n assertCanonicalBytes(bytes, descriptor, \"estate.json\");\n return { descriptor, estateHash: domainHash(HASH_DOMAIN.estate, bytes) };\n}\n\nexport function encodeEstateDescriptor(target: MigrationTarget): {\n bytes: Uint8Array;\n estateHash: Sha256;\n descriptor: MigrationEstateDescriptorV1;\n} {\n const descriptor: MigrationEstateDescriptorV1 = {\n format: \"1\",\n target,\n hash: \"sha256\",\n };\n const bytes = canonicalizeJson(descriptor);\n return {\n bytes,\n estateHash: domainHash(HASH_DOMAIN.estate, bytes),\n descriptor,\n };\n}\n\nfunction parseCheck(value: unknown, label: string): MigrationBooleanCheckV1 {\n const record = exactKeys(value, CHECK_KEYS, label);\n return {\n kind: parseMember(\n record.kind,\n [\"driver\", \"trusted-read\"] as const,\n `${label}.kind invalid`\n ),\n id: reqStr(record, \"id\", label),\n query: parseDispatch(record.query, `${label}.query`),\n equals: parseBoolean(record.equals, `${label}.equals`),\n };\n}\n\nfunction parseStep(value: unknown, label: string): MigrationStepV1 {\n if (\n !isRecord(value) ||\n (value.retry !== \"proven\" && value.retry !== \"opaque\")\n )\n refuse(`${label}.retry invalid`);\n if (value.retry === \"proven\") {\n const record = exactKeys(value, PROVEN_STEP_KEYS, label);\n return {\n retry: \"proven\",\n precheck: parseCheck(record.precheck, `${label}.precheck`),\n execute: parseDispatch(record.execute, `${label}.execute`),\n postcheck: parseCheck(record.postcheck, `${label}.postcheck`),\n };\n }\n const record = exactKeys(value, OPAQUE_STEP_KEYS, label);\n return {\n retry: \"opaque\",\n execute: parseDispatch(record.execute, `${label}.execute`),\n };\n}\n\nfunction parseOperation(value: unknown, label: string): MigrationOperationV1 {\n const record = exactKeys(value, OPERATION_KEYS, label);\n return {\n id: reqStr(record, \"id\", label),\n label: reqStr(record, \"label\", label),\n origin: parseMember(\n record.origin,\n [\"generated\", \"manual\"] as const,\n `${label}.origin invalid`\n ),\n risk: parseMember(\n record.risk,\n [\"safe\", \"destructive\", \"opaque\"] as const,\n `${label}.risk invalid`\n ),\n steps: parseNonEmptyArray(record.steps, `${label}.steps`, parseStep),\n };\n}\n\nfunction parseRollback(value: unknown, label: string): MigrationRollbackV1 {\n if (!(isRecord(value) && isString(value.kind)))\n refuse(`${label} invalid rollback`);\n if (value.kind === \"schema\") {\n const record = exactKeys(value, SCHEMA_ROLLBACK_KEYS, label);\n return {\n kind: \"schema\",\n operations: parseArray(\n record.operations,\n `${label}.operations`,\n parseOperation\n ),\n };\n }\n if (value.kind === \"manual\") {\n const record = exactKeys(value, MANUAL_ROLLBACK_KEYS, label);\n return {\n kind: \"manual\",\n requestedBoundary: parseMember(\n record.requestedBoundary,\n [\"transactional\", \"stepwise\"] as const,\n `${label}.requestedBoundary invalid`\n ),\n operations: parseArray(\n record.operations,\n `${label}.operations`,\n parseOperation\n ),\n };\n }\n if (value.kind === \"irreversible\") {\n const record = exactKeys(value, IRREVERSIBLE_KEYS, label);\n if (!isString(record.reason) || record.reason.trim().length === 0)\n refuse(`${label}.reason empty`);\n return { kind: \"irreversible\", reason: record.reason };\n }\n refuse(`${label}.kind invalid`);\n}\n\nfunction parseAdopts(value: unknown, label: string): readonly string[] {\n if (!Array.isArray(value) || value.length === 0)\n refuse(`${label} must be non-empty array`);\n return value.map((name: unknown, index) => {\n if (!isString(name) || name.length === 0 || name.includes(\"\\0\"))\n refuse(`${label}[${index}] invalid table name`);\n const previous: unknown = value[index - 1];\n if (index > 0 && !(isString(previous) && previous < name))\n refuse(`${label} not sorted/unique`);\n return name;\n });\n}\n\nfunction parseApprovals(\n value: unknown,\n label: string\n): readonly MigrationApprovalV1[] {\n return parseNonEmptyArray(value, label, (entry, at) =>\n parseApproval(exactKeys(entry, APPROVAL_KEYS, at), at)\n );\n}\n\nexport function parseApproval(\n fields: Readonly<Record<string, unknown>>,\n at: string,\n refuseWith: (message: string) => never = refuse\n): MigrationApprovalV1 {\n const { column, operation, table } = fields;\n const known = APPROVAL_OPERATIONS.find((name) => name === operation);\n if (!known) refuseWith(`${at}.operation invalid`);\n if (!isString(table) || table.length === 0) refuseWith(`${at}.table invalid`);\n if (column !== null && !(isString(column) && column.length > 0))\n refuseWith(`${at}.column invalid`);\n return { operation: known, table, column };\n}\n\nexport function encodeTransitionHash(\n transition: Omit<MigrationParentTransitionV1, \"transitionHash\">\n): Sha256 {\n const body: Record<string, unknown> = {};\n for (const key of TRANSITION_HASH_KEYS) {\n if (transition[key] !== undefined) body[key] = transition[key];\n }\n return domainHash(HASH_DOMAIN.transition, canonicalizeJson(body));\n}\n\nfunction parseParent(\n value: unknown,\n label: string\n): MigrationParentTransitionV1 {\n const record = exactObject(value, PARENT_KEYS, PARENT_REQUIRED_KEYS, label);\n const fromState =\n record.fromState === null\n ? null\n : parseSha256(record.fromState, `${label}.fromState`);\n if (\n record.requestedForwardBoundary !== null &&\n record.requestedForwardBoundary !== \"transactional\" &&\n record.requestedForwardBoundary !== \"stepwise\"\n )\n refuse(`${label}.requestedForwardBoundary invalid`);\n const operations = parseArray(\n record.operations,\n `${label}.operations`,\n parseOperation\n );\n const rollback = parseRollback(record.rollback, `${label}.rollback`);\n const origins = new Set(operations.map((operation) => operation.origin));\n if (origins.size > 1) refuse(`${label} mixes generated and manual`);\n if (record.requestedForwardBoundary !== null && origins.has(\"generated\"))\n refuse(`${label}.requestedForwardBoundary requires manual`);\n if (rollback.kind === \"manual\" && origins.has(\"generated\"))\n refuse(`${label}.rollback manual on generated`);\n const parsed: Omit<MigrationParentTransitionV1, \"transitionHash\"> = {\n fromState,\n originChecks: parseArray(\n record.originChecks,\n `${label}.originChecks`,\n parseCheck\n ),\n requestedForwardBoundary: record.requestedForwardBoundary,\n operations,\n rollback,\n ...(record.approvals === undefined\n ? {}\n : { approvals: parseApprovals(record.approvals, `${label}.approvals`) }),\n ...(record.adopts === undefined\n ? {}\n : { adopts: parseAdopts(record.adopts, `${label}.adopts`) }),\n };\n const transitionHash = parseSha256(\n record.transitionHash,\n `${label}.transitionHash`\n );\n if (transitionHash !== encodeTransitionHash(parsed))\n corrupt(`${label}.transitionHash mismatch`);\n return { ...parsed, transitionHash };\n}\n\nexport function compareFromState(\n left: Sha256 | null,\n right: Sha256 | null\n): number {\n if (left === right) return 0;\n if (left === null) return -1;\n if (right === null) return 1;\n return left < right ? -1 : 1;\n}\n\nexport function sortParents(\n parents: readonly MigrationParentTransitionV1[]\n): MigrationParentTransitionV1[] {\n return [...parents].sort((left, right) =>\n compareFromState(left.fromState, right.fromState)\n );\n}\n\nexport function encodeStateId(\n manifest: Omit<MigrationStateManifestV1, \"stateId\">\n): Sha256 {\n const body: Record<string, unknown> = {};\n for (const key of STATE_HASH_KEYS) {\n body[key] = manifest[key];\n }\n if (manifest.snapshotArtifactHash !== undefined) {\n body.snapshotArtifactHash = manifest.snapshotArtifactHash;\n }\n return domainHash(HASH_DOMAIN.state, canonicalizeJson(body));\n}\n\nexport function parseStateManifest(\n bytes: Uint8Array,\n expectedId: Sha256\n): MigrationStateManifestV1 {\n const parsed = parseJsonBytes(bytes, `states/${expectedId}.json`);\n const record = exactObject(\n parsed,\n STATE_ALLOWED_KEYS,\n STATE_KEYS,\n \"state manifest\"\n );\n const name = parseRequiredString(record.name, \"state manifest.name\");\n const parents = parseNonEmptyArray(\n record.parents,\n \"state.parents\",\n parseParent\n );\n for (let i = 1; i < parents.length; i++) {\n if (compareFromState(parents[i - 1]!.fromState, parents[i]!.fromState) >= 0)\n refuse(\"state.parents not sorted\");\n }\n const withoutId: Omit<MigrationStateManifestV1, \"stateId\"> = {\n format: parseFormat(record.format, \"state manifest\"),\n estateHash: parseSha256(record.estateHash, \"state.estateHash\"),\n name,\n snapshotHash: parseSha256(record.snapshotHash, \"state.snapshotHash\"),\n ...(\"snapshotArtifactHash\" in record\n ? {\n snapshotArtifactHash: parseSha256(\n record.snapshotArtifactHash,\n \"state.snapshotArtifactHash\"\n ),\n }\n : {}),\n sqlHash: parseSha256(record.sqlHash, \"state.sqlHash\"),\n destinationChecks: parseArray(\n record.destinationChecks,\n \"state.destinationChecks\",\n parseCheck\n ),\n parents,\n };\n assertCanonicalBytes(\n bytes,\n { ...withoutId, stateId: expectedId },\n `states/${expectedId}.json`\n );\n const stateId = parseSha256(record.stateId, \"state.stateId\");\n if (stateId !== encodeStateId(withoutId) || stateId !== expectedId)\n corrupt(\"stateId mismatch\");\n return { ...withoutId, stateId };\n}\n\nexport function encodeStateManifest(\n manifest: Omit<MigrationStateManifestV1, \"stateId\">\n): { bytes: Uint8Array; stateId: Sha256; manifest: MigrationStateManifestV1 } {\n const parents = sortParents(manifest.parents);\n const sorted = { ...manifest, parents };\n const stateId = encodeStateId(sorted);\n const complete = { ...sorted, stateId };\n return { bytes: canonicalizeJson(complete), stateId, manifest: complete };\n}\n\nexport function encodeSqlBlob(bytes: Uint8Array): Sha256 {\n return domainHash(HASH_DOMAIN.sql, bytes);\n}\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","import { renderQualifiedIdentifier } from \"../sql/identifiers\";\n/**\n * Driver catalog probes. These are the only checks the ORM proves read-only.\n * Manual trusted-read checks are a different arm.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"./drivers\";\nimport { RAW_INDEX_MARKER_PREFIX, rawIndexMarker } from \"./raw-index\";\nimport type { AutoViewObject, DiffOperation, IndexDef } from \"./types\";\nimport type { MigrationParameterV1 } from \"./v1-types\";\n\nexport interface CatalogProbe {\n readonly id: string;\n readonly sql: string;\n readonly parameters: readonly MigrationParameterV1[];\n readonly equals: boolean;\n}\n\ntype CatalogProbeLifetime = \"live-command\" | \"stored-artifact\";\n\nfunction namespace(driver: MigrationDriver): string | undefined {\n return (\n driver.namespace ??\n (driver.target?.dialect === \"postgresql\"\n ? driver.target.namespace\n : undefined)\n );\n}\n\nfunction boundCatalogNamespace(driver: MigrationDriver): string {\n const value = namespace(driver);\n if (value) return value;\n throw new MigrationError(\n \"Catalog probe requires a bound migration namespace\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { driver: driver.dialect } }\n );\n}\n\nfunction stringParam(value: string): MigrationParameterV1 {\n return { kind: \"string\", value };\n}\n\nfunction mysqlNamespaceParam(\n driver: MigrationDriver,\n lifetime: CatalogProbeLifetime\n): MigrationParameterV1 {\n return lifetime === \"stored-artifact\"\n ? { kind: \"target-namespace\" }\n : stringParam(boundCatalogNamespace(driver));\n}\n\nconst PG_CLASS_NS =\n \"pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\";\nconst existsSql = (from: string, where: string) =>\n `SELECT EXISTS (SELECT 1 FROM ${from} WHERE ${where})`;\nconst strParams = (...values: string[]) => values.map(stringParam);\nconst pgParams = (driver: MigrationDriver, ...names: string[]) =>\n strParams(boundCatalogNamespace(driver), ...names);\nconst myParams = (\n driver: MigrationDriver,\n lifetime: CatalogProbeLifetime,\n ...names: string[]\n) => [mysqlNamespaceParam(driver, lifetime), ...strParams(...names)];\nconst sqliteMaster = (type: string) =>\n existsSql(\"sqlite_master\", `type = '${type}' AND name = ?`);\n\nconst existsProbe = (\n kind: string,\n name: string,\n exists: boolean,\n sql: string,\n parameters: readonly MigrationParameterV1[]\n): CatalogProbe => ({\n id: `${kind}:${exists ? \"exists\" : \"absent\"}:${name}`,\n sql,\n parameters,\n equals: exists,\n});\n\nconst probePair = (\n creating: boolean,\n make: (exists: boolean) => CatalogProbe\n): { pre: CatalogProbe; post: CatalogProbe } => ({\n pre: make(!creating),\n post: make(creating),\n});\n\nexport function tableExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const d = driver.dialect;\n const [sql, params] =\n d === \"surrealql\"\n ? [\n \"RETURN [{ present: (INFO FOR DB STRUCTURE).tables.name CONTAINS $p1 }]\",\n strParams(tableName),\n ]\n : d === \"postgresql\"\n ? [\n existsSql(\n PG_CLASS_NS,\n \"n.nspname = $1 AND c.relname = $2 AND c.relkind IN ('r', 'p')\"\n ),\n pgParams(driver, tableName),\n ]\n : d === \"mysql\"\n ? [\n existsSql(\n \"information_schema.tables\",\n \"table_schema = ? AND table_name = ?\"\n ),\n myParams(driver, lifetime, tableName),\n ]\n : [sqliteMaster(\"table\"), strParams(tableName)];\n return existsProbe(\"table\", tableName, exists, sql, params);\n}\n\nexport function viewExistsProbe(\n driver: MigrationDriver,\n viewName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\",\n materialized = false\n): CatalogProbe {\n const kind = materialized ? \"materialized-view\" : \"view\";\n const d = driver.dialect;\n const [sql, params] =\n d === \"surrealql\"\n ? [\n \"RETURN [{ present: (INFO FOR DB STRUCTURE).tables.filter(|$t| $t.view != NONE).name CONTAINS $p1 }]\",\n strParams(viewName),\n ]\n : d === \"postgresql\"\n ? [\n existsSql(\n PG_CLASS_NS,\n `n.nspname = $1 AND c.relname = $2 AND c.relkind = '${materialized ? \"m\" : \"v\"}'`\n ),\n pgParams(driver, viewName),\n ]\n : d === \"mysql\"\n ? [\n existsSql(\n \"information_schema.views\",\n \"table_schema = ? AND table_name = ?\"\n ),\n myParams(driver, lifetime, viewName),\n ]\n : [sqliteMaster(\"view\"), strParams(viewName)];\n return existsProbe(kind, viewName, exists, sql, params);\n}\n\nexport function triggerExistsProbe(\n driver: MigrationDriver,\n table: string,\n triggerName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const d = driver.dialect;\n const [sql, params] =\n d === \"postgresql\"\n ? [\n existsSql(\n `pg_catalog.pg_trigger t JOIN ${PG_CLASS_NS} ON c.oid = t.tgrelid`,\n \"n.nspname = $1 AND c.relname = $2 AND t.tgname = $3\"\n ),\n pgParams(driver, table, triggerName),\n ]\n : d === \"mysql\"\n ? [\n existsSql(\n \"information_schema.triggers\",\n \"trigger_schema = ? AND trigger_name = ?\"\n ),\n myParams(driver, lifetime, triggerName),\n ]\n : [sqliteMaster(\"trigger\"), strParams(triggerName)];\n return existsProbe(\"trigger\", `${table}.${triggerName}`, exists, sql, params);\n}\n\nexport function columnExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n columnName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const d = driver.dialect;\n const [sql, params] =\n d === \"postgresql\"\n ? [\n existsSql(\n `pg_catalog.pg_attribute a JOIN ${PG_CLASS_NS} ON c.oid = a.attrelid`,\n \"n.nspname = $1 AND c.relname = $2 AND a.attname = $3 AND a.attnum > 0 AND NOT a.attisdropped\"\n ),\n pgParams(driver, tableName, columnName),\n ]\n : d === \"mysql\"\n ? [\n existsSql(\n \"information_schema.columns\",\n \"table_schema = ? AND table_name = ? AND column_name = ?\"\n ),\n myParams(driver, lifetime, tableName, columnName),\n ]\n : [\n existsSql(\"pragma_table_info(?)\", \"name = ?\"),\n strParams(tableName, columnName),\n ];\n return existsProbe(\n \"column\",\n `${tableName}.${columnName}`,\n exists,\n sql,\n params\n );\n}\n\nexport function indexExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n indexName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const d = driver.dialect;\n const [sql, params] =\n d === \"postgresql\"\n ? [\n existsSql(\n `${PG_CLASS_NS}${exists ? \" JOIN pg_catalog.pg_index x ON x.indexrelid = c.oid AND x.indisvalid\" : \"\"}`,\n \"n.nspname = $1 AND c.relname = $2 AND c.relkind = 'i'\"\n ),\n pgParams(driver, indexName),\n ]\n : d === \"mysql\"\n ? [\n existsSql(\n \"information_schema.statistics\",\n \"table_schema = ? AND table_name = ? AND index_name = ?\"\n ),\n myParams(driver, lifetime, tableName, indexName),\n ]\n : [sqliteMaster(\"index\"), strParams(indexName)];\n return existsProbe(\"index\", indexName, exists, sql, params);\n}\n\nfunction rawIndexMarkerProbe(\n driver: MigrationDriver,\n index: IndexDef,\n present: boolean\n): CatalogProbe {\n return {\n id: `index-marker:${present ? \"present\" : \"absent\"}:${index.name}`,\n sql: existsSql(\n PG_CLASS_NS,\n \"n.nspname = $1 AND c.relname = $2 AND c.relkind = 'i' AND pg_catalog.obj_description(c.oid, 'pg_class') IS NOT DISTINCT FROM $3\"\n ),\n parameters: pgParams(\n driver,\n index.name,\n RAW_INDEX_MARKER_PREFIX + rawIndexMarker(index)\n ),\n equals: present,\n };\n}\n\n/** The raw index whose marker a `COMMENT ON INDEX` statement writes. */\nfunction commentedRawIndex(\n operation: DiffOperation,\n statement: string\n): IndexDef | undefined {\n const indexes =\n operation.type === \"createIndex\"\n ? [operation.index]\n : operation.type === \"createTable\"\n ? operation.table.indexes\n : [];\n return indexes.find(\n (index) =>\n index.raw !== undefined &&\n statement.includes(\n (RAW_INDEX_MARKER_PREFIX + rawIndexMarker(index)).replaceAll(\"'\", \"''\")\n )\n );\n}\n\nconst CREATE_INDEX_HEADER =\n /^\\s*CREATE\\s+(?:UNIQUE\\s+|SPATIAL\\s+|FULLTEXT\\s+)?INDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?(\"(?:[^\"]|\"\")+\"|`(?:[^`]|``)+`|[\\w$]+)\\s+ON\\b/i;\n\n/** The trigger a `CREATE TRIGGER` or `DROP TRIGGER` statement names, unquoted. */\nconst TRIGGER_HEADER =\n /^(?:CREATE|DROP) TRIGGER (?:IF EXISTS )?(?:(?:\"(?:[^\"]|\"\")+\"|`(?:[^`]|``)+`)\\.)?(\"(?:[^\"]|\"\")+\"|`(?:[^`]|``)+`)/;\n\n/**\n * The probes of one statement of a view kept by triggers, created or\n * dropped: its table's, its body view's, each trigger's, and each index its\n * creation carries. Its function, its marker and its rows have none: they\n * stand with the table on a transactional dialect, and MySQL's filling is\n * written again whole by its next run.\n */\nfunction autoViewProbes(\n driver: MigrationDriver,\n view: string,\n objects: readonly AutoViewObject[],\n indexes: readonly IndexDef[],\n statement: string,\n creating: boolean\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n const text = statement.trimStart();\n // A creation's drops are of what a hand left: none is proven.\n if (creating && text.startsWith(\"DROP \")) return null;\n const pair = (probe: (exists: boolean) => CatalogProbe) =>\n probePair(creating, probe);\n if (text.startsWith(\"CREATE TABLE \") || text.startsWith(\"DROP TABLE \"))\n return pair((exists) =>\n tableExistsProbe(driver, view, exists, \"stored-artifact\")\n );\n const trigger = TRIGGER_HEADER.exec(text)?.[1];\n if (trigger !== undefined) {\n const name = trigger\n .slice(1, -1)\n .replaceAll(trigger[0]! + trigger[0], trigger[0]!);\n const object = objects.find(\n (candidate) => candidate.kind === \"trigger\" && candidate.name === name\n );\n return object\n ? pair((exists) =>\n triggerExistsProbe(\n driver,\n object.table!,\n name,\n exists,\n \"stored-artifact\"\n )\n )\n : null;\n }\n const body = objects.find((object) => object.kind === \"view\");\n if (\n body &&\n (text.startsWith(\"CREATE VIEW \") || text.startsWith(\"DROP VIEW \"))\n )\n return pair((exists) =>\n viewExistsProbe(driver, body.name, exists, \"stored-artifact\")\n );\n return creating ? createdIndexProbes(driver, view, indexes, statement) : null;\n}\n\n/** A view's own creation, materialized or not, as the SQL drivers write it. */\nconst VIEW_CREATION = /^CREATE (?:MATERIALIZED )?VIEW /;\n\n/** The name a `CREATE INDEX` statement gives its index, unquoted. */\nfunction createdIndexName(statement: string): string | undefined {\n const name = CREATE_INDEX_HEADER.exec(statement)?.[1];\n if (name === undefined) return undefined;\n const quote = name[0];\n return quote === '\"' || quote === \"`\"\n ? name.slice(1, -1).replaceAll(quote + quote, quote)\n : name;\n}\n\n/**\n * The probes of a `CREATE INDEX` statement that an operation creating a\n * relation runs after it (a table, a materialized view): the index named in\n * its header, neither one whose name it extends (`by_email_b`) nor a column\n * it indexes.\n */\nfunction createdIndexProbes(\n driver: MigrationDriver,\n relation: string,\n indexes: readonly IndexDef[],\n statement: string\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n const text = statement.trim().toUpperCase();\n if (!(text.startsWith(\"CREATE \") && text.includes(\"INDEX\"))) return null;\n const created = createdIndexName(statement);\n const index = indexes.find((item) => item.name === created);\n return index\n ? probePair(true, (exists) =>\n indexExistsProbe(\n driver,\n relation,\n index.name,\n exists,\n \"stored-artifact\"\n )\n )\n : null;\n}\n\nexport function probeForGeneratedStatement(\n driver: MigrationDriver,\n operation: DiffOperation,\n statement: string\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n // An operation here is several statements, and they run in the one transaction.\n if (driver.dialect === \"surrealql\") return null;\n if (\n (driver.dialect === \"postgresql\" || driver.dialect === \"mysql\") &&\n namespace(driver) === undefined\n ) {\n return null;\n }\n const text = statement.trim().toUpperCase();\n if (\n text.startsWith(\"PRAGMA\") ||\n text.startsWith(\"INSERT \") ||\n text.startsWith(\"--\")\n ) {\n return null;\n }\n if (text.startsWith(\"COMMENT ON INDEX\")) {\n const index = commentedRawIndex(operation, statement);\n return index === undefined\n ? null\n : probePair(true, (present) =>\n rawIndexMarkerProbe(driver, index, present)\n );\n }\n switch (operation.type) {\n case \"createTable\":\n return text.startsWith(\"CREATE TABLE\")\n ? probePair(true, (exists) =>\n tableExistsProbe(\n driver,\n operation.table.name,\n exists,\n \"stored-artifact\"\n )\n )\n : createdIndexProbes(\n driver,\n operation.table.name,\n operation.table.indexes,\n statement\n );\n case \"dropTable\":\n return probePair(false, (exists) =>\n tableExistsProbe(driver, operation.tableName, exists, \"stored-artifact\")\n );\n case \"addColumn\": {\n const pre = columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n false,\n \"stored-artifact\"\n );\n const required =\n !operation.column.nullable &&\n operation.column.default === undefined &&\n !operation.column.autoIncrement;\n const table = renderQualifiedIdentifier(\n (name) => driver.escapeIdentifier(name),\n driver.dialect === \"postgresql\" ? namespace(driver) : undefined,\n operation.tableName\n );\n return {\n pre: required\n ? {\n ...pre,\n id: `column:absent-and-empty-table:${operation.tableName}.${operation.column.name}`,\n sql: `SELECT (${pre.sql.slice(\"SELECT \".length)}) OR EXISTS (SELECT 1 FROM ${table} LIMIT 1)`,\n }\n : pre,\n post: columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n case \"dropColumn\":\n return probePair(false, (exists) =>\n columnExistsProbe(\n driver,\n operation.tableName,\n operation.columnName,\n exists,\n \"stored-artifact\"\n )\n );\n case \"createIndex\":\n return probePair(true, (exists) =>\n indexExistsProbe(\n driver,\n operation.tableName,\n operation.index.name,\n exists,\n \"stored-artifact\"\n )\n );\n case \"dropIndex\":\n return probePair(false, (exists) =>\n indexExistsProbe(\n driver,\n operation.tableName,\n operation.indexName,\n exists,\n \"stored-artifact\"\n )\n );\n case \"createView\":\n if (operation.view.auto)\n return autoViewProbes(\n driver,\n operation.view.name,\n operation.view.auto.objects,\n operation.view.indexes ?? [],\n statement,\n true\n );\n // A materialized view's creation is followed by its indexes.\n if (!VIEW_CREATION.test(text))\n return createdIndexProbes(\n driver,\n operation.view.name,\n operation.view.indexes ?? [],\n statement\n );\n return probePair(true, (exists) =>\n viewExistsProbe(\n driver,\n operation.view.name,\n exists,\n \"stored-artifact\",\n operation.view.materialized\n )\n );\n case \"dropView\":\n if (operation.auto)\n return autoViewProbes(\n driver,\n operation.viewName,\n operation.auto.objects,\n [],\n statement,\n false\n );\n return probePair(false, (exists) =>\n viewExistsProbe(\n driver,\n operation.viewName,\n exists,\n \"stored-artifact\",\n operation.materialized\n )\n );\n default:\n return null;\n }\n}\n\n/** One index an interrupted CONCURRENTLY build left INVALID. */\nexport interface InvalidIndex {\n readonly table: string;\n readonly index: string;\n}\n\n/**\n * The INVALID indexes on the estate's managed tables. Only PostgreSQL has the\n * state: MySQL and SQLite build an index or fail without leaving one behind.\n */\nexport async function readInvalidIndexes(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<readonly InvalidIndex[]> {\n if (driver.dialect !== \"postgresql\") return [];\n const result = await producer._executeRaw<InvalidIndex>(\n `SELECT t.relname AS \"table\", i.relname AS \"index\" FROM pg_catalog.pg_index x JOIN pg_catalog.pg_class i ON i.oid = x.indexrelid JOIN pg_catalog.pg_class t ON t.oid = x.indrelid JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT (x.indisvalid AND x.indisready) ORDER BY t.relname, i.relname`,\n [boundCatalogNamespace(driver)]\n );\n const managed = driver.target.tables;\n return result.rows.filter(\n (row) => managed === undefined || managed.includes(row.table)\n );\n}\n\nexport function boundNamespace(\n driver: BoundMigrationDriver\n): string | undefined {\n return namespace(driver);\n}\n\n/**\n * One object's name as a live statement spells it: qualified with the bound\n * namespace, or bare on SQLite and on unbound MySQL.\n */\nexport function qualifiedName(\n driver: BoundMigrationDriver,\n name: string\n): string {\n return renderQualifiedIdentifier(\n (part) => driver.escapeIdentifier(part),\n driver.target.dialect === \"sqlite\" || driver.target.dialect === \"surrealql\"\n ? undefined\n : namespace(driver),\n name\n );\n}\n","/**\n * Inverse owner for generated DiffOperation programs.\n * Empty programs invert to an empty schema rollback. Missing inverses are\n * irreversible. This is the only place that answers that question.\n */\n\nimport { applyNativeRename } from \"./native-rename\";\nimport type { DiffOperation, SchemaSnapshot, TableDef } from \"./types\";\nimport { defaultGeneratedPrimaryKeyName } from \"./utils\";\n\nexport interface InvertedOperations {\n operations: DiffOperation[];\n warnings: string[];\n}\n\nexport function invertOperations(\n operations: DiffOperation[],\n previousSnapshot: SchemaSnapshot,\n projectRename: typeof applyNativeRename = applyNativeRename,\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName = defaultGeneratedPrimaryKeyName\n): InvertedOperations {\n const warnings: string[] = [];\n const inverted: DiffOperation[] = [];\n // At the inverse of operation i, every rename that preceded i in the up\n // program is still active and every rename that followed it has already been\n // inverted. Keep the previous definitions at each exact prefix so a restored\n // FK targets the identity that exists at that point — neither always-old nor\n // always-new is correct.\n let previousAtOperationIdentity = previousSnapshot;\n const previousIdentityBefore: SchemaSnapshot[] = [];\n // A key the up program drops by itself (PostgreSQL/MySQL drop every key of\n // a dropped table first) comes back through that drop's own inverse, which\n // runs after every recreated table exists. The recreated table leaves it\n // out: restored inline it would name a table not yet recreated, and then be\n // added a second time.\n const keysRestoredByTheirOwnInverse = new Set<string>();\n for (const op of operations) {\n previousIdentityBefore.push(previousAtOperationIdentity);\n if (op.type === \"dropForeignKey\") {\n keysRestoredByTheirOwnInverse.add(\n foreignKeyIdentity(op.tableName, op.fkName)\n );\n }\n if (op.type === \"renameTable\" || op.type === \"renameColumn\") {\n previousAtOperationIdentity = projectRename(\n previousAtOperationIdentity,\n op\n );\n }\n }\n\n for (let i = operations.length - 1; i >= 0; i--) {\n const op = operations[i]!;\n const previousAtIdentity = previousIdentityBefore[i] ?? previousSnapshot;\n const findPrevTable = (name: string): TableDef | undefined =>\n previousAtIdentity.tables.find((table) => table.name === name);\n const inverse = invertOperation(\n op,\n previousSnapshot,\n findPrevTable,\n keysRestoredByTheirOwnInverse,\n warnings,\n primaryKeyName\n );\n if (inverse) inverted.push(...inverse);\n }\n\n return { operations: inverted, warnings };\n}\n\nconst foreignKeyIdentity = (tableName: string, fkName: string) =>\n `${tableName}\\u0000${fkName}`;\n\nfunction missingPrevious(warnings: string[], target: string): null {\n warnings.push(`Cannot invert ${target}: missing from previous snapshot.`);\n return null;\n}\n\nfunction invertOperation(\n op: DiffOperation,\n previousSnapshot: SchemaSnapshot,\n findPrevTable: (name: string) => TableDef | undefined,\n keysRestoredByTheirOwnInverse: ReadonlySet<string>,\n warnings: string[],\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName\n): DiffOperation[] | null {\n switch (op.type) {\n case \"createTable\":\n warnings.push(\n `createTable \"${op.table.name}\" inverts to dropTable. No data is preserved.`\n );\n return [{ type: \"dropTable\", tableName: op.table.name }];\n\n case \"dropTable\": {\n const table = findPrevTable(op.tableName);\n if (!table)\n return missingPrevious(warnings, `dropTable \"${op.tableName}\"`);\n warnings.push(\n `dropTable \"${op.tableName}\" rollback restores schema only.`\n );\n const foreignKeys = table.foreignKeys.filter(\n (fk) =>\n !keysRestoredByTheirOwnInverse.has(\n foreignKeyIdentity(table.name, fk.name)\n )\n );\n return [{ type: \"createTable\", table: { ...table, foreignKeys } }];\n }\n\n case \"renameTable\":\n return [{ type: \"renameTable\", from: op.to, to: op.from }];\n\n case \"addColumn\":\n return [\n {\n type: \"dropColumn\",\n tableName: op.tableName,\n columnName: op.column.name,\n },\n ];\n\n case \"dropColumn\": {\n const table = findPrevTable(op.tableName);\n const column = table?.columns.find((c) => c.name === op.columnName);\n if (!column)\n return missingPrevious(\n warnings,\n `dropColumn \"${op.tableName}.${op.columnName}\"`\n );\n warnings.push(\n `dropColumn \"${op.tableName}.${op.columnName}\" rollback restores column only.`\n );\n return [{ type: \"addColumn\", tableName: op.tableName, column }];\n }\n\n case \"renameColumn\":\n return [\n {\n type: \"renameColumn\",\n tableName: op.tableName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"alterColumn\":\n return [\n {\n type: \"alterColumn\",\n tableName: op.tableName,\n columnName: op.columnName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"createIndex\":\n return [\n {\n type: \"dropIndex\",\n tableName: op.tableName,\n indexName: op.index.name,\n ...(op.index.raw ? { raw: true } : {}),\n },\n ];\n\n case \"dropIndex\": {\n // A materialized view holds indexes too; renames never reach its name.\n const index = (\n findPrevTable(op.tableName) ??\n previousSnapshot.views?.find((view) => view.name === op.tableName)\n )?.indexes?.find((i) => i.name === op.indexName);\n if (!index)\n return missingPrevious(\n warnings,\n `dropIndex \"${op.indexName}\" on \"${op.tableName}\"`\n );\n return [{ type: \"createIndex\", tableName: op.tableName, index }];\n }\n\n case \"addForeignKey\":\n return [\n { type: \"dropForeignKey\", tableName: op.tableName, fkName: op.fk.name },\n ];\n\n case \"dropForeignKey\": {\n const table = findPrevTable(op.tableName);\n const fk = table?.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk)\n return missingPrevious(\n warnings,\n `dropForeignKey \"${op.fkName}\" on \"${op.tableName}\"`\n );\n return [{ type: \"addForeignKey\", tableName: op.tableName, fk }];\n }\n\n case \"addUniqueConstraint\":\n return [\n {\n type: \"dropUniqueConstraint\",\n tableName: op.tableName,\n constraintName: op.constraint.name,\n },\n ];\n\n case \"dropUniqueConstraint\": {\n const table = findPrevTable(op.tableName);\n const constraint = table?.uniqueConstraints.find(\n (u) => u.name === op.constraintName\n );\n if (!constraint)\n return missingPrevious(\n warnings,\n `dropUniqueConstraint \"${op.constraintName}\" on \"${op.tableName}\"`\n );\n return [\n { type: \"addUniqueConstraint\", tableName: op.tableName, constraint },\n ];\n }\n\n case \"addPrimaryKey\":\n return [\n {\n type: \"dropPrimaryKey\",\n tableName: op.tableName,\n constraintName: primaryKeyName(op.tableName, op.primaryKey.name),\n },\n ];\n\n case \"dropPrimaryKey\": {\n const table = findPrevTable(op.tableName);\n if (!table?.primaryKey)\n return missingPrevious(warnings, `dropPrimaryKey on \"${op.tableName}\"`);\n return [\n {\n type: \"addPrimaryKey\",\n tableName: op.tableName,\n primaryKey: table.primaryKey,\n },\n ];\n }\n\n case \"createView\":\n return [\n {\n type: \"dropView\",\n viewName: op.view.name,\n ...(op.view.materialized ? { materialized: true } : {}),\n ...(op.view.auto ? { auto: op.view.auto } : {}),\n },\n ];\n\n case \"dropView\": {\n const view = previousSnapshot.views?.find(\n (item) => item.name === op.viewName\n );\n if (!view) return missingPrevious(warnings, `dropView \"${op.viewName}\"`);\n return [{ type: \"createView\", view }];\n }\n\n case \"createEnum\":\n return [{ type: \"dropEnum\", enumName: op.enumDef.name }];\n\n case \"dropEnum\": {\n const enumDef = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!enumDef)\n return missingPrevious(warnings, `dropEnum \"${op.enumName}\"`);\n return [{ type: \"createEnum\", enumDef }];\n }\n\n case \"alterEnum\": {\n const prevEnum = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!prevEnum)\n return missingPrevious(warnings, `alterEnum \"${op.enumName}\"`);\n if (op.removeValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" removed [${op.removeValues.join(\", \")}]: rollback restores values only.`\n );\n }\n if (op.addValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" rollback removes [${op.addValues.join(\", \")}]: remap rows manually.`\n );\n }\n return [\n {\n type: \"alterEnum\",\n enumName: op.enumName,\n addValues: op.removeValues,\n removeValues: op.addValues,\n newValues: prevEnum.values,\n dependentColumns: op.dependentColumns,\n },\n ];\n }\n\n default:\n warnings.push(\"Cannot invert an unknown generated operation.\");\n return null;\n }\n}\n","/**\n * Exact SQL framing for Migration V1.\n *\n * The blob is the human review artifact. Execution slices UTF-8 byte ranges.\n * There is no delimiter parser, breakpoint marker, or comment search.\n */\n\nimport { decodeUtf8, type Sha256, utf8Bytes } from \"./identity\";\nimport { encodeSqlBlob } from \"./v1-parse\";\nimport { corrupt, refuse } from \"./v1-parse-shared\";\nimport type { MigrationDispatchV1, MigrationSqlRangeV1 } from \"./v1-types\";\n\nconst DISPLAY_SEPARATOR = utf8Bytes(\"\\n\\n\");\n\nexport function encodeSqlText(text: string): Uint8Array {\n if (text.includes(\"\\r\")) refuse(\"SQL refuses CR\");\n if (text.startsWith(\"\\uFEFF\")) refuse(\"SQL refuses BOM\");\n return utf8Bytes(text);\n}\n\nexport function composeSqlBlob(fragments: readonly string[]): {\n bytes: Uint8Array;\n ranges: MigrationSqlRangeV1[];\n sqlHash: Sha256;\n} {\n const encoded = fragments.map(encodeSqlText);\n let total = 0;\n for (let i = 0; i < encoded.length; i++) {\n if (i > 0) total += DISPLAY_SEPARATOR.length;\n total += encoded[i]!.length;\n }\n const bytes = new Uint8Array(total);\n const ranges: MigrationSqlRangeV1[] = [];\n let offset = 0;\n for (let i = 0; i < encoded.length; i++) {\n if (i > 0) {\n bytes.set(DISPLAY_SEPARATOR, offset);\n offset += DISPLAY_SEPARATOR.length;\n }\n const fragment = encoded[i]!;\n bytes.set(fragment, offset);\n ranges.push({ dispatchId: \"\", offset, length: fragment.length });\n offset += fragment.length;\n }\n return { bytes, sqlHash: encodeSqlBlob(bytes), ranges };\n}\n\nexport function validateSqlRanges(\n bytes: Uint8Array,\n dispatches: readonly MigrationDispatchV1[]\n): void {\n if (\n bytes.length >= 3 &&\n bytes[0] === 0xef &&\n bytes[1] === 0xbb &&\n bytes[2] === 0xbf\n )\n refuse(\"SQL refuses BOM\");\n if (bytes.includes(0x0d)) refuse(\"SQL refuses CR\");\n try {\n decodeUtf8(bytes);\n } catch {\n refuse(\"SQL must be valid UTF-8\");\n }\n const sqlHash = encodeSqlBlob(bytes);\n const unique: MigrationDispatchV1[] = [];\n const seen = new Set<string>();\n for (const dispatch of dispatches) {\n if (seen.has(dispatch.dispatchId)) continue;\n seen.add(dispatch.dispatchId);\n unique.push(dispatch);\n }\n const ordered = unique.sort(\n (left, right) => left.offset - right.offset || left.length - right.length\n );\n let previousEnd = 0;\n for (let index = 0; index < ordered.length; index++) {\n const dispatch = ordered[index]!;\n if (dispatch.sqlHash !== sqlHash) corrupt(\"Dispatch sqlHash mismatch\");\n if (\n !(\n Number.isSafeInteger(dispatch.offset) &&\n Number.isSafeInteger(dispatch.length)\n ) ||\n dispatch.offset < 0 ||\n dispatch.length < 0\n )\n refuse(\"SQL ranges invalid\");\n if (dispatch.offset + dispatch.length > bytes.length)\n refuse(\"SQL range exceeds blob\");\n if (index === 0) {\n if (dispatch.offset !== 0) refuse(\"SQL ranges must start at 0\");\n } else {\n const expectedOffset = previousEnd + DISPLAY_SEPARATOR.length;\n if (dispatch.offset !== expectedOffset)\n refuse(\n dispatch.offset < expectedOffset\n ? \"SQL ranges overlap\"\n : \"SQL ranges have gap\"\n );\n if (bytes[previousEnd] !== 0x0a || bytes[previousEnd + 1] !== 0x0a)\n refuse(\"SQL range separator must be LF+LF\");\n }\n previousEnd = dispatch.offset + dispatch.length;\n }\n if (ordered.length === 0) {\n if (bytes.length === 0) return;\n refuse(\"Empty-dispatch SQL blob not empty\");\n }\n if (previousEnd === bytes.length) return;\n if (previousEnd + 1 === bytes.length && bytes[previousEnd] === 0x0a) return;\n refuse(\"SQL blob has trailing bytes\");\n}\n\nexport function sliceDispatch(\n bytes: Uint8Array,\n dispatch: MigrationDispatchV1\n): string {\n return decodeUtf8(\n bytes.subarray(dispatch.offset, dispatch.offset + dispatch.length)\n );\n}\n\nconst MYSQL_DELIMITER = /^[ \\t]*DELIMITER\\s/im;\n\nexport function refuseMysqlDelimiter(text: string): void {\n if (MYSQL_DELIMITER.test(text)) refuse(\"MySQL DELIMITER unsupported\");\n}\n","/**\n * The ONE lexical classifier for migration-artifact execution safety.\n *\n * VibORM opens an enclosing boundary around every artifact it executes: an\n * apply/down/reset transaction on PostgreSQL, and a session lock on both\n * PostgreSQL and MySQL. This module refuses the DIRECT statements that would\n * end or reframe it — a `COMMIT` inside an artifact ends the rollback scope\n * VibORM promised, and a `RELEASE_LOCK`/`pg_advisory_unlock` inside one frees\n * the lock that is excluding every other migration command (§3.5).\n *\n * It refuses direct lexical controls and is NOT a sandbox for procedural or\n * dynamic SQL. That distinction is the module's contract, not a caveat on it.\n * Manual migration SQL is trusted last-mile authority: its author owns what it\n * does, this included. A dollar-quoted body is DATA to this scan — it has to\n * be, or every ordinary `CREATE FUNCTION` is refused — and the same bytes are a\n * statement to the server, so `DO $$ BEGIN PERFORM pg_advisory_unlock_all();\n * END $$` frees the migration lock while the command holds it. A pre-existing\n * safe-named function, a function the artifact creates, and `EXECUTE` over a\n * built string are the same escape by another route. It is executed rather than\n * asserted: `tests/unit/migrations/pinned-migration-session.core.test.ts` runs\n * that exact artifact through `apply()` on a real PostgreSQL and pins the lock\n * gone. Do not answer a procedural escape with another spelling here — the\n * enumeration does not close, and every addition costs valid author SQL.\n *\n * What the refusals do buy is the ACCIDENT and the audit: an author who typed a\n * `COMMIT` or a `pg_advisory_unlock(...)` straight into an artifact learns\n * before any of it runs, and a deliberate escape has to be WRITTEN as one, in\n * the artifact, where a reviewer sees it. The deliberate case is answered\n * afterwards instead, by the release proof in `pinned-session.ts`: a lock the\n * command acquired and no longer holds fails that command loudly and discards\n * the session, rather than letting it report a migration that ran outside the\n * boundary it published.\n *\n * The scanner is comment- and string-safe, which is the whole reason this is a\n * classifier rather than a regular expression: `-- COMMIT`, `'COMMIT'`, a\n * column named `\"commit\"`, and a dollar-quoted body that merely mentions\n * `pg_advisory_unlock` are all valid SQL and must stay valid. Only executable\n * tokens are classified.\n *\n * Executable is not enough on its own, because a spelling is not a role. A\n * table named `pg_advisory_notes`, a column named `release_lock`, and MySQL's\n * `@autocommit` user variable are executable tokens that call nothing and set\n * nothing, and refusing them refused valid author SQL over a resemblance. So\n * every scanned word carries the role its POSITION gives it, and the lock\n * refusals key on a call — one owner deciding it for bare and quoted\n * identifiers alike.\n *\n * Comment- and string-safety is DIALECT-SPECIFIC, so the scan takes the dialect\n * rather than reading one lexical grammar into both servers. Every arm below\n * that branches exists because the two servers disagree about what is data:\n * MySQL's `#` line comments and its `--` whitespace rule, its executable\n * `/*!…` comments whose contents the server RUNS, its backslash escapes inside\n * string literals, PostgreSQL's `E'…'` escape strings, and PostgreSQL's nested\n * block comments. Reading one server's grammar on the other either blinds the\n * scanner to a real statement or refuses an artifact that is entirely a\n * comment.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationTarget } from \"./types\";\n\n/**\n * Statement-leading PHRASES that open, close, or reframe a transaction.\n *\n * The test is on the LEADING word because that is what makes the word a\n * statement rather than a name: `END` opens nothing in `CREATE TABLE end_state`,\n * and `RELEASE` is only `RELEASE SAVEPOINT` at the start of a statement.\n *\n * `PREPARE TRANSACTION` is the entry that needs a second word, and it needs it\n * in both directions. It DETACHES the running transaction from this session for\n * a later `COMMIT PREPARED`, so where the server allows it at all\n * (`max_prepared_transactions > 0`) the entry's DDL is left unresolved while\n * the tracking write that records it lands in the autocommit that follows. And\n * `PREPARE plan AS SELECT …` begins with the same word while controlling\n * nothing, so refusing the leader alone would ban ordinary author SQL. The\n * phrase is the unit of the test; `PREPARE` alone is not an entry. Its two\n * siblings need no entry of their own — `COMMIT PREPARED` and\n * `ROLLBACK PREPARED` already lead with a refused word.\n */\nconst wordSet = (words: string) => new Set(words.split(\",\"));\n\nconst TRANSACTION_LEADERS: Record<ClassifiedDialect, ReadonlySet<string>> = {\n postgresql: wordSet(\n \"ABORT,BEGIN,COMMIT,END,PREPARE TRANSACTION,RELEASE,ROLLBACK,SAVEPOINT,START\"\n ),\n mysql: wordSet(\n \"BEGIN,COMMIT,LOCK,RELEASE,ROLLBACK,SAVEPOINT,START,UNLOCK,XA\"\n ),\n sqlite: wordSet(\"BEGIN,COMMIT,END,RELEASE,ROLLBACK,SAVEPOINT\"),\n};\n\nconst POSTGRES_ADVISORY_PREFIXES = [\"PG_ADVISORY\", \"PG_TRY_ADVISORY\"];\n\nconst OBJECT_NAME_KEYWORDS = wordSet(\n \"AGGREGATE,EXISTS,FUNCTION,PROCEDURE,TABLE,VIEW\"\n);\n\nconst MYSQL_LOCK_FUNCTIONS = wordSet(\n \"GET_LOCK,IS_FREE_LOCK,IS_USED_LOCK,RELEASE_ALL_LOCKS,RELEASE_LOCK\"\n);\n\n/** The tag body of a PostgreSQL dollar quote: `$tag$`. */\nconst DOLLAR_TAG_PART = /[A-Za-z0-9_]/;\nconst WORD_START = /[A-Za-z_]/;\nconst WORD_PART = /\\w/;\nconst WHITESPACE = /\\s/;\n/** The optional server-version prefix of a MySQL executable comment. */\nconst VERSION_DIGIT = /[0-9]/;\n\n/**\n * MySQL's SYSTEM-variable sigil, which the bare spelling of the same name also\n * reaches: `SET @@autocommit = 0` and `SET autocommit = 0` change one setting,\n * so the sigil folds away and both meet the same refusal.\n *\n * ONE `@` does not fold. `@autocommit` is a user variable — a slot with a name\n * that happens to read like the setting, which no server behavior consults —\n * and folding it refused `SET @autocommit = 0`, valid MySQL, as a commit-\n * boundary change. `SELECT @release_lock` was refused as a lock call the same\n * way.\n */\nconst SYSTEM_VARIABLE_SIGIL = /^@@/;\n\n/**\n * The dialects this classifier reads.\n */\nexport type ClassifiedDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\n/**\n * The characters that make a bare word, per dialect.\n *\n * `@` is the whole difference and it is not cosmetic. In MySQL the sigil is\n * part of the identifier — `@name` and `@@name` are two different names, and\n * neither is the bare one. PostgreSQL has no variable sigil at all: `@` is an\n * operator character there, so joining it to the word behind it would read\n * `SELECT @pg_advisory_unlock(1)` as one name the advisory prefix no longer\n * matches, hiding a call the server still makes.\n */\nconst WORD_CHARACTERS: Record<\n ClassifiedDialect,\n { readonly start: RegExp; readonly part: RegExp }\n> = {\n mysql: { start: /[A-Za-z_@]/, part: /[A-Za-z0-9_$@]/ },\n postgresql: { start: /[A-Za-z_]/, part: /[A-Za-z0-9_$]/ },\n sqlite: { start: /[A-Za-z_]/, part: /[A-Za-z0-9_$]/ },\n};\n\n/**\n * One executable word and the syntactic role its POSITION gives it.\n *\n * The role is the point. A lock-function refusal that reads spelling alone\n * refuses `CREATE TABLE get_lock (id INT)` and `CREATE TABLE t (release_lock\n * INT)`, which call nothing and are the author's to keep. `calls` is decided\n * once, by {@link callsArguments}, for bare and quoted identifiers alike.\n */\ntype ScannedWord = readonly [text: string, calls: boolean];\n\ntype PrecedingToken = \"word\" | \"qualifier\" | \"other\";\n\nexport function readExecutableStatements(\n sql: string,\n dialect: ClassifiedDialect\n): string[][] {\n return scanStatements(sql, dialect).map((words) =>\n words.map((word) => word[0])\n );\n}\n\nfunction skipCommentAt(\n sql: string,\n index: number,\n dialect: ClassifiedDialect,\n openExecutable: boolean\n): number {\n const char = sql.charAt(index);\n const next = sql.charAt(index + 1);\n if (char === \"-\" && next === \"-\" && opensLineComment(sql, index, dialect)) {\n return skipLine(sql, index);\n }\n if (dialect === \"mysql\" && char === \"#\") {\n return skipLine(sql, index);\n }\n if (char === \"/\" && next === \"*\") {\n return openExecutable && dialect === \"mysql\" && sql[index + 2] === \"!\"\n ? openExecutableComment(sql, index)\n : skipBlockComment(sql, index, dialect);\n }\n return -1;\n}\n\nfunction scanStatements(\n sql: string,\n dialect: ClassifiedDialect\n): ScannedWord[][] {\n const characters = WORD_CHARACTERS[dialect];\n const statements: ScannedWord[][] = [];\n let words: ScannedWord[] = [];\n let index = 0;\n let preceding: PrecedingToken = \"other\";\n let previousWord: string | undefined;\n let governing: string | undefined;\n let atomic = 0;\n\n while (index < sql.length) {\n const commentEnd = skipCommentAt(sql, index, dialect, true);\n if (commentEnd >= 0) {\n index = commentEnd;\n continue;\n }\n const char = sql.charAt(index);\n if (char === \"'\" || char === '\"' || char === \"`\") {\n const quoteEnd = skipQuoted(\n sql,\n index,\n char,\n escapesWithBackslash(dialect, char)\n );\n governing = governingWord(preceding, previousWord, governing);\n const name = readQuotedIdentifier(sql, index, quoteEnd, char, dialect);\n if (name !== null && callsArguments(sql, quoteEnd, governing, dialect)) {\n words.push([name, true]);\n }\n preceding = \"other\";\n index = quoteEnd;\n continue;\n }\n if (dialect === \"sqlite\" && char === \"[\") {\n index = skipBracketQuoted(sql, index);\n preceding = \"other\";\n continue;\n }\n if (dialect === \"postgresql\" && char === \"$\") {\n const dollarEnd = skipDollarQuoted(sql, index);\n if (dollarEnd !== null) {\n index = dollarEnd;\n preceding = \"other\";\n continue;\n }\n }\n if (char === \";\") {\n if (words.length > 0 && atomic === 0) {\n statements.push(words);\n words = [];\n }\n index += 1;\n preceding = \"other\";\n continue;\n }\n if (characters.start.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && characters.part.test(sql.charAt(index))) {\n index += 1;\n }\n const text = sql\n .slice(start, index)\n .toUpperCase()\n .replace(SYSTEM_VARIABLE_SIGIL, \"\");\n if (dialect === \"postgresql\" && text === \"E\" && sql[index] === \"'\") {\n index = skipQuoted(sql, index, \"'\", true);\n preceding = \"other\";\n continue;\n }\n governing = governingWord(preceding, previousWord, governing);\n words.push([text, callsArguments(sql, index, governing, dialect)]);\n if (dialect === \"postgresql\") {\n if (atomic === 0 && text === \"ATOMIC\" && previousWord === \"BEGIN\")\n atomic = 1;\n else if (atomic > 0 && text === \"CASE\") atomic += 1;\n else if (atomic > 0 && text === \"END\") atomic -= 1;\n }\n previousWord = text;\n preceding = \"word\";\n continue;\n }\n if (char.trim() !== \"\") {\n preceding = char === \".\" ? \"qualifier\" : \"other\";\n }\n index += 1;\n }\n\n if (words.length > 0) {\n statements.push(words);\n }\n return statements;\n}\n\n/**\n * The word that governs the identifier position at the cursor, or undefined\n * when no word reaches it.\n *\n * Directly in front of an identifier, a word governs it: the `TABLE` of\n * `CREATE TABLE get_lock (…)` says that name is being defined. Across a `.`\n * the governor is inherited rather than replaced, so a qualified name is\n * decided by whatever opened the chain — `CREATE TABLE alpha.pg_advisory_notes\n * (…)` defines, `SELECT pg_catalog.\"pg_advisory_unlock_all\"()` calls.\n *\n * Any other punctuation ends the reach, and that is the half that keeps the\n * exemption honest: a comma away from a column named `view`,\n * `SELECT view, \"pg_advisory_unlock\"(1)` is a call, and reading the previous\n * WORD alone admitted it as a definition.\n */\nfunction governingWord(\n preceding: PrecedingToken,\n previousWord: string | undefined,\n chainGovernor: string | undefined\n): string | undefined {\n if (preceding === \"word\") {\n return previousWord;\n }\n if (preceding === \"qualifier\") {\n return chainGovernor;\n }\n return undefined;\n}\n\n/**\n * The unquoted-equivalent spelling of a quoted identifier, or null when the\n * quoted run is a literal or a spelling no built-in answers to.\n *\n * PostgreSQL is the only dialect that reaches a decision here. MySQL's `\"` is a\n * STRING quote, so the same bytes are data there, and its backtick-quoted names\n * resolve to stored functions rather than to the built-in named-lock family —\n * `` SELECT `release_lock`('k') `` does not run MySQL's `RELEASE_LOCK`.\n *\n * A quoted identifier is CASE-SENSITIVE, so only the folded spelling names the\n * built-in: `\"PG_ADVISORY_UNLOCK_ALL\"` is a function PostgreSQL does not have,\n * and refusing it would ban a name over a call that cannot happen. The name is\n * returned in that folded (lowercase) spelling, which is also what keeps it out\n * of every keyword test in this module — bare words arrive uppercased.\n */\nfunction readQuotedIdentifier(\n sql: string,\n start: number,\n end: number,\n quote: string,\n dialect: ClassifiedDialect\n): string | null {\n if (dialect !== \"postgresql\" || quote !== '\"') {\n return null;\n }\n // An UNTERMINATED quote ran to the end of the input; nothing follows it, so\n // nothing calls it.\n if (end - start < 2 || sql[end - 1] !== '\"') {\n return null;\n }\n const name = sql.slice(start + 1, end - 1).replaceAll('\"\"', '\"');\n return name === name.toLowerCase() ? name : null;\n}\n\n/**\n * The ONE call-position owner: whether the identifier ending at `end` is CALLED\n * where it stands.\n *\n * Two halves, and both are needed. A governing keyword makes the identifier the\n * name of an object being defined, `(` behind it or not — that is what keeps\n * `CREATE TABLE pg_advisory_notes (id INT)` and\n * `CREATE TABLE \"pg_advisory_unlock_all\" (id INT)` valid, since both open a\n * column list. Otherwise an argument list has to actually open, modulo what\n * sits between a function's name and its `(`: whitespace is the obvious case\n * and comments are the one that matters, because\n * `pg_catalog.\"pg_advisory_unlock_all\"/**\\/()` is one call to the server and a\n * lookahead that stopped at the first non-space would read it as a name.\n *\n * A qualifier is not read: `myschema.\"pg_advisory_unlock\"()` is a call too,\n * because a `search_path` this classifier cannot see decides what that name\n * resolves to. Whitespace before the `(` is admitted on MySQL as well, where\n * only `IGNORE_SPACE` makes the server accept it — refusing a call the server\n * might make is the direction this classifier can afford to be wrong in.\n */\nfunction callsArguments(\n sql: string,\n end: number,\n governing: string | undefined,\n dialect: ClassifiedDialect\n): boolean {\n if (governing !== undefined && OBJECT_NAME_KEYWORDS.has(governing)) {\n return false;\n }\n let cursor = end;\n while (cursor < sql.length) {\n const commentEnd = skipCommentAt(sql, cursor, dialect, false);\n if (commentEnd >= 0) {\n cursor = commentEnd;\n continue;\n }\n const char = sql.charAt(cursor);\n if (char.trim() !== \"\") return char === \"(\";\n cursor += 1;\n }\n return false;\n}\n\n/**\n * Whether the `--` at `start` opens a line comment.\n *\n * PostgreSQL's always does. MySQL's requires whitespace (or a control\n * character, or end of input) after the second dash, so\n * `SELECT 1--RELEASE_LOCK('viborm_migration_…')` is arithmetic over a REAL\n * function call there rather than a comment. Reading it as a comment hides\n * exactly the statement this classifier exists to refuse.\n */\nfunction opensLineComment(\n sql: string,\n start: number,\n dialect: ClassifiedDialect\n): boolean {\n if (dialect !== \"mysql\") {\n return true;\n }\n const after = sql[start + 2];\n if (after === undefined) {\n return true;\n }\n return after.trim() === \"\" || after.charCodeAt(0) < 0x20;\n}\n\n/** Past SQLite's square-bracket identifier quote. */\nfunction skipBracketQuoted(sql: string, start: number): number {\n const end = sql.indexOf(\"]\", start + 1);\n return end < 0 ? sql.length : end + 1;\n}\n\n/** Past a line comment, including its newline. */\nfunction skipLine(sql: string, start: number): number {\n const lineEnd = sql.indexOf(\"\\n\", start);\n return lineEnd < 0 ? sql.length : lineEnd + 1;\n}\n\n/**\n * Past the OPENING of a MySQL executable comment (`/*!`, optionally followed by\n * a server-version prefix), leaving its contents to be scanned as statements.\n *\n * MySQL RUNS what is inside these — that is what they are for — so skipping\n * them the way an ordinary comment is skipped admits\n * `/*!50000 DO RELEASE_LOCK('viborm_migration_…')`, which frees the lock the\n * running command holds, and `/*!40101 SET AUTOCOMMIT=0`, which reframes the\n * commit boundary of everything after it. The closing delimiter needs no arm of\n * its own: neither of its characters starts a word.\n */\nfunction openExecutableComment(sql: string, start: number): number {\n let cursor = start + 3;\n while (cursor < sql.length && VERSION_DIGIT.test(sql.charAt(cursor))) {\n cursor += 1;\n }\n return cursor;\n}\n\n/**\n * Past a block comment.\n *\n * PostgreSQL NESTS them, so an outer comment holding a complete inner one is\n * entirely a comment there; stopping at the first close would leave the outer\n * comment's tail scanned as SQL and refuse a valid artifact over a `COMMIT` no\n * server ever sees. MySQL does not nest, so its depth never rises and it stops\n * at the first close — which is also where the server stops.\n */\nfunction skipBlockComment(\n sql: string,\n start: number,\n dialect: ClassifiedDialect\n): number {\n let cursor = start + 2;\n let depth = 1;\n while (cursor < sql.length) {\n if (sql[cursor] === \"*\" && sql[cursor + 1] === \"/\") {\n depth -= 1;\n cursor += 2;\n if (depth === 0) {\n return cursor;\n }\n continue;\n }\n if (\n dialect === \"postgresql\" &&\n sql[cursor] === \"/\" &&\n sql[cursor + 1] === \"*\"\n ) {\n depth += 1;\n cursor += 2;\n continue;\n }\n cursor += 1;\n }\n return sql.length;\n}\n\n/**\n * Whether a backslash escapes the next character inside this quote.\n *\n * MySQL's default mode treats `\\` as an escape inside both string quotes, so\n * `'a\\'b'` is ONE literal there; its backtick identifiers take no escapes.\n * PostgreSQL's strings are standard-conforming, so a backslash is an ordinary\n * character in `'…'` and `\"…\"` — its one escape-bearing form, `E'…'`, is\n * recognised at the `E` in the scan above.\n */\nfunction escapesWithBackslash(\n dialect: ClassifiedDialect,\n quote: string\n): boolean {\n return dialect === \"mysql\" && quote !== \"`\";\n}\n\n/**\n * Past a quoted run, honoring the doubling escape every admitted dialect uses\n * (`''`, `\"\"`, ` `` `) and, where the dialect has them, backslash escapes. An\n * unterminated quote consumes the rest of the statement, which is what a\n * database would also do with it.\n */\nfunction skipQuoted(\n sql: string,\n start: number,\n quote: string,\n backslashEscapes: boolean\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] !== quote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return sql.length;\n}\n\n/**\n * Past a PostgreSQL dollar-quoted body (`$$…$$`, `$tag$…$tag$`), or null when\n * this `$` does not open one.\n *\n * Function bodies are the common shape of a hand-written PostgreSQL artifact,\n * and their contents are a string, not statements. Reading them as statements\n * would refuse a perfectly ordinary `CREATE FUNCTION` whose body happens to\n * contain `COMMIT` or `BEGIN`.\n */\nfunction skipDollarQuoted(sql: string, start: number): number | null {\n let cursor = start + 1;\n while (cursor < sql.length && DOLLAR_TAG_PART.test(sql.charAt(cursor))) {\n cursor += 1;\n }\n if (sql[cursor] !== \"$\") {\n return null;\n }\n const tag = sql.slice(start, cursor + 1);\n const bodyEnd = sql.indexOf(tag, cursor + 1);\n return bodyEnd < 0 ? sql.length : bodyEnd + tag.length;\n}\n\n/** The refusal a classified statement raises, naming its artifact and cause. */\nfunction refuse(\n artifact: string,\n statement: string,\n reason: string\n): MigrationError {\n return new MigrationError(\n `Migration \"${artifact}\" refused (${reason}): \"${statement.trim().slice(0, 80)}\".`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { migrationName: artifact } }\n );\n}\n\nconst SURREAL_QUOTES: Readonly<Record<string, string>> = {\n \"'\": \"'\",\n '\"': '\"',\n \"`\": \"`\",\n \"\\u27E8\": \"\\u27E9\",\n};\nconst SURREAL_TRANSACTION_WORDS = new Set([\"BEGIN\", \"COMMIT\", \"CANCEL\"]);\n\n/**\n * Refuses an artifact that DIRECTLY reframes the execution boundary.\n *\n * Runs BEFORE any of the artifact's effects, so a refusal leaves the estate\n * exactly as it was. SQLite has no advisory lock, but the migration runner\n * still owns its transaction and savepoint boundary.\n */\nexport function assertArtifactExecutionSafe(\n statements: readonly string[],\n dialect: MigrationTarget[\"dialect\"],\n artifact: string\n): void {\n if (dialect === \"surrealql\") {\n for (const chunk of statements) assertSurrealStatementSafe(chunk, artifact);\n return;\n }\n const sqlDialect = dialect as ClassifiedDialect;\n for (const chunk of statements) {\n const scanned = scanStatements(chunk, sqlDialect);\n if (dialect === \"sqlite\" && isSqliteTrigger(scanned[0])) {\n continue;\n }\n for (const words of scanned) {\n classifyOne(words, chunk, sqlDialect, artifact);\n }\n }\n}\n\n/**\n * SurrealQL's own lexical grammar, kept apart from SQL's: a comment is `--`, `//`, `#`\n * or a block, a string or a name is quoted four ways, and a block is `{ … }`.\n * `visit` sees each bare word, uppercased, whether it opens its statement, and\n * how deep in brackets it stands; `end` sees each top-level `;`.\n */\nfunction scanSurreal(\n chunk: string,\n visit: (word: string, atStart: boolean, depth: number) => void,\n end: () => void = () => undefined\n): void {\n let depth = 0;\n let atStart = true;\n for (let index = 0; index < chunk.length; ) {\n const char = chunk.charAt(index);\n const two = chunk.slice(index, index + 2);\n if (two === \"--\" || two === \"//\" || char === \"#\") {\n const close = chunk.indexOf(\"\\n\", index);\n index = close < 0 ? chunk.length : close + 1;\n continue;\n }\n if (two === \"/*\") {\n const close = chunk.indexOf(\"*/\", index + 2);\n index = close < 0 ? chunk.length : close + 2;\n continue;\n }\n const closing = SURREAL_QUOTES[char];\n if (closing) {\n index += 1;\n while (index < chunk.length && chunk.charAt(index) !== closing)\n index += chunk.charAt(index) === \"\\\\\" ? 2 : 1;\n index += 1;\n atStart = false;\n continue;\n }\n if (char === \"(\" || char === \"[\" || char === \"{\") depth += 1;\n else if (char === \")\" || char === \"]\" || char === \"}\") depth -= 1;\n if (char === \";\" && depth === 0) {\n atStart = true;\n end();\n index += 1;\n continue;\n }\n if (WORD_START.test(char)) {\n let stop = index + 1;\n while (stop < chunk.length && WORD_PART.test(chunk.charAt(stop)))\n stop += 1;\n visit(chunk.slice(index, stop).toUpperCase(), atStart, depth);\n atStart = false;\n index = stop;\n continue;\n }\n if (!WHITESPACE.test(char)) atStart = false;\n index += 1;\n }\n}\n\n/** A transaction control at the top level would end the boundary the command opened. */\nfunction assertSurrealStatementSafe(chunk: string, artifact: string): void {\n scanSurreal(chunk, (word, atStart, depth) => {\n if (atStart && depth === 0 && SURREAL_TRANSACTION_WORDS.has(word))\n throw refuse(artifact, chunk, `transaction-control \"${word}\"`);\n });\n}\n\n/**\n * The executable bare words of a SurrealQL chunk, grouped per top-level\n * statement: what {@link readExecutableStatements} is for SQL. A quoted name,\n * a string and a comment hold none.\n */\nexport function readSurrealStatements(chunk: string): string[][] {\n const statements: string[][] = [[]];\n scanSurreal(\n chunk,\n (word) => statements.at(-1)!.push(word),\n () => statements.push([])\n );\n return statements.filter((words) => words.length > 0);\n}\n\n/**\n * A SQLite trigger body uses `BEGIN … END` as grammar, not transaction control.\n * Stock SQLite execution accepts one prepared statement per dispatch, so the\n * whole trigger is the provider statement and its body controls stay inside it.\n */\nfunction isSqliteTrigger(first: readonly ScannedWord[] | undefined): boolean {\n if (first?.[0]?.[0] !== \"CREATE\") return false;\n const second = first[1]?.[0];\n return (\n second === \"TRIGGER\" ||\n ((second === \"TEMP\" || second === \"TEMPORARY\") &&\n first[2]?.[0] === \"TRIGGER\")\n );\n}\n\nfunction leadingTransactionCommand(\n words: readonly ScannedWord[],\n leaders: ReadonlySet<string>\n): string | undefined {\n const first = words[0]?.[0];\n const second = words[1]?.[0];\n const pair = second === undefined ? undefined : `${first} ${second}`;\n if (pair !== undefined && leaders.has(pair)) return pair;\n return first !== undefined && leaders.has(first) ? first : undefined;\n}\n\n/** Classifies ONE statement's executable words. */\nfunction classifyOne(\n words: readonly ScannedWord[],\n statement: string,\n dialect: ClassifiedDialect,\n artifact: string\n): void {\n const leader = words[0]![0];\n const control = leadingTransactionCommand(\n words,\n TRANSACTION_LEADERS[dialect]\n );\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `${dialect === \"mysql\" ? \"transaction/lock statement\" : \"transaction-control\"} \"${control}\"`\n );\n }\n if (dialect === \"postgresql\") {\n const advisory = words.find(\n ([text, calls]) =>\n calls &&\n POSTGRES_ADVISORY_PREFIXES.some((prefix) =>\n text.toUpperCase().startsWith(prefix)\n )\n );\n if (advisory !== undefined) {\n throw refuse(\n artifact,\n statement,\n `advisory-lock call \"${advisory[0].toLowerCase()}\"`\n );\n }\n return;\n }\n if (dialect !== \"mysql\") return;\n if (leader === \"SET\" && words.some(([text]) => text === \"AUTOCOMMIT\")) {\n throw refuse(artifact, statement, \"SET autocommit\");\n }\n const named = words.find(\n ([text, calls]) => calls && MYSQL_LOCK_FUNCTIONS.has(text)\n );\n if (named !== undefined) {\n throw refuse(\n artifact,\n statement,\n `named-lock call \"${named[0].toLowerCase()}\"`\n );\n }\n}\n\n/**\n * Whether a PostgreSQL migration edge must commit before the next one runs.\n *\n * `ALTER TYPE ... ADD VALUE` cannot be used by a later statement of the\n * transaction that added it (55P04), so apply, rollback and reset end their\n * shared transaction after such an edge. Reset creates the type in its own\n * transaction, but only PostgreSQL 17 and later exempt such a type's values.\n *\n * The question is PostgreSQL's alone — no other dialect has the statement — so\n * the scan reads PostgreSQL's lexical grammar rather than taking a dialect its\n * callers would each have to answer for.\n */\nexport function needsEnumAdditionCommitBoundary(\n statements: readonly string[]\n): boolean {\n for (const chunk of statements) {\n for (const words of readExecutableStatements(chunk, \"postgresql\")) {\n if (\n words[0] === \"ALTER\" &&\n words[1] === \"TYPE\" &&\n words.includes(\"ADD\") &&\n words.includes(\"VALUE\")\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\nconst SCHEMA_CHANGES = wordSet(\"ALTER,COMMENT,CREATE,DROP\");\nconst UNPLANNED = wordSet(\"GRANT,SET,TRUNCATE\");\nconst OPAQUE = wordSet(\"CALL,DO,EXECUTE\");\n\nconst NAME_START = /[A-Za-z_]/;\nconst NAME_PART = /[A-Za-z0-9_$]/;\nconst NAME_UNSAFE = /[^A-Za-z0-9_$]/g;\nconst LEADING_WORDS = /^([A-Za-z_]+)(?:\\s+([A-Za-z_]+))?/;\nconst NAME = String.raw`(?:\"[^\"]*\"|[A-Za-z_][\\w$]*)`;\nconst QUALIFIED = String.raw`${NAME}(?:\\s*\\.\\s*${NAME}){0,2}`;\n/** A parenthesized run, three levels deep; the structural text has no literal. */\nconst GROUP = String.raw`\\((?:[^()]|\\((?:[^()]|\\([^()]*\\))*\\))*\\)`;\nconst LAST_NAME = new RegExp(`${NAME}$`);\nconst ALTER_TABLE = new RegExp(\n String.raw`^ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${QUALIFIED})\\s*\\*?\\s*([\\s\\S]*)$`,\n \"i\"\n);\nconst TABLE_PREFIX = String.raw`^CREATE\\s+(?:(?:GLOBAL|LOCAL|TEMP|TEMPORARY|UNLOGGED)\\s+)*`;\nconst CREATE_TABLE = new RegExp(\n String.raw`${TABLE_PREFIX}TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(${QUALIFIED})`,\n \"i\"\n);\n/**\n * `CREATE TABLE … AS`, `CREATE MATERIALIZED VIEW … AS` and `CREATE [OR\n * REPLACE] VIEW … AS` plan a query: a view's body resolves its names when the\n * view is created.\n */\nconst CREATE_AS =\n /^CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:(?:GLOBAL|LOCAL|TEMP|TEMPORARY|UNLOGGED|RECURSIVE)\\s+)*(?:TABLE|MATERIALIZED\\s+VIEW|VIEW)\\b[\\s\\S]*\\bAS\\s+(?:SELECT|WITH|TABLE|VALUES|EXECUTE)\\b/i;\nconst RENAME_TO = new RegExp(String.raw`^RENAME\\s+TO\\s+(${NAME})\\s*$`, \"i\");\n/**\n * The unregistered-relation refusal's actions (NK316): a type change, a\n * column rename, a column drop, a move to another schema.\n */\nconst UNREGISTERED_ACTION = new RegExp(\n String.raw`(?:^|,)\\s*(?:ALTER\\s+(?:COLUMN\\s+)?${NAME}\\s+(?:SET\\s+DATA\\s+)?TYPE\\b|RENAME\\s+(?:COLUMN\\s+)?(?!(?:TO|CONSTRAINT)\\b)${NAME}\\s+TO\\b|DROP\\s+(?:COLUMN\\s+)?(?!(?:CONSTRAINT|DEFAULT|NOT|IDENTITY|EXPRESSION)\\b)(?:IF\\s+EXISTS\\s+)?${NAME}|SET\\s+SCHEMA\\b)`,\n \"i\"\n);\n/**\n * The `ALTER TABLE` actions Neki's planner needs no commit for: what they\n * change is enforced where the row is written, never resolved where the\n * statement is planned (defaults, NOT NULL, CHECK and foreign keys, a\n * validated constraint). A relation created or dropped, an index or a\n * constraint's own included, is not one: a literal naming it resolves\n * against the committed schema (`to_regclass`, `::regclass`, measured stale).\n */\nconst SEEN_ACTION = String.raw`(?:ALTER\\s+(?:COLUMN\\s+)?${NAME}\\s+(?:SET\\s+DEFAULT\\s+(?:[^,()]|${GROUP})+|DROP\\s+DEFAULT|(?:SET|DROP)\\s+NOT\\s+NULL)|ADD\\s+(?:CONSTRAINT\\s+${NAME}\\s+)?(?:CHECK\\s*${GROUP}|FOREIGN\\s+KEY\\s*${GROUP}\\s*REFERENCES\\s+${QUALIFIED}(?:\\s*${GROUP})?)(?:\\s+[A-Za-z]+|\\s*${GROUP})*|VALIDATE\\s+CONSTRAINT\\s+${NAME})`;\nconst SEEN_ALTERATION = new RegExp(\n String.raw`^${SEEN_ACTION}(?:\\s*,\\s*${SEEN_ACTION})*\\s*$`,\n \"i\"\n);\nconst SEEN_STATEMENT = /^COMMENT\\b/i;\n\n/**\n * The PostgreSQL statements of `sql` as their structure alone: comments\n * dropped, every literal, dollar-quoted body and `BEGIN ATOMIC … END` body\n * emptied (`''`), and every quoted identifier spelled with characters that\n * open or close nothing, so a pattern over what is left reads clauses, never\n * data. Its only readers are {@link catalogCommitBoundaries}' patterns.\n */\nfunction structuralStatements(sql: string): string[] {\n const statements: string[] = [];\n let text = \"\";\n let index = 0;\n let previous = \"\";\n // The CASE … END depth inside an open `BEGIN ATOMIC` body, whose `;` end\n // its own statements, not this one.\n let body = 0;\n const emit = (part: string) => {\n if (body === 0) text += part;\n };\n const end = () => {\n if (text.trim() !== \"\") statements.push(text.trim());\n text = \"\";\n };\n while (index < sql.length) {\n const char = sql.charAt(index);\n const next = sql.charAt(index + 1);\n if (char === \"-\" && next === \"-\") {\n index = skipLine(sql, index);\n emit(\" \");\n } else if (char === \"/\" && next === \"*\") {\n index = skipBlockComment(sql, index, \"postgresql\");\n emit(\" \");\n } else if (char === \"'\") {\n index = skipQuoted(sql, index, \"'\", false);\n emit(\"''\");\n } else if (char === '\"') {\n const close = skipQuoted(sql, index, '\"', false);\n const name = sql.slice(index + 1, close - 1).replaceAll('\"\"', '\"');\n emit(\n `\"${name.replace(NAME_UNSAFE, (unsafe) => `_${unsafe.charCodeAt(0).toString(16)}_`)}\"`\n );\n index = close;\n } else if (char === \"$\" && skipDollarQuoted(sql, index) !== null) {\n index = skipDollarQuoted(sql, index)!;\n emit(\"''\");\n } else if (char === \";\") {\n if (body === 0) end();\n index += 1;\n } else if (NAME_START.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && NAME_PART.test(sql.charAt(index))) {\n index += 1;\n }\n const word = sql.slice(start, index);\n const upper = word.toUpperCase();\n // `E'…'`, the one PostgreSQL string a backslash escapes in.\n if (upper === \"E\" && sql[index] === \"'\") {\n index = skipQuoted(sql, index, \"'\", true);\n emit(\"''\");\n } else if (body > 0) {\n if (upper === \"CASE\") body += 1;\n if (upper === \"END\") body -= 1;\n if (body === 0) text += \"'' END\";\n } else {\n text += word;\n if (upper === \"ATOMIC\" && previous === \"BEGIN\") body = 1;\n }\n previous = upper;\n } else {\n emit(char);\n index += 1;\n }\n }\n end();\n return statements;\n}\n\n/** A relation as {@link structuralStatements} spells it, schema dropped: quoted as written, bare folded. */\nfunction relationName(qualified: string): string {\n const last = LAST_NAME.exec(qualified)?.[0] ?? qualified;\n return last.startsWith('\"') ? last.slice(1, -1) : last.toLowerCase();\n}\n\n/** One statement of a program: its position there and its leading words. */\nexport interface CatalogStatement {\n readonly position: number;\n readonly words: string;\n}\n\n/** What one Neki transaction changed since it began that a later statement may not see. */\nexport interface CatalogChanges {\n /** Its first change Neki plans later row statements without. */\n readonly unseen?: CatalogStatement;\n /** The relations it created or renamed, by name: Neki has not registered them (NK316). */\n readonly unregistered: ReadonlyMap<string, CatalogStatement>;\n}\n\n/** A statement that needs `change` committed before it runs on Neki. */\nexport interface CatalogHazard {\n /**\n * `rows`: a statement planned against the committed schema after a change\n * its planner does not see (`42P01`, `42703`, `42704`, `42883`, `22P02`, or\n * a silently stale `*` or column type); `columns`: a column type change,\n * rename or drop of a relation created or renamed in the same transaction\n * (`NK316`).\n */\n readonly kind: \"rows\" | \"columns\";\n readonly change: CatalogStatement;\n readonly statement: CatalogStatement;\n}\n\nexport const UNCHANGED_CATALOG: CatalogChanges = { unregistered: new Map() };\n\n/** One program entry read against `since`: its first hazard, and the changes after it. */\nfunction readCatalogChunk(\n chunk: string,\n position: number,\n since: CatalogChanges\n): { readonly hazard?: CatalogHazard; readonly changes: CatalogChanges } {\n let { unseen } = since;\n const unregistered = new Map(since.unregistered);\n let hazard: CatalogHazard | undefined;\n for (const text of structuralStatements(chunk)) {\n const [, first = \"\", second] = LEADING_WORDS.exec(text) ?? [];\n const leader = first.toUpperCase();\n const site = {\n position,\n words: [leader, second?.toUpperCase()].filter(Boolean).join(\" \"),\n };\n const schema = SCHEMA_CHANGES.has(leader);\n const plans = !(schema || UNPLANNED.has(leader)) || CREATE_AS.test(text);\n const table = leader === \"ALTER\" ? ALTER_TABLE.exec(text) : null;\n const created = table ? undefined : CREATE_TABLE.exec(text)?.[1];\n const relation = table ? relationName(table[1]!) : undefined;\n const clause = table?.[2] ?? \"\";\n const registering = relation && unregistered.get(relation);\n if (hazard === undefined && plans && unseen) {\n hazard = {\n kind: \"rows\",\n change: unseen,\n statement: { position, words: leader },\n };\n } else if (\n hazard === undefined &&\n registering &&\n UNREGISTERED_ACTION.test(clause)\n ) {\n hazard = { kind: \"columns\", change: registering, statement: site };\n }\n const seen =\n SEEN_STATEMENT.test(text) ||\n (table !== null && SEEN_ALTERATION.test(clause));\n if (unseen === undefined && (schema ? !seen : OPAQUE.has(leader))) {\n unseen = site;\n }\n const renamed = RENAME_TO.exec(clause)?.[1];\n if (created) unregistered.set(relationName(created), site);\n if (renamed) unregistered.set(relationName(renamed), site);\n }\n return { hazard, changes: { unseen, unregistered } };\n}\n\n/**\n * Where PlanetScale's Neki needs a commit inside a PostgreSQL transaction\n * that runs `chunks` in order, its changes since its last commit `since`.\n *\n * Neki's router plans a statement against the schema committed before its\n * transaction, and only the server it routes to sees the transaction's own\n * changes. Measured on Neki's PostgreSQL 18.6 (2026-10-13), and held by\n * `tests/providers/hosted/neki-migrations.test.ts` and the simulation in\n * `tests/unit/migrations/postgres-neki-apply.test.ts`: a statement that\n * resolves a name, a `*`, a column's type, an enum label or an ON CONFLICT\n * target the transaction changed fails there, or reads the old schema without\n * an error; a schema statement sees the transaction, except that a relation it\n * created or renamed has no column it can retype, rename or drop, and cannot\n * move to another schema (`NK316`), and that a statement creating a table or a\n * view from a query plans that query like a row statement. Defaults, NOT NULL, CHECK and foreign\n * keys, validated constraints and comments change nothing a statement is\n * planned by. A routine, a view's body or a literal (`nextval('…')`,\n * `to_regclass('…')`, stale for a created or dropped table, index or\n * constraint) can reach any relation, so a row statement after any other\n * schema change needs the commit, whichever relation it names; a `DO` block,\n * a `CALL` or an `EXECUTE` may change the schema itself (what it creates is\n * not read for `NK316`).\n *\n * `boundaries` are the entries a commit must precede, each counted with the\n * changes since the previous one; `first` is the first hazard as `since`\n * leaves it; `inside` is the first entry whose own statements need a commit\n * between them, where none can be placed; `changes` are what the last\n * boundary leaves for whatever follows.\n */\nexport function catalogCommitBoundaries(\n chunks: readonly string[],\n since: CatalogChanges = UNCHANGED_CATALOG\n): {\n readonly boundaries: readonly number[];\n readonly first?: CatalogHazard;\n readonly inside?: CatalogHazard;\n readonly changes: CatalogChanges;\n} {\n let changes = since;\n const boundaries: number[] = [];\n let first: CatalogHazard | undefined;\n let inside: CatalogHazard | undefined;\n for (const [position, chunk] of chunks.entries()) {\n let read = readCatalogChunk(chunk, position, changes);\n if (read.hazard) {\n first ??= read.hazard;\n read = readCatalogChunk(chunk, position, UNCHANGED_CATALOG);\n inside ??= read.hazard;\n boundaries.push(position);\n }\n changes = read.changes;\n }\n return { boundaries, first, inside, changes };\n}\n\n/**\n * Whether `sql` holds a PostgreSQL statement run `CONCURRENTLY` that refuses\n * a transaction block: `CREATE [UNIQUE] INDEX CONCURRENTLY`, `DROP INDEX\n * CONCURRENTLY`, a `REINDEX … CONCURRENTLY` or `ALTER TABLE … DETACH\n * PARTITION … CONCURRENTLY`. Only these wait, by design, for every older\n * transaction without blocking anyone (plan S1). Read from each statement's\n * executable words, so the words in a comment or a literal are not one, and\n * neither is `REFRESH MATERIALIZED VIEW CONCURRENTLY`.\n */\nexport function runsConcurrently(sql: string): boolean {\n return readExecutableStatements(sql, \"postgresql\").some((words) => {\n const [verb] = words;\n if (verb === \"REINDEX\") return words.includes(\"CONCURRENTLY\");\n if (verb === \"ALTER\") {\n return [\"DETACH\", \"PARTITION\", \"CONCURRENTLY\"].every((word) =>\n words.includes(word)\n );\n }\n const index = verb === \"CREATE\" && words[1] === \"UNIQUE\" ? 2 : 1;\n return (\n (verb === \"CREATE\" || verb === \"DROP\") &&\n words[index] === \"INDEX\" &&\n words[index + 1] === \"CONCURRENTLY\"\n );\n });\n}\n","import { isDestructiveOperation } from \"./differ\";\n/**\n * One compiler: DiffOperation and manual Sql become structured operations\n * that share one SQL blob. No delimiter split.\n */\n\nimport type { Sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalDecimalText } from \"../validation/primitives/decimal-value\";\nimport { decodeCanonicalBase64, encodeBase64 } from \"./base64\";\nimport {\n type CatalogProbe,\n probeForGeneratedStatement,\n} from \"./catalog-probes\";\nimport type { DDLContext, MigrationDriver } from \"./drivers\";\nimport { invertOperations } from \"./invert\";\nimport type { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport {\n needsEnumAdditionCommitBoundary,\n runsConcurrently,\n} from \"./statement-safety\";\nimport type { DiffOperation, SchemaSnapshot } from \"./types\";\nimport { encodeTransitionHash } from \"./v1-parse\";\nimport type {\n AtomicityClass,\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationCheckInput,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationParameterV1,\n MigrationParentTransitionV1,\n MigrationRollbackV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport interface CompiledTransition {\n readonly operations: readonly MigrationOperationV1[];\n readonly rollback: MigrationRollbackV1;\n readonly originChecks: readonly MigrationBooleanCheckV1[];\n readonly requestedForwardBoundary: \"transactional\" | \"stepwise\" | null;\n readonly atomicity: AtomicityClass;\n readonly warnings?: readonly string[];\n}\n\n/** The SQL each step of `operations` executes, in order. */\nexport function stepStatements(\n blob: Uint8Array,\n operations: readonly MigrationOperationV1[]\n): string[] {\n return operations.flatMap((operation) =>\n operation.steps.map((step) => sliceDispatch(blob, step.execute))\n );\n}\n\nconst VALIDATE_CONSTRAINT = /\\bVALIDATE\\s+CONSTRAINT\\b/i;\n\n/**\n * Contiguous edges of one boundary share a commit, except that an edge adding\n * a PostgreSQL enum value ends its group: a later edge may use that value,\n * which PostgreSQL refuses until the addition commits (55P04). An edge that\n * validates a constraint commits alone (T5b): sharing a transaction with the\n * edge that added it `NOT VALID` would hold that addition's lock through the\n * scan the split exists to free.\n */\nexport function groupContiguousAtomicity<\n T extends { readonly boundary: string },\n>(\n items: readonly T[],\n statementsOf: (item: T) => readonly string[]\n): readonly {\n readonly boundary: T[\"boundary\"];\n readonly items: readonly T[];\n}[] {\n const groups: {\n boundary: T[\"boundary\"];\n items: T[];\n }[] = [];\n let mustCommit = false;\n for (const item of items) {\n const statements = statementsOf(item);\n const alone = statements.some((text) => VALIDATE_CONSTRAINT.test(text));\n const current = groups.at(-1);\n if (current?.boundary === item.boundary && !(mustCommit || alone)) {\n current.items.push(item);\n } else {\n groups.push({ boundary: item.boundary, items: [item] });\n }\n mustCommit = alone || needsEnumAdditionCommitBoundary(statements);\n }\n return groups;\n}\n\n/**\n * The context a generated statement compiles in. `lowLock` asks PostgreSQL\n * for the form of a step that blocks no write while it reads the table (T5b):\n * `\"add\"` builds an index `CONCURRENTLY` or adds a foreign key `NOT VALID`,\n * `\"validate\"` validates that key. Only `generate({ lowLock: true })` sets\n * it, and only on a table that existed before the migration.\n */\nexport type LowLockContext = DDLContext & {\n readonly lowLock?: \"add\" | \"validate\";\n};\n\n/** One state of a generated program split at its low-lock steps. */\nexport interface LowLockState {\n readonly operations: readonly DiffOperation[];\n /** The schema the state reaches. */\n readonly snapshot: SchemaSnapshot;\n /** Whether it validates the keys an earlier state added `NOT VALID`. */\n readonly validates: boolean;\n}\n\n/**\n * Splits a generated PostgreSQL program into the states that give each\n * low-lock step its own commit (T5b), or returns `undefined` when it has none\n * to give. A step is an index built on, or a foreign key added to, a table\n * the program does not create (a table it creates is empty). Each index build\n * is a state of its own: `CREATE INDEX CONCURRENTLY` runs outside any\n * transaction, and an interrupted build is then one unfinished single-step\n * attempt that `resolve` repairs either way. The keys are added `NOT VALID`\n * with the last state, and a final state validates them in a commit of its\n * own; a failed validation rolls back alone and `apply` resumes from the\n * marker.\n *\n * The schemas between states are the target's with the later states' effects\n * undone, so only an index build, an index drop or a key may follow the first\n * build; otherwise, or when a dropped index cannot be read back from the\n * origin, the program is not split and keeps its blocking forms.\n */\nexport function lowLockStates(\n operations: readonly DiffOperation[],\n current: SchemaSnapshot,\n desired: SchemaSnapshot\n): { states: LowLockState[]; steps: ReadonlySet<DiffOperation> } | undefined {\n const steps = lowLockSteps(operations, desired);\n if (steps.size === 0) return;\n const first = operations.findIndex(\n (op) => op.type === \"createIndex\" && steps.has(op)\n );\n const tail = first < 0 ? [] : operations.slice(first);\n const renames = operations.some(\n (op) => op.type === \"renameTable\" || op.type === \"renameColumn\"\n );\n if (\n !tail.every((op) =>\n op.type === \"createIndex\"\n ? steps.has(op)\n : op.type === \"addForeignKey\" || (op.type === \"dropIndex\" && !renames)\n )\n ) {\n return;\n }\n const ends: number[] = [];\n for (const [index, op] of operations.entries()) {\n if (op.type === \"createIndex\" && steps.has(op)) {\n if (index > (ends.at(-1) ?? 0)) ends.push(index);\n ends.push(index + 1);\n }\n }\n if (ends.at(-1) !== operations.length) ends.push(operations.length);\n const states: LowLockState[] = [];\n for (const [index, end] of ends.entries()) {\n const snapshot = withoutEffects(desired, current, operations.slice(end));\n if (!snapshot) return;\n states.push({\n operations: operations.slice(ends[index - 1] ?? 0, end),\n snapshot,\n validates: false,\n });\n }\n const keys = operations.filter(\n (op) => op.type === \"addForeignKey\" && steps.has(op)\n );\n if (keys.length > 0) {\n states.push({ operations: keys, snapshot: desired, validates: true });\n }\n return { states, steps };\n}\n\n/**\n * The index builds and keys of `operations` on tables it does not create. A\n * raw index is not one: its text is the author's, and it is built blocking.\n * Nor is an index of a materialized view: no write waits for its build, only\n * a refresh.\n */\nexport function lowLockSteps(\n operations: readonly DiffOperation[],\n desired: SchemaSnapshot\n): ReadonlySet<DiffOperation> {\n const inPlace = new Set([\n ...operations.flatMap((op) =>\n op.type === \"createTable\" ? op.table.name : []\n ),\n ...(desired.views ?? []).map((view) => view.name),\n ]);\n return new Set(\n operations.filter(\n (op) =>\n ((op.type === \"createIndex\" && !op.index.raw) ||\n op.type === \"addForeignKey\") &&\n !inPlace.has(op.tableName)\n )\n );\n}\n\n/** `desired` before `later`: an index build, an index drop or a key. */\nfunction withoutEffects(\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n later: readonly DiffOperation[]\n): SchemaSnapshot | undefined {\n let readable = later.every(\n (op) =>\n \"tableName\" in op &&\n desired.tables.some((table) => table.name === op.tableName)\n );\n const tables = desired.tables.map((table) => {\n const own = later.filter(\n (op) => \"tableName\" in op && op.tableName === table.name\n );\n if (own.length === 0) return table;\n const built = new Set(\n own.flatMap((op) => (op.type === \"createIndex\" ? op.index.name : []))\n );\n const keys = new Set(\n own.flatMap((op) => (op.type === \"addForeignKey\" ? op.fk.name : []))\n );\n const restored = own.flatMap((op) => {\n if (op.type !== \"dropIndex\") return [];\n const index = current.tables\n .find((origin) => origin.name === table.name)\n ?.indexes.find((item) => item.name === op.indexName);\n if (!index) readable = false;\n return index ?? [];\n });\n return {\n ...table,\n indexes: [\n ...table.indexes.filter((index) => !built.has(index.name)),\n ...restored,\n ],\n foreignKeys: table.foreignKeys.filter((key) => !keys.has(key.name)),\n };\n });\n return readable ? { ...desired, tables } : undefined;\n}\n\nexport function compileGeneratedTransition(\n operations: readonly DiffOperation[],\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n desiredSchema: SchemaSnapshot,\n assembly: SqlAssembly,\n lowLock: ReadonlySet<DiffOperation> = new Set()\n): CompiledTransition {\n const compiled = operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n currentSchema,\n operations,\n index,\n assembly,\n lowLock.has(operation) ? \"add\" : undefined\n )\n )\n .filter((operation) => operation.steps.length > 0);\n const inverse = invertOperations(\n [...operations],\n currentSchema,\n driver.projectNativeRename.bind(driver),\n driver.generatedPrimaryKeyName.bind(driver)\n );\n const missingBackfill = inverse.operations.find(\n (operation) =>\n operation.type === \"addColumn\" &&\n !operation.column.nullable &&\n operation.column.default === undefined\n );\n const irreversibleReason =\n missingBackfill && missingBackfill.type === \"addColumn\"\n ? `Rollback cannot restore required \"${missingBackfill.tableName}.${missingBackfill.column.name}\" without backfill; author manual rollback.`\n : inverse.operations\n .map((operation) => driver.getIrreversibleRollbackReason(operation))\n .find((reason) => reason !== undefined);\n const rollback: MigrationRollbackV1 =\n inverse.operations.length === 0 && operations.length === 0\n ? { kind: \"schema\", operations: [] }\n : irreversibleReason !== undefined\n ? { kind: \"irreversible\", reason: irreversibleReason }\n : inverse.operations.length === 0\n ? {\n kind: \"irreversible\",\n reason:\n inverse.warnings[0] ??\n \"Generated operations have no automatic inverse\",\n }\n : {\n kind: \"schema\",\n operations: inverse.operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n desiredSchema,\n inverse.operations,\n index,\n assembly\n )\n )\n .filter((operation) => operation.steps.length > 0),\n };\n return {\n operations: compiled,\n rollback,\n warnings: inverse.warnings,\n originChecks: [],\n requestedForwardBoundary: null,\n atomicity: classifyGeneratedAtomicity(driver, operations),\n };\n}\n\n/**\n * The state that validates the foreign keys an earlier state added `NOT VALID`\n * (T5b). Undoing it is nothing: the keys stay, as their state declares them.\n */\nexport function compileValidationTransition(\n keys: readonly DiffOperation[],\n driver: MigrationDriver,\n currentSchema: SchemaSnapshot,\n assembly: SqlAssembly\n): CompiledTransition {\n return {\n operations: keys.map((key, index) =>\n compileGeneratedOperation(\n key,\n driver,\n \"artifact\",\n currentSchema,\n keys,\n index,\n assembly,\n \"validate\"\n )\n ),\n rollback: { kind: \"schema\", operations: [] },\n originChecks: [],\n requestedForwardBoundary: null,\n atomicity: \"transactional\",\n };\n}\n\nfunction compileGeneratedOperation(\n operation: DiffOperation,\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n batch: readonly DiffOperation[],\n index: number,\n assembly: SqlAssembly,\n lowLock?: LowLockContext[\"lowLock\"]\n): MigrationOperationV1 {\n const context: LowLockContext = {\n destination,\n currentSchema,\n precedingOperations: batch.slice(0, index),\n followingOperations: batch.slice(index + 1),\n ...(lowLock === undefined ? {} : { lowLock }),\n };\n const statements = driver.compileStatements(operation, context);\n const steps: MigrationStepV1[] = statements.map((statement) => {\n const probes = probeForGeneratedStatement(driver, operation, statement);\n const execute = addDispatch(assembly, statement, []);\n if (!probes) {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: checkFromProbe(assembly, probes.pre),\n execute,\n postcheck: checkFromProbe(assembly, probes.post),\n };\n });\n return {\n id: `${operation.type}:${index}`,\n label: operationLabel(operation),\n origin: \"generated\",\n risk: isDestructiveOperation(operation) ? \"destructive\" : \"safe\",\n steps,\n };\n}\n\nfunction operationLabel(operation: DiffOperation): string {\n if (operation.type === \"createView\")\n return `createView ${operation.view.name}`;\n if (operation.type === \"dropView\") return `dropView ${operation.viewName}`;\n return \"tableName\" in operation\n ? `${operation.type} ${operation.tableName}${\"columnName\" in operation ? `.${operation.columnName}` : \"column\" in operation ? `.${operation.column.name}` : \"\"}`\n : operation.type;\n}\n\nconst invalidEstate = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE);\nconst unsupportedProvider = (message: string, meta?: Record<string, unknown>) =>\n new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n meta ? { meta } : undefined\n );\n\nexport function compileManualTransition(\n up: readonly Sql[],\n rollback:\n | {\n readonly kind: \"manual\";\n readonly execution: AtomicityClass;\n readonly sql: readonly Sql[];\n }\n | { readonly kind: \"irreversible\"; readonly reason: string },\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n requested: AtomicityClass,\n originChecks: readonly MigrationCheckInput[] | undefined,\n assembly: SqlAssembly\n): CompiledTransition {\n const operations = compileManualOperations(\n up,\n dialect,\n assembly,\n \"forward\",\n requested\n );\n if (rollback.kind === \"irreversible\" && rollback.reason.trim().length === 0)\n throw invalidEstate(\"Irreversible rollback needs non-empty reason\");\n const compiledRollback: MigrationRollbackV1 =\n rollback.kind === \"irreversible\"\n ? rollback\n : {\n kind: \"manual\",\n requestedBoundary: rollback.execution,\n operations: compileManualOperations(\n rollback.sql,\n dialect,\n assembly,\n \"rollback\",\n rollback.execution\n ),\n };\n return {\n operations,\n rollback: compiledRollback,\n originChecks: (originChecks ?? []).map((check, index) =>\n compileTrustedCheck(check, dialect, assembly, `origin:${index}`)\n ),\n requestedForwardBoundary: requested,\n atomicity: requested,\n };\n}\n\nexport function assertManualStepwiseProof(\n compiled: CompiledTransition,\n destinationChecks: readonly MigrationBooleanCheckV1[]\n): void {\n const forwardStepwise = compiled.requestedForwardBoundary === \"stepwise\";\n const rollbackStepwise =\n compiled.rollback.kind === \"manual\" &&\n compiled.rollback.requestedBoundary === \"stepwise\";\n if (!(forwardStepwise || rollbackStepwise)) return;\n if (compiled.originChecks.length === 0 || destinationChecks.length === 0)\n throw invalidEstate(\n \"Stepwise manual requires origin and destination checks\"\n );\n}\n\nfunction compileManualOperations(\n fragments: readonly Sql[],\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n prefix: string,\n execution: AtomicityClass\n): MigrationOperationV1[] {\n if (fragments.length === 0)\n throw invalidEstate(`Manual ${prefix} requires >= 1 dispatch`);\n if (execution === \"stepwise\" && dialect === \"sqlite\")\n throw unsupportedProvider(\n `SQLite does not support stepwise manual ${prefix}; use \"transactional\".`,\n { dialect, feature: \"stepwise execution\" }\n );\n return fragments.map((fragment, index) => {\n const text = fragment.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n if (text.trim().length === 0)\n throw invalidEstate(`Manual ${prefix} dispatch ${index} is empty`);\n if (\n execution === \"transactional\" &&\n dialect === \"postgresql\" &&\n runsConcurrently(text)\n )\n throw invalidEstate(\n `Manual ${prefix} dispatch ${index} uses CONCURRENTLY; requires \"stepwise\".`\n );\n const parameters = fragment.values.map((value) => encodeParameter(value));\n return {\n id: `manual:${prefix}:${index}`,\n label: \"manual\",\n origin: \"manual\" as const,\n risk: \"opaque\" as const,\n steps: [\n {\n retry: \"opaque\" as const,\n execute: addDispatch(assembly, text, parameters),\n },\n ],\n };\n });\n}\n\nexport function compileTrustedCheck(\n input: MigrationCheckInput,\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n id: string\n): MigrationBooleanCheckV1 & { readonly kind: \"trusted-read\" } {\n const text = input.query.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n const parameters = input.query.values.map((value) => encodeParameter(value));\n return {\n kind: \"trusted-read\" as const,\n id,\n query: addDispatch(assembly, text, parameters),\n equals: input.equals,\n };\n}\n\nexport function sealParent(\n fromState: string | null,\n compiled: CompiledTransition,\n approvals: readonly MigrationApprovalV1[] = [],\n adopts: readonly string[] = []\n): Omit<MigrationParentTransitionV1, \"transitionHash\"> {\n return {\n fromState,\n originChecks: compiled.originChecks,\n requestedForwardBoundary: compiled.requestedForwardBoundary,\n operations: compiled.operations,\n rollback: compiled.rollback,\n ...(approvals.length === 0 ? {} : { approvals }),\n ...(adopts.length === 0 ? {} : { adopts }),\n };\n}\n\nexport function hashParent(\n parent: Omit<MigrationParentTransitionV1, \"transitionHash\">\n): MigrationParentTransitionV1 {\n return { ...parent, transitionHash: encodeTransitionHash(parent) };\n}\n\nfunction addDispatch(\n assembly: SqlAssembly,\n text: string,\n parameters: readonly MigrationParameterV1[]\n): MigrationDispatchV1 {\n const index = assembly.add(text, parameters);\n return {\n dispatchId: \"0\".repeat(64),\n sqlHash: \"0\".repeat(64),\n offset: index,\n length: 0,\n parameters,\n };\n}\n\nfunction checkFromProbe(\n assembly: SqlAssembly,\n probe: CatalogProbe\n): MigrationBooleanCheckV1 {\n return {\n kind: \"driver\",\n id: probe.id,\n query: addDispatch(assembly, probe.sql, probe.parameters),\n equals: probe.equals,\n };\n}\n\nexport function rebindDispatches(\n operations: readonly MigrationOperationV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationOperationV1[] {\n return operations.map((operation) => ({\n ...operation,\n steps: operation.steps.map((step) => rebindStep(step, dispatches)),\n }));\n}\n\nfunction rebindStep(\n step: MigrationStepV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationStepV1 {\n const execute = dispatchAt(dispatches, step.execute.offset);\n if (step.retry === \"opaque\") {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: {\n ...step.precheck,\n query: dispatchAt(dispatches, step.precheck.query.offset),\n },\n execute,\n postcheck: {\n ...step.postcheck,\n query: dispatchAt(dispatches, step.postcheck.query.offset),\n },\n };\n}\n\n/** The sealed dispatch at an index the same assembly handed out. */\nexport function dispatchAt(\n dispatches: readonly MigrationDispatchV1[],\n index: number\n): MigrationDispatchV1 {\n const found = dispatches[index];\n if (!found) {\n throw new MigrationError(\n \"Compiled dispatch is missing from the SQL assembly\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return found;\n}\n\nexport function rebindChecks(\n checks: readonly MigrationBooleanCheckV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationBooleanCheckV1[] {\n return checks.map((check) => ({\n ...check,\n query: dispatchAt(dispatches, check.query.offset),\n }));\n}\n\nexport function rebindRollback(\n rollback: MigrationRollbackV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationRollbackV1 {\n if (rollback.kind === \"irreversible\") return rollback;\n return {\n ...rollback,\n operations: rebindDispatches(rollback.operations, dispatches),\n };\n}\n\nconst IDENTIFIER = String.raw`(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)`;\nconst QUALIFIED = String.raw`${IDENTIFIER}(?:\\.${IDENTIFIER})?`;\n\nconst ALTER_TYPE_ADD_VALUE = /ALTER\\s+TYPE\\s+\\S+\\s+ADD\\s+VALUE/i;\n\n/** `CREATE TABLE <name>` (group 1), or `ALTER TABLE <name>` (2) and its actions (3). */\nconst TABLE_STATEMENT = new RegExp(\n String.raw`\\bCREATE\\s+(?:(?:GLOBAL|LOCAL|TEMP|TEMPORARY|UNLOGGED)\\s+)*TABLE\\s+(?!IF\\s+NOT\\s+EXISTS\\b)(${QUALIFIED})|\\bALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${QUALIFIED})([^;]*)`,\n \"gi\"\n);\n/** `RENAME TO <name>`, the whole action of an `ALTER TABLE`. */\nconst RENAME_TO = new RegExp(\n String.raw`^\\s*RENAME\\s+TO\\s+(${IDENTIFIER})\\s*$`,\n \"i\"\n);\nconst LAST_IDENTIFIER = new RegExp(`${IDENTIFIER}$`);\n/** Each action that rewrites or scans the table, and how a refusal names it. */\nconst TABLE_REWRITES: readonly (readonly [RegExp, (name: string) => string])[] =\n [\n [\n new RegExp(\n String.raw`\\bALTER\\s+(?:COLUMN\\s+)?(${IDENTIFIER})\\s+(?:SET\\s+DATA\\s+)?TYPE\\b`,\n \"i\"\n ),\n (column) => `column type change of ${column}`,\n ],\n [\n new RegExp(\n String.raw`\\bALTER\\s+(?:COLUMN\\s+)?(${IDENTIFIER})\\s+SET\\s+NOT\\s+NULL\\b`,\n \"i\"\n ),\n (column) => `SET NOT NULL on ${column}`,\n ],\n [\n new RegExp(\n String.raw`\\bADD\\s+(?:COLUMN\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?(?!(?:CONSTRAINT|PRIMARY|UNIQUE|FOREIGN|CHECK|EXCLUDE)\\b)(${IDENTIFIER})[\\s\\S]*?(?:\\b(?:gen_random_uuid|uuidv[47]|uuid_generate_v[14]|random|clock_timestamp|timeofday|nextval)\\s*\\(|\\b(?:SMALL|BIG)?SERIAL\\b|\\bGENERATED\\b)`,\n \"i\"\n ),\n (column) => `volatile default on new column ${column}`,\n ],\n [\n // `NOT VALID` counts up to the next `, ADD` action, not past it.\n new RegExp(\n String.raw`\\bADD\\s+(?:CONSTRAINT\\s+${IDENTIFIER}\\s+)?(FOREIGN\\s+KEY|CHECK)\\b(?!(?:(?!,\\s*ADD\\b)[\\s\\S])*\\bNOT\\s+VALID\\b)`,\n \"i\"\n ),\n (constraint) => `${constraint.toUpperCase()} validation`,\n ],\n ];\n\n/**\n * The PostgreSQL statements of `program` that rewrite or scan an existing\n * table while holding a lock that blocks it (T5a): a column type change (an\n * enum replacement and a decimal descriptor change are ones), `SET NOT NULL`,\n * a new column whose default is volatile, and a FOREIGN KEY or CHECK added\n * without `NOT VALID`. One entry per `ALTER TABLE`, naming its table as the\n * statement spells it and its first such action; a table an earlier\n * `RENAME TO` of the program renamed is named by its spelling before the\n * program ran, the one the live catalog holds. A table the program has\n * already created by that spelling is empty, so it is left out (a force\n * reset, a drop and recreate), as it is once renamed. A plain `CREATE INDEX`\n * (writes blocked, reads not) is not one.\n */\nexport function tableRewrites(\n program: readonly string[]\n): { readonly table: string; readonly operation: string }[] {\n const created = new Set<string>();\n const before = new Map<string, string>();\n return program.flatMap((statement) =>\n [...statement.matchAll(TABLE_STATEMENT)].flatMap(\n ([, made, table, clause]) => {\n if (made) created.add(made);\n if (!table) return [];\n const renamedTo = RENAME_TO.exec(clause ?? \"\")?.[1];\n if (renamedTo) {\n const next = table.replace(LAST_IDENTIFIER, renamedTo);\n if (created.has(table)) created.add(next);\n else before.set(next, before.get(table) ?? table);\n return [];\n }\n if (created.has(table)) return [];\n for (const [pattern, name] of TABLE_REWRITES) {\n const action = pattern.exec(clause ?? \"\")?.[1];\n if (action) {\n return [\n { table: before.get(table) ?? table, operation: name(action) },\n ];\n }\n }\n return [];\n }\n )\n );\n}\n\nfunction isNonTransactionalSql(driver: MigrationDriver, sql: string): boolean {\n if (runsConcurrently(sql)) return true;\n return (\n ALTER_TYPE_ADD_VALUE.test(sql) &&\n !driver.capabilities.supportsAddEnumValueInTransaction\n );\n}\n\nexport function classifyGeneratedAtomicity(\n driver: MigrationDriver,\n operations: readonly DiffOperation[],\n reset?: boolean\n): AtomicityClass {\n if (driver.dialect === \"mysql\" || driver.buildsApart?.(operations, reset))\n return \"stepwise\";\n if (\n operations.some(\n (operation) =>\n operation.type === \"alterEnum\" &&\n (operation.addValues?.length ?? 0) > 0 &&\n !driver.capabilities.supportsAddEnumValueInTransaction\n )\n ) {\n return \"stepwise\";\n }\n return \"transactional\";\n}\n\nexport function assertTransactionalBoundaryHonored(\n supportsTransactions: boolean,\n requested: \"transactional\" | \"stepwise\" | null\n): void {\n if (requested === \"transactional\" && !supportsTransactions) {\n throw unsupportedProvider(\"Producer cannot honor transactional boundary\");\n }\n}\n\nexport function refuseSqliteStepwise(\n driver: MigrationDriver,\n requested: \"transactional\" | \"stepwise\" | null,\n toState: string\n): void {\n if (requested !== \"stepwise\" || driver.dialect !== \"sqlite\") return;\n throw unsupportedProvider(\n 'SQLite does not support stepwise; use \"transactional\".',\n { dialect: \"sqlite\", toState, feature: \"stepwise execution\" }\n );\n}\n\nexport function classifyStoredAtomicity(\n driver: MigrationDriver,\n requested: \"transactional\" | \"stepwise\" | null,\n operations: readonly MigrationOperationV1[],\n blob?: Uint8Array\n): AtomicityClass {\n if (requested === \"transactional\" && driver.dialect === \"mysql\") {\n throw unsupportedProvider(\"Provider cannot honor transactional boundary\");\n }\n // Neki refuses any statement after a schema change in its transaction, a\n // control write included: there every step commits alone, as before an\n // edge whose statements needed a commit was already cut into parts.\n if (driver.commitsSchemaChangesAlone()) return \"stepwise\";\n if (requested === \"transactional\") return \"transactional\";\n if (requested === \"stepwise\") return \"stepwise\";\n if (driver.dialect === \"mysql\") return \"stepwise\";\n if (\n blob &&\n stepStatements(blob, operations).some((text) =>\n isNonTransactionalSql(driver, text)\n )\n ) {\n return \"stepwise\";\n }\n return \"transactional\";\n}\n\nexport function encodeParameter(value: unknown): MigrationParameterV1 {\n if (value === null || value === undefined) return { kind: \"null\" };\n if (typeof value === \"boolean\") return { kind: \"boolean\", value };\n if (typeof value === \"string\") return { kind: \"string\", value };\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw invalidEstate(\"SQL parameters refuse NaN and Infinity\");\n }\n return { kind: \"number\", value };\n }\n if (typeof value === \"bigint\")\n return { kind: \"bigint\", value: value.toString() };\n if (value instanceof Date)\n return { kind: \"date-time\", value: value.toISOString() };\n if (value instanceof Uint8Array) {\n return { kind: \"bytes\", value: encodeBase64(value) };\n }\n const decimal = canonicalDecimalText(value);\n if (decimal !== undefined) return { kind: \"decimal\", value: decimal };\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n throw invalidEstate(\"SQL parameters refuse functions and symbols\");\n }\n return { kind: \"json\", value };\n}\n\nexport function decodeParameter(\n parameter: MigrationParameterV1,\n targetNamespace?: string\n): unknown {\n switch (parameter.kind) {\n case \"null\":\n return null;\n case \"target-namespace\":\n if (targetNamespace === undefined) {\n throw new MigrationError(\n \"Stored target-namespace parameter requires resolved namespace\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return targetNamespace;\n case \"boolean\":\n case \"string\":\n case \"number\":\n case \"json\":\n return parameter.value;\n case \"bigint\":\n return BigInt(parameter.value);\n case \"bytes\": {\n const bytes = decodeCanonicalBase64(parameter.value);\n if (bytes === undefined) {\n throw invalidEstate(\"Stored bytes parameter is not canonical Base64\");\n }\n return bytes;\n }\n case \"date-time\":\n return new Date(parameter.value);\n case \"decimal\":\n return parameter.value;\n default: {\n const kind: never = parameter;\n throw invalidEstate(\n `Unknown SQL parameter kind: ${JSON.stringify(kind)}`\n );\n }\n }\n}\n","import { errorCause } from \"../errors/diagnostic-safety\";\n/**\n * One execution owner for authenticated SQL slices and typed parameters.\n * Apply, down, reset, and push consume this. There is no second executor.\n */\n\nimport type { AnyDriver, CommitRerunningDriver } from \"../drivers/driver\";\nimport { attachMissingMeta } from \"../drivers/driver-error-context\";\nimport type { SqlDialect } from \"../drivers/types\";\nimport {\n ConnectionError,\n isVibORMError,\n MigrationError,\n type MigrationErrorMeta,\n type VibORMError,\n VibORMErrorCode,\n} from \"../errors\";\nimport { decodeParameter } from \"./compile\";\nimport type { MigrationBatch } from \"./pinned-session\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { readExecutableStatements } from \"./statement-safety\";\nimport { readFlag } from \"./v1-parse-shared\";\nimport type {\n LedgerEffectStateV1,\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\n/**\n * Every statement a migration runs, as the engine built it: the driver may run\n * it again where its own transaction around it was refused at its commit\n * (`rerunRefusedCommit`, SurrealDB), which a caller's raw statement never is.\n */\nexport async function executeExactSql(\n producer: AnyDriver,\n sql: string,\n parameters: readonly unknown[] = []\n): Promise<void> {\n const send = () => producer._executeRaw(sql, [...parameters]);\n await (rerunsRefusedCommits(producer)\n ? producer.rerunRefusedCommit(sql, send)\n : send());\n}\n\n/**\n * Whether `driver` makes one transaction of a batch it sends, and runs it\n * again where that transaction was refused at its commit (SurrealDB).\n */\nexport const rerunsRefusedCommits = (\n driver: AnyDriver\n): driver is AnyDriver & CommitRerunningDriver =>\n typeof Reflect.get(driver, \"rerunRefusedCommit\") === \"function\";\n\n/**\n * Dispatches that commit together or not at all, as ONE request: the driver\n * makes one transaction of the batch, outside any other. Refused at its\n * commit, nothing of it was applied, so it runs again (`rerunRefusedCommit`),\n * which no other failure does. The engine opens that transaction: a\n * migration's text never holds `BEGIN`, `COMMIT` or `CANCEL`\n * (`statement-safety.ts`).\n */\nexport async function executeDispatchGroup(\n producer: AnyDriver & CommitRerunningDriver,\n blob: Uint8Array,\n dispatches: readonly MigrationDispatchV1[],\n targetNamespace?: string\n): Promise<void> {\n const queries = dispatches.map((dispatch) =>\n dispatchQuery(blob, dispatch, targetNamespace)\n );\n await producer.rerunRefusedCommit(queries, () =>\n producer._executeBatch(queries)\n );\n}\n\n/** A dispatch's exact text and its decoded parameters. */\nfunction dispatchQuery(\n blob: Uint8Array,\n dispatch: MigrationDispatchV1,\n targetNamespace: string | undefined\n): { readonly sql: string; readonly params: unknown[] } {\n return {\n sql: sliceDispatch(blob, dispatch),\n params: dispatch.parameters.map((parameter) =>\n decodeParameter(parameter, targetNamespace)\n ),\n };\n}\n\nexport async function executeDispatch(\n producer: AnyDriver,\n blob: Uint8Array,\n dispatch: MigrationDispatchV1,\n targetNamespace?: string\n): Promise<void> {\n const { sql, params } = dispatchQuery(blob, dispatch, targetNamespace);\n await executeExactSql(producer, sql, params);\n}\n\nexport async function evaluateCheck(\n producer: AnyDriver,\n blob: Uint8Array,\n check: MigrationBooleanCheckV1,\n targetNamespace?: string\n): Promise<boolean> {\n const { sql, params } = dispatchQuery(blob, check.query, targetNamespace);\n const result = await producer._executeRaw<Record<string, unknown>>(\n sql,\n params\n );\n if (result.rows.length !== 1)\n throw new MigrationError(\n `Check ${check.id} must return 1 row`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n const values = Object.values(result.rows[0]!);\n if (values.length !== 1)\n throw new MigrationError(\n `Check ${check.id} must return 1 column`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n const flag = readFlag(values[0]);\n if (flag === undefined)\n throw new MigrationError(\n `Check ${check.id} must return boolean`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return flag === check.equals;\n}\n\nconst TRAILING_SEMICOLON = /;\\s*$/;\n\n/**\n * {@link evaluateCheck} as a condition one request asserts (plan D7): the\n * check's one row holds one value, `check.equals` in a spelling\n * `readFlag` reads. No row, more rows, or another value do not hold. A\n * check with another number of columns is refused, as `evaluateCheck`\n * refuses it: the `UNION ALL` with one column fails the request, which rolls\n * back. Columns are named, never read as one whole row, which PlanetScale\n * Neki refuses.\n */\nexport function checkCondition(\n blob: Uint8Array,\n check: MigrationBooleanCheckV1,\n targetNamespace: string | undefined\n): { readonly sql: string; readonly params: unknown[] } {\n const { sql, params } = dispatchQuery(blob, check.query, targetNamespace);\n const spellings = check.equals ? \"'true', 't', '1'\" : \"'false', 'f', '0'\";\n return {\n sql: `(SELECT CASE WHEN count(*) = 1 THEN min(one.value::text) END FROM (SELECT * FROM (\\n${sql.replace(TRAILING_SEMICOLON, \"\")}\\n) AS checked UNION ALL SELECT NULL WHERE false) AS one(value)) IN (${spellings})`,\n params,\n };\n}\n\n/**\n * Whether `error` is the provider refusing a statement — its answer carries a\n * provider code — rather than a failure of the transport.\n */\nexport function providerRefused(error: unknown): error is VibORMError {\n return (\n isVibORMError(error) &&\n !(error instanceof ConnectionError) &&\n (error.meta.providerCode !== undefined ||\n error.meta.providerSqlState !== undefined)\n );\n}\n\n/**\n * The provider's SQLSTATE and code of a refusal, for the meta of the\n * migration error that wraps it (both are on the error-metadata allow-list;\n * the provider's text stays in the cause, disclosed as the driver's\n * diagnostics allow), and the statement when those diagnostics disclosed it:\n * a wrapped cause keeps no meta of its own. Nothing for a transport failure.\n */\nexport function providerFacts(error: unknown): {\n readonly providerCode?: unknown;\n readonly providerSqlState?: unknown;\n readonly query?: string;\n} {\n if (!providerRefused(error)) return {};\n const { providerCode, providerSqlState, query } = error.meta;\n return {\n ...(providerCode === undefined ? {} : { providerCode }),\n ...(providerSqlState === undefined ? {} : { providerSqlState }),\n ...(query === undefined ? {} : { query }),\n };\n}\n\nexport interface StepProgress {\n readonly operationId: string;\n readonly dispatchId: string;\n readonly skipped: boolean;\n}\n\n/**\n * Records one step's progress. An opaque stepwise step is announced (`none`)\n * before it runs, then answered: `committed`, or — refused whole, nothing of\n * it committed — `none` again with the refusal as `failure`. An announcement\n * never answered may have committed.\n */\ntype OnProgress = (\n progress: StepProgress,\n effect: LedgerEffectStateV1,\n failure?: string\n) => Promise<void>;\n\n/** The edge a program runs, and its command step: every failure names both. */\nexport interface DispatchEdge {\n readonly fromState: string | null;\n readonly toState: string | null;\n /** `apply`, `down`, `resolve` or `reset-replay`. */\n readonly step: string;\n}\n\n/** Where one dispatch sits: its edge, operation, statement and boundary. */\ninterface DispatchSite {\n readonly edge: DispatchEdge | undefined;\n readonly operationId: string;\n readonly statementIndex: number;\n readonly strategy: \"transactional\" | \"stepwise\" | \"atomic\";\n}\n\n/**\n * `failure`, naming where in the command it happened: the keys it already has\n * stay its own. A transport failure keeps its class, so a lost connection is\n * still the retryable `ConnectionError` it is (plan S2).\n */\nexport function annotateMigrationFailure(\n failure: unknown,\n meta: MigrationErrorMeta\n): unknown {\n return isVibORMError(failure) ? attachMissingMeta(failure, meta) : failure;\n}\n\n/**\n * `atomic` is a program inside a real transaction (plan D5): its rollback\n * undoes whatever a failure leaves half done, so no step is probed, and the\n * caller proves the destination once. Its progress is reported only when\n * asked (one part of an edge split at Neki's commit boundaries,\n * `apply-v1.ts`): each report lands in the step's own transaction, so it\n * commits with the step or not at all.\n */\nexport async function executeOperations(\n producer: AnyDriver,\n blob: Uint8Array,\n operations: readonly MigrationOperationV1[],\n boundary: \"transactional\" | \"stepwise\" | \"atomic\",\n onProgress?: OnProgress,\n targetNamespace?: string,\n edge?: DispatchEdge\n): Promise<void> {\n let statementIndex = 0;\n for (const operation of operations) {\n for (const step of operation.steps) {\n await executeStep(\n producer,\n blob,\n {\n edge,\n operationId: operation.id,\n statementIndex,\n strategy: boundary,\n },\n step,\n boundary,\n onProgress,\n targetNamespace\n );\n statementIndex += 1;\n }\n }\n}\n\nfunction siteMeta(site: DispatchSite, dispatchId: string): MigrationErrorMeta {\n const { edge } = site;\n return {\n ...(edge ? { step: edge.step } : {}),\n strategy: site.strategy,\n ...(edge?.fromState ? { fromState: edge.fromState } : {}),\n ...(edge?.toState ? { toState: edge.toState, stateId: edge.toState } : {}),\n operationId: site.operationId,\n dispatchId,\n statementIndex: site.statementIndex,\n };\n}\n\n/**\n * Runs one dispatch. A statement the provider refused — its answer carries a\n * provider code — becomes a MigrationError naming its edge, operation,\n * dispatch and statement, with that code; SQL and parameters stay on the\n * cause, behind diagnostics. A transport failure is not a refusal: it stays\n * what it is, and the pinned session reports a lost connection as the\n * retryable failure it is (plan S2).\n */\nasync function runDispatch(\n producer: AnyDriver,\n blob: Uint8Array,\n site: DispatchSite,\n dispatch: MigrationDispatchV1,\n targetNamespace: string | undefined\n): Promise<void> {\n try {\n await executeDispatch(producer, blob, dispatch, targetNamespace);\n } catch (error) {\n if (!providerRefused(error))\n throw annotateMigrationFailure(\n error,\n siteMeta(site, dispatch.dispatchId)\n );\n throw refusal(site, dispatch.dispatchId, error);\n }\n}\n\nfunction refusal(\n site: DispatchSite,\n dispatchId: string,\n error: VibORMError,\n meta?: MigrationErrorMeta\n): MigrationError {\n return new MigrationError(\n `Migration statement ${site.statementIndex} of operation ${site.operationId} failed`,\n VibORMErrorCode.MIGRATION_FAILED,\n {\n cause: error,\n meta: {\n ...siteMeta(site, dispatchId),\n ...providerFacts(error),\n ...meta,\n },\n }\n );\n}\n\n/**\n * Leaders of a statement that may COMMIT part of its work before it fails: a\n * procedure, a PostgreSQL `DO` block, a statement prepared earlier.\n */\nconst COMMITS_INSIDE = new Set([\"CALL\", \"DO\", \"EXECUTE\"]);\n\n/**\n * Whether the provider's refusal of `sql` proves none of it committed: one\n * statement, run bare as a transaction of its own, which the server undoes\n * whole when it refuses it (VibORM's MySQL tables are InnoDB). Not one led by\n * {@link COMMITS_INSIDE}, nor a `CONCURRENTLY` statement, which commits in\n * phases.\n */\nfunction refusedWhole(\n error: unknown,\n sql: string,\n dialect: AnyDriver[\"dialect\"]\n): error is VibORMError {\n if (!providerRefused(error)) return false;\n const statements = readExecutableStatements(sql, dialect as SqlDialect);\n const [leader = \"\", ...rest] = statements[0] ?? [];\n return (\n statements.length === 1 &&\n !COMMITS_INSIDE.has(leader) &&\n !rest.includes(\"CONCURRENTLY\")\n );\n}\n\nasync function executeStep(\n producer: AnyDriver,\n blob: Uint8Array,\n site: DispatchSite,\n step: MigrationStepV1,\n boundary: \"transactional\" | \"stepwise\" | \"atomic\",\n onProgress?: OnProgress,\n targetNamespace?: string\n): Promise<void> {\n const { operationId } = site;\n if (boundary === \"atomic\") {\n await runDispatch(producer, blob, site, step.execute, targetNamespace);\n // Recorded, when asked, in the transaction the step ran in: with it.\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n return;\n }\n if (step.retry === \"proven\") {\n if (await evaluateCheck(producer, blob, step.postcheck, targetNamespace)) {\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: true },\n \"none\"\n );\n return;\n }\n if (\n !(await evaluateCheck(producer, blob, step.precheck, targetNamespace))\n ) {\n throw new MigrationError(\n `Proven step ${operationId} is neither at origin nor destination`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { lastConfirmedStep: step.execute.dispatchId } }\n );\n }\n await runDispatch(producer, blob, site, step.execute, targetNamespace);\n if (\n !(await evaluateCheck(producer, blob, step.postcheck, targetNamespace))\n ) {\n throw new MigrationError(\n `Proven step ${operationId} failed its postcheck`,\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT,\n {\n meta: {\n lastConfirmedStep: step.execute.dispatchId,\n effectState: \"partial\",\n partial: true,\n },\n }\n );\n }\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n return;\n }\n\n if (boundary === \"stepwise\") {\n const progress = {\n operationId,\n dispatchId: step.execute.dispatchId,\n skipped: false,\n };\n await onProgress?.(progress, \"none\");\n try {\n await executeDispatch(producer, blob, step.execute, targetNamespace);\n } catch (error) {\n const sql = sliceDispatch(blob, step.execute);\n if (refusedWhole(error, sql, producer.dialect)) {\n const refused = refusal(site, step.execute.dispatchId, error, {\n effectState: \"none\",\n partial: true,\n });\n // Unrecorded, the announcement stands: it may have committed.\n await onProgress?.(\n progress,\n \"none\",\n `${refused.code}: ${refused.message}`\n )?.catch(() => undefined);\n throw refused;\n }\n throw new MigrationError(\n `Opaque stepwise dispatch ${step.execute.dispatchId} failed with an ambiguous outcome`,\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n cause: errorCause(error),\n meta: {\n ...siteMeta(site, step.execute.dispatchId),\n lastConfirmedStep: step.execute.dispatchId,\n effectState: \"may-have-committed\",\n partial: true,\n },\n }\n );\n }\n await onProgress?.(progress, \"committed\");\n return;\n }\n\n await runDispatch(producer, blob, site, step.execute, targetNamespace);\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n}\n\nexport async function evaluateAllChecks(\n producer: AnyDriver,\n blob: Uint8Array,\n checks: readonly MigrationBooleanCheckV1[],\n targetNamespace?: string\n): Promise<boolean> {\n for (const check of checks) {\n if (!(await evaluateCheck(producer, blob, check, targetNamespace))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * The one owner of \"authored checks must hold\": every one of `checks` holds,\n * else `refusal` is the command's MIGRATION_DRIFT. Inside one request (plan\n * D7) each is asserted there instead, as its {@link checkCondition}.\n */\nexport async function assertAllChecks(\n producer: AnyDriver,\n blob: Uint8Array,\n checks: readonly MigrationBooleanCheckV1[],\n targetNamespace: string | undefined,\n refusal: string,\n batch?: MigrationBatch\n): Promise<void> {\n const drift = () =>\n new MigrationError(refusal, VibORMErrorCode.MIGRATION_DRIFT);\n if (batch) {\n for (const check of checks) {\n const { sql, params } = checkCondition(blob, check, targetNamespace);\n batch.assert(sql, params, drift());\n }\n return;\n }\n if (!(await evaluateAllChecks(producer, blob, checks, targetNamespace))) {\n throw drift();\n }\n}\n","/**\n * The one DDL statement a transaction silently swallows.\n *\n * SQLite cannot alter a table in place, so `alterColumn`, `addForeignKey` and\n * both halves of a unique-constraint change go through\n * `SQLite3MigrationDriver.generateTableRecreation`: create `__new_<t>`, copy\n * the rows, `DROP TABLE <t>`, rename. `DROP TABLE` is the step that needs\n * foreign keys really disabled — with enforcement on, SQLite performs an\n * implicit `DELETE FROM` before removing the table, which either raises the\n * constraint or fires the referential action on every child row.\n *\n * `PRAGMA foreign_keys` is documented by SQLite as a NO-OP inside a\n * transaction, and all three places that execute generated DDL run the batch\n * inside one — `execute-dispatch.ts` and the SQLite recreation path.\n * MEASURED on better-sqlite3 at `5e5bc60`, recreating a populated table a\n * single child row pointed at:\n *\n * - `onDelete: noAction` -> `DROP TABLE` threw `FOREIGN KEY constraint\n * failed` and the push applied nothing;\n * - `onDelete: cascade` -> no error, and every child row was gone;\n * - `onDelete: setNull` -> no error, and every child's key was NULL.\n *\n * `PRAGMA defer_foreign_keys=ON` — the spelling SQLite does honor inside a\n * transaction — does not close it: it defers the violation counter the\n * implicit delete already incremented, so `noAction` merely moves its failure\n * from `DROP TABLE` to `COMMIT`, and the two silent halves stay silent.\n *\n * So the pragma is lifted out to bracket the transaction, which is SQLite's own\n * documented procedure — its step 1 (`PRAGMA foreign_keys=OFF`) precedes its\n * step 2 (`BEGIN`). Lifting it is what makes the disable real for the first\n * time, and a real disable is fail-open for the rest of the batch: a\n * `dropTable` sharing the batch would now orphan its children instead of\n * refusing. `assertForeignKeysIntact` is that hole closed — step 10 of the same\n * procedure — and it runs inside the transaction so a violation rolls the whole\n * batch back.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\n\n/**\n * `PRAGMA foreign_keys = OFF` / `= ON`, the only statement any migration driver\n * emits whose effect a transaction discards. Written by\n * `generateTableRecreation`; no other dialect emits it.\n */\nconst MATCH_FOREIGN_KEYS_PRAGMA =\n /^PRAGMA\\s+foreign_keys\\s*=\\s*(ON|OFF)\\s*;?$/i;\n\n/** A statement's leading whitespace and SQL comments. */\nconst LEADING_TRIVIA = /^(?:\\s+|--[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/)*/;\n\nconst DROPS_TABLE = /^DROP\\s+TABLE\\b/i;\n\n/**\n * The `DROP TABLE` a recreation or a `dropTable` renders (`\"name\"`), and the\n * plain spelling a hand-written transition may use, optionally in `main`.\n */\nconst MATCH_DROP_TABLE =\n /^DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:(?:main|\"main\")\\s*\\.\\s*)?(?:\"((?:[^\"]|\"\")+)\"|([A-Za-z_][\\w$]*))\\s*;?\\s*$/i;\n\nconst quote = createIdentifierQuoter('\"');\n\nexport interface ForeignKeyBracket {\n /** Runs before the transaction opens. */\n readonly disable: string;\n /** Runs after it closes, however it closes. */\n readonly enable: string;\n}\n\nexport interface LiftedStatements {\n /** `null` when nothing was lifted; the statements are then untouched. */\n readonly bracket: ForeignKeyBracket | null;\n readonly statements: string[];\n}\n\n/**\n * Whether this driver has no transaction to lift the pragmas out of — and so\n * nothing to prove the lift in.\n *\n * What the pragma does is the driver's declared claim: effectful SQLite work is\n * admitted only on a driver declaring `sqliteMigrationCapability`, whose\n * `foreignKeys: \"pragma\"` says `PRAGMA foreign_keys` between transactions takes\n * effect and reads back (`admission.ts` is that claim's one reader). The claim\n * is then verified on every lift. What is left is the transaction: without one,\n * a recreation that went wrong can neither be checked before it commits nor\n * rolled back, so it is refused (D1 is the stock case: one native batch, no\n * transaction).\n *\n * Exported because the SQLite driver asks the same question before it plans a\n * relation-bearing domain conversion (plan §7.4's D1 prerequisite).\n */\nexport function foreignKeyPragmasCannotBeLifted(driver: AnyDriver): boolean {\n return !driver.supportsTransactions;\n}\n\n/**\n * Takes the foreign-key pragmas out of a DDL batch so the caller can run them\n * around its transaction instead of inside it.\n *\n * Returns `bracket: null` — and the statements unchanged — when there is\n * nothing to lift, so every caller can run the result unconditionally. A batch\n * that needs the lift on a driver that cannot prove one is refused here,\n * before any of it runs.\n */\nexport function liftForeignKeyPragmas(\n driver: AnyDriver,\n statements: string[]\n): LiftedStatements {\n let disable: string | null = null;\n let enable: string | null = null;\n const rest: string[] = [];\n\n for (const statement of statements) {\n const trimmed = statement.trim();\n const match = trimmed.match(MATCH_FOREIGN_KEYS_PRAGMA);\n if (!match) {\n rest.push(statement);\n continue;\n }\n if (match[1]?.toUpperCase() === \"OFF\") {\n disable ??= trimmed;\n } else {\n enable ??= trimmed;\n }\n }\n\n // Half a bracket would leave enforcement off past the batch. Leave the batch\n // exactly as it came instead, so it fails the way it failed before rather\n // than succeeding with the database unguarded.\n if (!(disable && enable)) {\n return { bracket: null, statements };\n }\n if (foreignKeyPragmasCannotBeLifted(driver)) {\n throw new MigrationError(\n `Driver \"${driver.driverName}\" has no transactions for SQLite table recreation.`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n {\n meta: { driver: driver.driverName, feature: \"SQLite table recreation\" },\n }\n );\n }\n\n return { bracket: { disable, enable }, statements: rest };\n}\n\ninterface ForeignKeyCheckRow {\n table?: unknown;\n parent?: unknown;\n}\n\n/**\n * Runs one body inside the lifted transaction: on `transaction`, with every\n * `DROP TABLE` counted around, then `PRAGMA foreign_key_check`.\n */\nexport type InsideLift = <R>(\n transaction: AnyDriver,\n body: (producer: AnyDriver) => Promise<R>\n) => Promise<R>;\n\nconst unlifted: InsideLift = (transaction, body) => body(transaction);\n\n/**\n * Runs `work` with enforcement really off, restoring it however `work` ends.\n * Call it OUTSIDE the transaction `work` opens — that placement is the whole\n * point — and run that transaction's statements through the `inside` it is\n * handed. Without a bracket nothing is lifted and `inside` adds nothing.\n *\n * The lift is verified, not assumed. The driver's `beforeForeignKeysOff` hook\n * runs first, and `PRAGMA foreign_keys` must read 0 after the disable — or the\n * change is refused before any of it runs — and 1 after the re-enable. Inside,\n * every table referencing a dropped table must keep its rows and its keys\n * across that `DROP TABLE`, which still catches a driver whose read-back lies,\n * and `PRAGMA foreign_key_check` must find nothing before the commit.\n */\nexport async function withForeignKeysLifted<T>(\n driver: AnyDriver,\n bracket: ForeignKeyBracket | null,\n work: (inside: InsideLift) => Promise<T>\n): Promise<T> {\n if (!bracket) {\n return await work(unlifted);\n }\n\n await driver[\"beforeForeignKeysOff\"]?.();\n await driver._executeRaw(terminate(bracket.disable));\n let completed = false;\n try {\n await assertEnforcement(driver, 0);\n const result = await work(async (transaction, body) => {\n const value = await body(keepingChildren(transaction));\n await assertForeignKeysIntact(transaction);\n return value;\n });\n completed = true;\n return result;\n } finally {\n await driver._executeRaw(terminate(bracket.enable));\n if (completed) await assertEnforcement(driver, 1);\n }\n}\n\nfunction terminate(statement: string): string {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n}\n\nasync function assertEnforcement(\n driver: AnyDriver,\n expected: 0 | 1\n): Promise<void> {\n const { rows } = await driver._executeRaw<{ foreign_keys?: unknown }>(\n \"PRAGMA foreign_keys;\"\n );\n const read = rows[0]?.foreign_keys;\n if (Number(read) === expected) return;\n throw new MigrationError(\n expected === 0\n ? `PRAGMA foreign_keys=${String(read)} after OFF on \"${driver.driverName}\".`\n : `Committed, but PRAGMA foreign_keys=${String(read)} after ON on \"${driver.driverName}\".`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { driver: driver.driverName, pragma: \"foreign_keys\", expected } }\n );\n}\n\n/**\n * `transaction`, with every `DROP TABLE` run between two counts of each table\n * that references the dropped one (built the way every execution view in this\n * layer is: an `Object.create` restating one member).\n *\n * With enforcement really off, `DROP TABLE` touches no other table. With it on\n * — a driver whose `PRAGMA foreign_keys` read-back lies — it deletes or nulls\n * every child row, which `foreign_key_check` cannot see afterwards. Counting\n * right around the statement, rather than around the whole batch, leaves the\n * batch free to write those rows itself.\n */\nfunction keepingChildren(transaction: AnyDriver): AnyDriver {\n const view: AnyDriver = Object.create(transaction);\n Object.defineProperty(view, \"_executeRaw\", {\n value: async (sql: string, params?: unknown[]) => {\n const parent = droppedTable(sql);\n if (parent === undefined) {\n return await transaction._executeRaw(sql, params);\n }\n const children = await referencingColumns(transaction, parent);\n const before = await countChildren(transaction, children);\n const result = await transaction._executeRaw(sql, params);\n const after = await countChildren(transaction, children);\n const changed = [...children].flatMap(([child, columns], i) =>\n [`\"${child}\" rows`, ...columns.map((c) => `\"${child}\".\"${c}\" non-null`)]\n .map((label, k) => `${label} ${before[i]?.[k]} -> ${after[i]?.[k]}`)\n .filter((_, k) => before[i]?.[k] !== after[i]?.[k])\n );\n if (changed.length > 0) {\n throw new MigrationError(\n `Rows referencing \"${parent}\" changed during DROP TABLE (${changed.join(\", \")}); rolled back.`,\n VibORMErrorCode.MIGRATION_FAILED,\n { meta: { driver: transaction.driverName, table: parent } }\n );\n }\n return result;\n },\n });\n return view;\n}\n\n/**\n * The table a `DROP TABLE` statement drops, or `undefined` for any other\n * statement. A drop whose name it cannot read is refused: its children could\n * not be counted, and the census must not be skipped silently.\n */\nfunction droppedTable(sql: string): string | undefined {\n const statement = sql.replace(LEADING_TRIVIA, \"\");\n if (!DROPS_TABLE.test(statement)) return;\n const match = statement.match(MATCH_DROP_TABLE);\n const name = match?.[1]?.replaceAll('\"\"', '\"') ?? match?.[2];\n if (name !== undefined) return name;\n throw new MigrationError(\n 'Unparseable DROP TABLE during SQLite recreation; rolled back. Use DROP TABLE \"name\".',\n VibORMErrorCode.MIGRATION_FAILED\n );\n}\n\n/** Every other table with a foreign key to `parent`, and its referencing columns. */\nasync function referencingColumns(\n transaction: AnyDriver,\n parent: string\n): Promise<Map<string, string[]>> {\n const { rows } = await transaction._executeRaw<{\n child: unknown;\n column: unknown;\n }>(\n `SELECT DISTINCT m.\"name\" AS \"child\", f.\"from\" AS \"column\" FROM sqlite_master AS m, pragma_foreign_key_list(m.\"name\") AS f WHERE m.\"type\" = 'table' AND f.\"table\" = ? COLLATE NOCASE AND m.\"name\" <> ? COLLATE NOCASE`,\n [parent, parent]\n );\n const children = new Map<string, string[]>();\n for (const row of rows) {\n const child = String(row.child);\n const columns = children.get(child) ?? [];\n columns.push(String(row.column));\n children.set(child, columns);\n }\n return children;\n}\n\n/** Per child: its row count, then the non-null count of each referencing column. */\nasync function countChildren(\n transaction: AnyDriver,\n children: ReadonlyMap<string, readonly string[]>\n): Promise<number[][]> {\n const counts: number[][] = [];\n for (const [child, columns] of children) {\n const keys = columns.map(\n (column, k) => `, count(${quote(column)}) AS \"k${k}\"`\n );\n const { rows } = await transaction._executeRaw<Record<string, unknown>>(\n `SELECT count(*) AS \"rows\"${keys.join(\"\")} FROM ${quote(child)}`\n );\n const row = rows[0] ?? {};\n counts.push([row.rows, ...columns.map((_, k) => row[`k${k}`])].map(Number));\n }\n return counts;\n}\n\n/**\n * Refuses a lifted batch that would commit against a broken reference: the\n * last statement `inside` runs, in the transaction, so the throw takes the\n * batch back.\n *\n * This is why the lift is not a fail-open trade. Lifting the pragma disables\n * enforcement for the whole batch, not just the recreation, so a `dropTable`\n * or a rebuild that sheds a referenced column could commit orphans the\n * un-lifted — and therefore never actually disabled — batch would have refused.\n * `PRAGMA foreign_key_check` is step 10 of SQLite's own recreation procedure.\n *\n * It cannot tell a reference the batch broke from one it merely found, and\n * refuses either way: SQLite's procedure says a reported violation means the\n * schema change is to be abandoned.\n */\nexport async function assertForeignKeysIntact(\n transaction: AnyDriver\n): Promise<void> {\n const result = await transaction._executeRaw<ForeignKeyCheckRow>(\n \"PRAGMA foreign_key_check;\"\n );\n if (result.rows.length === 0) {\n return;\n }\n\n const offenders = [\n ...new Set(\n result.rows.map(\n (row) => `${String(row.table)} -> ${String(row.parent ?? \"?\")}`\n )\n ),\n ];\n throw new MigrationError(\n `Migration left ${result.rows.length} row(s) violating a foreign key (${offenders.join(\", \")}); rolled back.`,\n VibORMErrorCode.MIGRATION_FAILED\n );\n}\n","/**\n * The ONE pinned migration session (§3.5): one physical producer reserved for\n * a command, the lock proven on it, its loss and limits tracked, and the\n * producer condemned whenever a lock or unlock proof fails. PostgreSQL and\n * SQLite hold the lock in their transactions instead (plans D1, S5); only\n * PostgreSQL stepwise work, PlanetScale's Neki (the whole command) and MySQL\n * keep a session lock. The dialect's lock and session statements come from\n * the bound migration driver.\n */\n\nimport type {\n AnyDriver,\n MigrationFrame,\n MigrationFrameDriver,\n} from \"../drivers/driver\";\nimport { normalizeDriverError } from \"../drivers/error-mapping\";\nimport {\n createExecutionContext,\n snapshotExecutionContext,\n} from \"../drivers/execution-context\";\nimport {\n CLEANUP_BOUND_MS,\n leasePinnedCommand,\n type PinnedSessionControl,\n type PinnedSessionReservation,\n} from \"../drivers/shared/pinned-session\";\nimport { settleWithin } from \"../drivers/shared/settle\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport type { TransactionOptionSupport } from \"../drivers/shared/transaction-options\";\nimport { runTransactionLifecycle } from \"../drivers/shared/transactions\";\nimport type { BatchQuery, QueryExecutionContext } from \"../drivers/types\";\nimport {\n ConnectionError,\n type DiagnosticDisclosure,\n FeatureNotSupportedError,\n MigrationError,\n VibORMError,\n VibORMErrorCode,\n} from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ResolvedExtensionChain } from \"../extensions/chain\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { providerFacts, providerRefused } from \"./execute-dispatch\";\nimport { liftForeignKeyPragmas, withForeignKeysLifted } from \"./foreign-keys\";\nimport {\n DEFAULT_MIGRATION_LIMITS,\n type ResolvedMigrationLimits,\n} from \"./limits\";\nimport { runsConcurrently } from \"./statement-safety\";\nimport { type CatalogRead, readsCommandNamespace } from \"./target\";\nimport { createQueryExecutor } from \"./utils\";\n\n/**\n * The migration lock's key, \"viborm\" in hex. PostgreSQL's advisory lock is\n * database-wide, so estates in one database serialize with each other; MySQL\n * names its lock after the database instead (`drivers/mysql/pinned-session.ts`).\n */\nconst MIGRATION_LOCK_ID = 0x76_69_62_6f_72_6d;\n/**\n * The first pause between two PostgreSQL lock tries, doubled up to the cap. A\n * longer cap sends fewer tries but lets newcomers take a freed lock first: at\n * 1 s, waits under contention stretched to `lockWait`.\n */\nconst LOCK_RETRY_MS = 50;\nconst LOCK_RETRY_CAP_MS = 250;\n\n/**\n * A condition true while no command holds the migration lock (plan D5), for a\n * decision read before the lock.\n */\nexport function migrationLockFree(command: BoundMigrationDriver): string {\n return command.generateLockFree(MIGRATION_LOCK_ID);\n}\n\n/**\n * Whether this driver can pin a session: the provider's `pinnedSession()`\n * hook is the capability, asked by admission before any provider work.\n */\nexport function canPinSession(driver: AnyDriver): boolean {\n return driver[\"pinnedSession\"] !== undefined;\n}\n\n/**\n * Whether `driver` runs migration work with no session, one atomic request per\n * transactional group (plan D7): Neon HTTP is the shipped case.\n */\nexport function runsMigrationBatches(driver: AnyDriver): boolean {\n return (\n driver.dialect === \"postgresql\" &&\n !canPinSession(driver) &&\n driver.supportsBatch &&\n driver.supportsOrderedCommittedSegments\n );\n}\n\n/**\n * One transactional group as ONE request on a transport with no session\n * (plan D7). Statements sent to `producer` are recorded, not run; the request\n * opens with the limits and the bounded transaction lock, and what the command\n * would read inside its transaction is asserted there instead.\n */\nexport interface MigrationBatch {\n readonly producer: AnyDriver;\n /** `condition`, SQL with its own `$n` parameters, holds here, else `refusal` is the command's failure. */\n assert(\n condition: string,\n params: readonly unknown[],\n refusal: MigrationError\n ): void;\n /**\n * Resolves once the request committed, even when its reply was then\n * unreadable. Throws a `MigrationError` when the server refused (and rolled\n * back) the request; any other failure is a lost reply, after which the\n * request may have committed.\n */\n send(): Promise<void>;\n}\n\n/**\n * An assertion's refusal leaves its SQLSTATE (`P0V` + its position in base 36)\n * in a transaction-local setting, which this block raises: the SQLSTATE\n * survives diagnostics redaction where the message does not.\n */\nconst RAISE_REFUSAL = `DO $viborm$BEGIN IF current_setting('viborm.refusal') <> '' THEN RAISE EXCEPTION 'VibORM migration assertion %', current_setting('viborm.refusal') USING ERRCODE = current_setting('viborm.refusal'); END IF; END$viborm$`;\nconst REFUSAL = /^P0V([0-9A-Z]{2})$/;\n\nexport function openMigrationBatch(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): MigrationBatch {\n const queries: BatchQuery[] = [\n { sql: postgresSessionLimits(migrationDriver.limits).t },\n ];\n const refusals: MigrationError[] = [];\n const producer: AnyDriver = Object.create(driver);\n Object.defineProperty(producer, \"_executeRaw\", {\n value: (sql: string, params?: unknown[]) => {\n queries.push({ sql, params });\n return Promise.resolve({ rows: [], rowCount: 0 });\n },\n });\n const batch: MigrationBatch = {\n producer,\n assert(condition, params, refusal) {\n queries.push(\n {\n sql: `SELECT set_config('viborm.refusal', CASE WHEN ${condition} THEN '' ELSE 'P0V${refusals.length.toString(36).toUpperCase().padStart(2, \"0\")}' END, true)`,\n params: [...params],\n },\n { sql: RAISE_REFUSAL }\n );\n refusals.push(refusal);\n },\n async send() {\n let committed = false;\n try {\n await driver._executeBatch(queries, undefined, undefined, () => {\n committed = true;\n return Promise.resolve();\n });\n } catch (failure) {\n if (committed) return;\n if (!providerRefused(failure)) throw failure;\n const position = REFUSAL.exec(String(failure.meta.providerSqlState));\n const refusal = position && refusals[Number.parseInt(position[1]!, 36)];\n if (refusal) throw refusal;\n throw new MigrationError(\n \"Server refused migration request; rolled back.\",\n VibORMErrorCode.MIGRATION_FAILED,\n {\n cause: failure,\n meta: { providerSqlState: failure.meta.providerSqlState },\n }\n );\n }\n },\n };\n batch.assert(\n `(SELECT acquired FROM (${migrationDriver.generateAcquireLock(MIGRATION_LOCK_ID)}) AS lock)`,\n [],\n lockNotConfirmed(migrationDriver)\n );\n return batch;\n}\n\n/**\n * What a pinned session runs under besides its body (plan S1): the bound on\n * its reservation, the PostgreSQL command's limits, and, for a driver whose\n * one connection IS the session (SQLite), that session.\n */\nexport interface PinnedSessionScope {\n readonly connectionWait: number;\n readonly limits?: PostgresSessionLimits | undefined;\n readonly session?: () => Promise<PinnedSessionReservation<unknown>>;\n /** The command's `diagnostics`, disclosed by every statement of the session. */\n readonly diagnostics?: DiagnosticDisclosure | undefined;\n}\n\n/** The statements that impose, lift and reset one PostgreSQL session's limits. */\ninterface PostgresSessionLimits {\n readonly s: string;\n e(present: readonly string[]): string;\n x(present: readonly string[]): readonly string[];\n readonly t: string;\n readonly u: string;\n readonly r: string;\n}\n\nconst DEFAULT_SCOPE: PinnedSessionScope = {\n connectionWait: DEFAULT_MIGRATION_LIMITS.connectionWait,\n};\n\nasync function resetSessionLimits(\n driverName: string,\n control: SessionControl,\n limits: PostgresSessionLimits | undefined,\n execute: (sql: string) => Promise<unknown>,\n throwOnFailure: boolean\n): Promise<unknown> {\n const present = control.ld();\n if (limits === undefined || present === undefined || control.lost()) {\n return undefined;\n }\n try {\n for (const statement of limits.x(present)) {\n await control.cleanup(() => execute(statement));\n }\n return undefined;\n } catch (failure) {\n const lostConnection = control.lost(failure, true);\n control.ab();\n const surfaced = lostConnection\n ? failure\n : limitsRefused(driverName, \"reset\", failure);\n if (throwOnFailure) throw surfaced;\n return surfaced;\n }\n}\n\nexport async function withPinnedSession<D extends AnyDriver, T>(\n driver: D,\n body: (pinned: D, control: SessionControl) => Promise<T>,\n scope: PinnedSessionScope = DEFAULT_SCOPE\n): Promise<T> {\n const reserve = scope.session ?? driver[\"pinnedSession\"];\n if (reserve === undefined) {\n // A custom driver with no hook, or a view that IS a reserved session\n // (`createPinnedSessionView` withdraws the hook); admission refuses the\n // shipped paths earlier.\n throw new FeatureNotSupportedError(\n driver.driverName,\n \"pinnedSession\",\n \"No interactive session available on this driver.\"\n );\n }\n\n const runSession = async (): Promise<T> => {\n // A server that accepts the socket and never answers is bounded here.\n const reservation = await settleWithin(\n reserve.call(driver),\n scope.connectionWait,\n () => connectionWaitError(driver.driverName, scope.connectionWait),\n (late) => {\n late.release(true).catch(() => undefined);\n }\n );\n const control = controlSession(driver, reservation);\n const { limits } = scope;\n const view = createPinnedSessionView(\n driver,\n reservation.session,\n control,\n limits,\n scope.diagnostics\n );\n\n // Converted only when the failure IS the loss: a failure the command hit\n // first, whose cleanup then went unanswered, stays primary.\n const surface = (failure: unknown): unknown =>\n control.lost(failure, true)\n ? connectionLostError(driver.driverName, failure)\n : failure;\n\n const resetLimits = () =>\n resetSessionLimits(\n driver.driverName,\n control,\n limits,\n (statement) => view._executeRaw(statement),\n false\n );\n\n // The first failure stays primary; later ones are recorded beside it.\n const releaseAfter = async (\n surfaced: unknown,\n resetFailure: unknown\n ): Promise<unknown> => {\n let failure =\n resetFailure === undefined\n ? surfaced\n : withSuppressedFailure(surfaced, resetFailure);\n try {\n await reservation.release(true, control.lost());\n } catch (releaseFailure) {\n failure = withSuppressedFailure(failure, releaseFailure);\n }\n return failure;\n };\n\n let value: T;\n try {\n value = await body(view, control);\n } catch (bodyFailure) {\n // Surfaced first: it is what tells the reset the session is lost.\n throw await releaseAfter(surface(bodyFailure), await resetLimits());\n }\n const resetFailure = await resetLimits();\n if (resetFailure !== undefined) {\n throw await releaseAfter(surface(resetFailure), undefined);\n }\n // Nothing else failed, so a release failure IS the failure.\n await reservation.release(control.dd(), false);\n return value;\n };\n\n // A dedicated connection needs no lease: the real lock arbitrates.\n if (!driver[\"serializeTransactions\"]) {\n return runSession();\n }\n // A single-connection driver runs the whole session as ONE job of its queue\n // (§3.5): a narrower lease lets a second command in, and a PostgreSQL\n // session advisory lock is reentrant. A transaction-bound caller is refused\n // before the lease rather than waiting on its own holder.\n driver[\"assertPinnedSessionAllowed\"]();\n const queue = driver[\"connectionQueue\"];\n const identify = driver[\"physicalPinnedSession\"];\n if (identify === undefined) {\n return queue.enqueue(runSession);\n }\n // The physical lease keeps ANOTHER driver over the same client out, and\n // refuses one whose advisory-lock state was condemned.\n const session = await identify.call(driver);\n return leasePinnedCommand(driver.driverName, session, () =>\n queue.enqueue(runSession)\n );\n}\n\n/** The control of one reserved session, and what it knows about its connection. */\ninterface SessionControl extends PinnedSessionControl {\n dd(): boolean;\n lost(failure?: unknown, reported?: boolean): boolean;\n ab(): void;\n lm(present: readonly string[]): void;\n ld(): readonly string[] | undefined;\n}\n\nfunction controlSession(\n driver: AnyDriver,\n reservation: PinnedSessionReservation<unknown>\n): SessionControl {\n let discarded = false;\n let lost = false;\n let limited: readonly string[] | undefined;\n return {\n discard: () => {\n discarded = true;\n },\n dd: () => discarded,\n ab: () => {\n lost = true;\n },\n lm: (present: readonly string[]) => {\n limited = present;\n },\n ld: () => limited,\n lost: (failure?: unknown, reported = false) => {\n const reports =\n reservation.lost?.() !== undefined ||\n reportsLostConnection(driver, failure);\n lost ||= reports;\n return reported ? reports : lost;\n },\n cleanup: <R>(run: () => Promise<R>) =>\n settleWithin(run(), CLEANUP_BOUND_MS, () => {\n lost = true;\n return new ConnectionError(\n `Pinned session cleanup timed out on \"${driver.driverName}\" (${CLEANUP_BOUND_MS}ms).`,\n {\n code: VibORMErrorCode.CONNECTION_TIMEOUT,\n meta: { driver: driver.driverName, operation: \"pinnedSession\" },\n }\n );\n }),\n };\n}\n\n/**\n * Whether `failure`, or anything it was caused by, is the provider reporting\n * that the connection itself failed, by the driver error mapping's one\n * classifier.\n */\nfunction reportsLostConnection(driver: AnyDriver, failure: unknown): boolean {\n let link: unknown = failure;\n for (let depth = 0; depth < 8 && link instanceof Error; depth += 1) {\n const normalized =\n link instanceof VibORMError\n ? link\n : normalizeDriverError(link, {\n driverName: driver.driverName,\n dialect: driver.dialect,\n });\n if (normalized instanceof ConnectionError) return true;\n link = link.cause;\n }\n return false;\n}\n\n/**\n * The failure a command on a lost session surfaces: the provider's own report\n * when it already is a connection error or a migration outcome, otherwise a\n * retryable connection error carrying it (pg reports a dead socket as an\n * ordinary query failure).\n */\nfunction connectionLostError(driverName: string, failure: unknown): unknown {\n if (failure instanceof ConnectionError || failure instanceof MigrationError) {\n return failure;\n }\n return new ConnectionError(\n `Pinned migration session lost on \"${driverName}\"; retry under lock.`,\n {\n code: VibORMErrorCode.CONNECTION_FAILED,\n cause: errorCause(failure),\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\nfunction connectionWaitError(driverName: string, ms: number): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" timed out acquiring migration session (${ms}ms).`,\n {\n code: VibORMErrorCode.CONNECTION_TIMEOUT,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * A chain of no extension that carries the client's `disclosure` alone: a\n * driver discloses a failure as the client would, and this one has no\n * observer, transform or row scope of the client's to bring.\n */\nfunction disclosingChain(\n disclosure: DiagnosticDisclosure\n): ResolvedExtensionChain {\n return { extensions: [], disclosure };\n}\n\n/**\n * This driver, viewed with its client pinned to one reserved session: the\n * same driver in every other respect, with the transport assertion forwarded\n * exactly. Every statement it sends records a lost connection (plan S2).\n */\nfunction createPinnedSessionView<D extends AnyDriver>(\n driver: D,\n session: unknown,\n control: PinnedSessionControl,\n limits: PostgresSessionLimits | undefined,\n diagnostics: DiagnosticDisclosure | undefined\n): D {\n const view: D = Object.create(driver);\n // The session's statements, its transactions' included, disclose failures\n // as the command's client does: only its `diagnostics`, not its chain.\n if (diagnostics !== undefined) {\n Object.defineProperty(view, \"_bc\", {\n value: snapshotExecutionContext(\n createExecutionContext({}, undefined, disclosingChain(diagnostics)),\n driver._bc\n ),\n });\n }\n const support = driver[\"transactionOptionSupport\"]();\n const executeRaw = driver[\"executeRaw\"];\n const beforeForeignKeysOff = driver[\"beforeForeignKeysOff\"];\n Object.defineProperties(view, {\n client: { value: session, writable: true },\n // A pinned view must never start a second connection.\n initPromise: { value: null, writable: true },\n // The view IS the queue's serialized job: waiting on the queue would wait\n // for its own holder.\n serializeTransactions: { value: false },\n // The view is the reservation, so it has none to give (§3.5): a nested\n // lock refuses instead of taking a second connection.\n pinnedSession: { value: undefined },\n // The provider's own `transaction()` acquires a connection.\n transaction: {\n value(\n this: AnyDriver,\n pinned: unknown,\n fn: (tx: unknown) => Promise<unknown>,\n context?: QueryExecutionContext\n ) {\n return runPinnedTransaction(this, pinned, fn, context, control, limits);\n },\n },\n executeRaw: {\n async value(\n this: AnyDriver,\n client: unknown,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ) {\n if (control.lost())\n throw connectionLostError(driver.driverName, undefined);\n const locked = LOCKED.get(this);\n await locked?.b(sql);\n const send = (statement: string, parameters?: unknown[]) =>\n executeRaw.call(this, client, statement, parameters, context);\n const run = async () => {\n try {\n if (limits === undefined || !runsConcurrently(sql)) {\n return await send(sql, params);\n }\n await send(limits.u);\n const result = await send(sql, params);\n await send(limits.r);\n return result;\n } catch (failure) {\n control.lost(failure);\n throw failure;\n }\n };\n try {\n return await run();\n } catch (failure) {\n if (locked === undefined) throw failure;\n return await locked.x(failure);\n }\n },\n },\n transactionOptionSupport: {\n value: (): TransactionOptionSupport =>\n support.maxWait === \"queue\"\n ? {\n ...support,\n maxWait: \"unsupported\",\n maxWaitReason: \"pinned session holds connection queue\",\n }\n : support,\n },\n migrationNamespaceAttestation: {\n value: driver.migrationNamespaceAttestation,\n },\n beforeForeignKeysOff: {\n async value(this: AnyDriver) {\n await LOCKED.get(this)?.t();\n await beforeForeignKeysOff?.call(this);\n },\n },\n });\n return view;\n}\n\nfunction runPinnedTransaction<T>(\n view: AnyDriver,\n session: unknown,\n fn: (tx: unknown) => Promise<T>,\n context: QueryExecutionContext | undefined,\n control: PinnedSessionControl,\n limits: PostgresSessionLimits | undefined\n): Promise<T> {\n const locked = LOCKED.get(view)?.g(() => fn(session));\n if (locked !== undefined) return locked;\n const statement = (sql: string) =>\n view[\"executeRaw\"](session, sql, undefined, context);\n return runTransactionLifecycle({\n begin: () => statement(\"BEGIN\"),\n callback: async () => {\n if (limits !== undefined) await statement(limits.t);\n return fn(session);\n },\n commit: () => statement(\"COMMIT\"),\n rollback: () =>\n control.lost() ? undefined : control.cleanup(() => statement(\"ROLLBACK\")),\n });\n}\n\n/**\n * Runs `body` on ONE reserved producer holding this estate's migration lock,\n * with the migration driver THIS command renders from (§5.2).\n *\n * MySQL holds a session lock for the whole command, and so does PostgreSQL\n * where the server mixes no session and transaction advisory locks\n * (`holdsSessionLock`, PlanetScale's Neki); PostgreSQL and SQLite otherwise\n * run it in locked transactions ({@link lockTransactions}); a batch transport\n * locks each request (plan D7). `unlocked` (PostgreSQL) runs first, before any\n * lock, for a decision one statement proves while no command holds the lock\n * (plan D5); a failure that is not the lost connection only means it could not\n * decide. It is not asked where the session lock is held alone: its proof\n * takes the transaction lock.\n */\nexport function withLockedMigrationProducer<T>(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n body: (pinned: AnyDriver, command: BoundMigrationDriver) => Promise<T>,\n unlocked?: (session: AnyDriver, lockFree: string) => Promise<T | undefined>\n): Promise<T> {\n const { dialect } = migrationDriver.target;\n const limits = migrationDriver.limits;\n const run = async (producer: AnyDriver) =>\n body(\n producer,\n await validateAndSelectMigrationTarget(producer, migrationDriver)\n );\n if (migrationDriver.holdLock)\n return migrationDriver.holdLock(driver, limits.lockWait, () => run(driver));\n const lockFree = migrationLockFree(migrationDriver);\n const scope: PinnedSessionScope = {\n connectionWait: limits.connectionWait,\n diagnostics: migrationDriver.diagnostics,\n limits:\n dialect === \"postgresql\" ? postgresSessionLimits(limits) : undefined,\n session:\n dialect === \"sqlite\"\n ? async () => ({\n session: await driver[\"getClient\"]({ operation: \"pinnedSession\" }),\n release: () => Promise.resolve(),\n })\n : undefined,\n };\n if (runsMigrationBatches(driver)) {\n return (async () => {\n const answer = await unlocked?.(driver, lockFree).catch(() => undefined);\n if (answer !== undefined) return answer;\n return run(driver);\n })();\n }\n if (dialect === \"mysql\") {\n return withPinnedSession(\n driver,\n async (pinned, control) => {\n // A lock never proven is not this session's to release (§3.5).\n await acquireLock(pinned, migrationDriver, control);\n let result: T;\n try {\n result = await run(pinned);\n } catch (error) {\n await releaseAfterFailure(pinned, migrationDriver, control, error);\n throw error;\n }\n await releaseLock(pinned, migrationDriver, control);\n return result;\n },\n scope\n );\n }\n return withPinnedSession(\n driver,\n async (pinned, control) => {\n // PlanetScale's Neki holds the session lock alone, for the whole\n // command; its decision is read under that lock, never before it.\n const holdsSession =\n dialect === \"postgresql\" &&\n (await migrationDriver.holdsSessionLock((sql, params) =>\n pinned._executeRaw(sql, params)\n ));\n try {\n const answer = holdsSession\n ? undefined\n : await unlocked?.(pinned, lockFree);\n if (answer !== undefined) return answer;\n } catch (failure) {\n if (control.lost(failure)) throw failure;\n }\n // An admitted SQLite driver without transactions runs under the\n // driver's queue lease alone.\n if (!pinned.supportsTransactions) return run(pinned);\n const locked = lockTransactions(\n pinned,\n migrationDriver,\n control,\n scope.limits\n );\n LOCKED.set(pinned, locked);\n let result: T;\n try {\n if (holdsSession) await locked.h();\n result = await run(pinned);\n } catch (error) {\n await locked.a(error);\n throw error;\n }\n await locked.f();\n return result;\n },\n scope\n );\n}\n\ninterface LockedTransactions {\n b(sql: string): Promise<void>;\n x(failure: unknown): Promise<never>;\n g<T>(fn: () => Promise<T>): Promise<T> | undefined;\n w(): void;\n h(): Promise<void>;\n t(): Promise<void>;\n l(): Promise<void>;\n c(): boolean;\n f(): Promise<void>;\n a(cause: unknown): Promise<void>;\n}\n\nconst LOCKED = new WeakMap<object, LockedTransactions>();\n\n/**\n * A frame from the driver the capability says opens them. A declaration that\n * claims frames without the hook would lock nothing, so it is refused here,\n * before the command's first statement.\n */\nfunction openFrame(driver: AnyDriver): Promise<MigrationFrame> {\n if (!opensFrames(driver))\n throw new MigrationError(\n `SQLite driver \"${driver.driverName}\" declares exclusion \"frame\" without openMigrationFrame().`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { driver: driver.driverName } }\n );\n return driver.openMigrationFrame();\n}\nconst opensFrames = (\n driver: AnyDriver\n): driver is AnyDriver & MigrationFrameDriver =>\n typeof Reflect.get(driver, \"openMigrationFrame\") === \"function\";\n\n/** The switch SQLite ignores inside a transaction; its read form runs anywhere. */\nconst FOREIGN_KEYS_SWITCH = /^\\s*PRAGMA\\s+foreign_keys\\s*=/i;\n\nfunction lockTransactions(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: SessionControl,\n limits: PostgresSessionLimits | undefined\n): LockedTransactions {\n const sqlite = migrationDriver.target.dialect === \"sqlite\";\n // `exclusion: \"frame\"`: the driver's platform transaction is the lock, and\n // it stands where the statements below would be sent.\n const frames =\n migrationDriver.sqliteMigrationCapability?.exclusion === \"frame\";\n // The protocol's own statements, on the same session, past `before`.\n const direct: AnyDriver = Object.create(pinned);\n const run = <T = Record<string, unknown>>(sql: string) =>\n direct._executeRaw<T>(sql);\n let frame: MigrationFrame | undefined;\n const end = async (outcome: \"commit\" | \"rollback\"): Promise<void> => {\n if (frame === undefined) {\n await run(outcome === \"commit\" ? \"COMMIT\" : \"ROLLBACK\");\n return;\n }\n const settled = frame;\n frame = undefined;\n await settled[outcome]();\n };\n let open = false;\n let sessionLocked = false;\n // Held from the command's start (`hold`): each committed group still ends\n // `continuous`, so every group re-reads the marker as one under\n // transaction locks does, and Neki's split parts prove their attempt.\n let heldAlone = false;\n let armed = false;\n let continuous = true;\n let grouped = false;\n\n const rollback = async (): Promise<void> => {\n if (!open) return;\n open = false;\n continuous &&= sessionLocked && !heldAlone;\n // A frame is the driver's own pending transaction, not a statement on the\n // connection: left unsettled, it would hold every later statement.\n if (control.lost() && frame === undefined) return;\n await control.cleanup(() => end(\"rollback\"));\n };\n const commit = async (): Promise<void> => {\n await end(\"commit\");\n open = false;\n continuous &&= sessionLocked && !heldAlone;\n };\n // SQLite's lock IS its BEGIN IMMEDIATE: `lockWait` bounds that one\n // statement's busy wait, then the connection's own timeout is restored.\n // A frame has no wait to bound: the driver's queue lease is already held.\n const beginImmediate = async (): Promise<void> => {\n if (frames) {\n frame = await openFrame(direct);\n return;\n }\n const [own] = (await run<{ timeout: unknown }>(\"PRAGMA busy_timeout\")).rows;\n await run(`PRAGMA busy_timeout = ${migrationDriver.limits.lockWait}`);\n try {\n await run(\"BEGIN IMMEDIATE\");\n } finally {\n // Interpolated, so only an integer is written back.\n if (Number.isInteger(own?.timeout)) {\n await run(`PRAGMA busy_timeout = ${own?.timeout}`);\n }\n }\n };\n // A PostgreSQL transaction takes its limits and tries the lock in one\n // statement. A refused try waits outside any transaction, so the wait holds\n // no snapshot: another command's `CREATE INDEX CONCURRENTLY` under the\n // session lock would otherwise wait for this one to give up. Each jittered\n // pause doubles up to the cap and ends in one autocommit try, which lets go\n // of what it takes, until the lock is free or `lockWait` is spent.\n const lockFree = `${migrationLockFree(migrationDriver)} AS acquired`;\n const tryLock = sqlite ? null : `SELECT ${lockFree}`;\n const enter = limits === undefined ? tryLock : `${limits.t}, ${lockFree}`;\n // Each jittered pause doubles up to the cap; past `lockWait` the lock is\n // not held.\n const waiting = () => {\n const deadline = Date.now() + migrationDriver.limits.lockWait;\n let pause = LOCK_RETRY_MS;\n return async (): Promise<void> => {\n const left = deadline - Date.now();\n if (left <= 0) throw lockNotConfirmed(migrationDriver);\n const jittered = pause * (0.5 + Math.random() / 2);\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(left, jittered))\n );\n pause = Math.min(pause * 2, LOCK_RETRY_CAP_MS);\n };\n };\n const begin = async (): Promise<void> => {\n const wait = waiting();\n for (;;) {\n try {\n await (sqlite ? beginImmediate() : run(\"BEGIN\"));\n } catch (error) {\n // SQLite's lock IS its BEGIN IMMEDIATE: a busy database is a lock wait.\n if (!sqlite || control.lost(error)) throw error;\n throw lockStatementFailed(migrationDriver, error);\n }\n open = true;\n let held: boolean;\n try {\n held = await lockHeld(direct, migrationDriver, control, enter);\n } catch (error) {\n await rollback().catch((cleanup: unknown) => {\n throw withSuppressedFailure(error, cleanup);\n });\n throw error;\n }\n if (held) return;\n // Nothing was read under a lock never held: not a gap in `continuous`.\n open = false;\n await control.cleanup(() => end(\"rollback\"));\n do {\n await wait();\n } while (!(await lockHeld(direct, migrationDriver, control, tryLock)));\n }\n };\n const sessionLock = migrationDriver.generateSessionLock(MIGRATION_LOCK_ID);\n const imposeLimits = async (): Promise<void> => {\n if (limits === undefined) return;\n try {\n const { rows } = await run<{ name: unknown }>(limits.s);\n const present = rows.flatMap(({ name }) =>\n typeof name === \"string\" ? [name] : []\n );\n await run(limits.e(present));\n control.lm(present);\n } catch (failure) {\n if (control.lost(failure)) throw failure;\n throw limitsRefused(pinned.driverName, \"enter\", failure);\n }\n };\n const beginUnderSessionLock = async (): Promise<void> => {\n if (!sessionLocked) await hold();\n await run(\"BEGIN\");\n open = true;\n if (limits !== undefined) await run(limits.t);\n };\n const hold = async (): Promise<void> => {\n const wait = waiting();\n while (!(await lockHeld(direct, migrationDriver, control, sessionLock))) {\n await wait();\n }\n sessionLocked = true;\n heldAlone = true;\n await imposeLimits();\n };\n const escalate = async (): Promise<void> => {\n if (!open) await begin();\n await acquireLock(direct, migrationDriver, control, sessionLock);\n sessionLocked = true;\n armed = false;\n await imposeLimits();\n await commit();\n };\n\n const between = async (): Promise<void> => {\n if (open) await commit();\n };\n // No idle limit cuts the session, and no other command waits, while the\n // caller works; a refused reset leaves the limits on a session no one can\n // clean, which is abandoned.\n const letGo = async (): Promise<void> => {\n await between();\n if (!(heldAlone && sessionLocked)) return;\n await resetSessionLimits(pinned.driverName, control, limits, run, true);\n await releaseLock(direct, migrationDriver, control);\n sessionLocked = false;\n continuous = false;\n };\n const abort = async (cause: unknown): Promise<void> => {\n // A failure that IS the lost connection: nothing more is sent (plan S2).\n control.lost(cause);\n try {\n await rollback();\n } catch (cleanup) {\n throw withSuppressedFailure(cause, cleanup);\n }\n if (sessionLocked) {\n await releaseAfterFailure(direct, migrationDriver, control, cause);\n }\n };\n\n return {\n async x(failure) {\n if (!(sqlite || grouped || control.lost(failure))) {\n await rollback().catch((cleanup: unknown) => {\n throw withSuppressedFailure(failure, cleanup);\n });\n }\n throw failure;\n },\n async b(sql) {\n if (heldAlone && !sessionLocked) await hold();\n if (grouped || sessionLocked) return;\n if (sqlite && FOREIGN_KEYS_SWITCH.test(sql)) {\n await between();\n return;\n }\n if (!sqlite && (armed || runsConcurrently(sql))) {\n await escalate();\n return;\n }\n if (!open) await begin();\n },\n g(fn) {\n if (sessionLocked && !heldAlone) return undefined;\n return runTransactionLifecycle({\n begin: () => {\n if (open) return undefined;\n return heldAlone ? beginUnderSessionLock() : begin();\n },\n callback: async () => {\n grouped = true;\n try {\n return await fn();\n } finally {\n grouped = false;\n }\n },\n commit,\n rollback,\n });\n },\n w() {\n armed = true;\n },\n h: hold,\n t: between,\n l: letGo,\n c: () => continuous,\n async f() {\n if (open) {\n try {\n await commit();\n } catch (failure) {\n await abort(failure);\n throw failure;\n }\n }\n if (sessionLocked) await releaseLock(direct, migrationDriver, control);\n },\n a: abort,\n };\n}\n\nexport async function commitLockedTransaction(\n pinned: AnyDriver,\n command: BoundMigrationDriver\n): Promise<void> {\n if (command.target.dialect === \"postgresql\") {\n await LOCKED.get(pinned)?.t();\n }\n}\n\nexport async function letLockGo(pinned: AnyDriver): Promise<void> {\n await LOCKED.get(pinned)?.l();\n}\n\nexport function lockedSinceDecision(producer: AnyDriver): boolean {\n return LOCKED.get(producer)?.c() ?? true;\n}\n\nconst OPTIONAL_SESSION_SETTINGS = [\n \"idle_in_transaction_session_timeout\",\n \"idle_session_timeout\",\n \"client_connection_check_interval\",\n] as const;\n\nfunction postgresSessionLimits(\n limits: ResolvedMigrationLimits\n): PostgresSessionLimits {\n const bound = (lock: number, statement: number, local: boolean) =>\n `set_config('lock_timeout', '${lock}', ${local}), set_config('statement_timeout', '${statement}', ${local})`;\n const { lockTimeout, statementTimeout, idleTimeout } = limits;\n const set = (name: string, value: number) =>\n `, set_config('${name}', '${value}', false)`;\n const idleInTx = OPTIONAL_SESSION_SETTINGS[0];\n return {\n s: `SELECT name FROM pg_catalog.pg_settings WHERE name IN (${OPTIONAL_SESSION_SETTINGS.map((name) => `'${name}'`).join(\", \")}) AND pg_catalog.version() NOT LIKE '%emscripten%' ORDER BY name`,\n e: (present) => {\n const idle = OPTIONAL_SESSION_SETTINGS.slice(0, 2)\n .filter((name) => present.includes(name))\n .map((name) => set(name, idleTimeout))\n .join(\"\");\n const check = present.includes(\"client_connection_check_interval\")\n ? `\nBEGIN\nPERFORM set_config('client_connection_check_interval', '1000', false);\nEXCEPTION WHEN invalid_parameter_value THEN NULL;\nEND;`\n : \"\";\n return `DO $viborm_limits$BEGIN\nPERFORM ${bound(lockTimeout, statementTimeout, false)}${idle};${check}\nEND$viborm_limits$`;\n },\n x: (present) =>\n [\"lock_timeout\", \"statement_timeout\", ...present].map(\n (name) => `RESET ${name}`\n ),\n t: `SELECT ${bound(lockTimeout, statementTimeout, true)}, set_config('${idleInTx}', CASE WHEN pg_catalog.version() LIKE '%emscripten%' THEN pg_catalog.current_setting('${idleInTx}') ELSE '${idleTimeout}' END, true)`,\n u: `SELECT ${bound(0, 0, false)}`,\n r: `SELECT ${bound(lockTimeout, statementTimeout, false)}`,\n };\n}\n\n/**\n * The server refused to impose (`enter`) or reset (`reset`) the migration\n * session's limits: part of holding the session lock, so a lock failure\n * (V11005), named as itself rather than as the statement it preceded. A\n * session whose reset was refused is never returned to the pool.\n */\nfunction limitsRefused(\n driverName: string,\n step: \"enter\" | \"reset\",\n failure: unknown\n): MigrationError {\n return new MigrationError(\n `Driver \"${driverName}\": server refused to ${step === \"enter\" ? \"set\" : \"reset\"} session limits.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n {\n cause: errorCause(failure),\n meta: {\n driver: driverName,\n operation: \"pinnedSession\",\n ...providerFacts(failure),\n },\n }\n );\n}\n\n/**\n * Selects the live migration target on a pinned producer, if this dialect has\n * one: when the lock is taken and again before every relative artifact, since\n * a manual artifact may issue its own `USE` (§10).\n */\nexport async function selectMigrationTarget(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<void> {\n const statement = migrationDriver.generateSelectTarget();\n if (statement === null) {\n return;\n }\n await pinned._executeRaw(statement);\n}\n\n/**\n * §5.3's step 2, once per locked session: the namespace proof (§3.3), the\n * target selection, then the dialect's own proof of the session.\n */\nasync function validateAndSelectMigrationTarget(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<BoundMigrationDriver> {\n const command = await resolveCommandDriver(pinned, migrationDriver);\n await selectMigrationTarget(pinned, command);\n return command.proveSession((sql, params) => pinned._executeRaw(sql, params));\n}\n\n/**\n * The ONE owner of the migration driver a command renders from, after its\n * namespace proof (§5.2): on the dialect that resolves a command-local\n * spelling (MySQL), a frozen view carrying the server's own spelling, which\n * lives exactly as long as the command. Read-only commands reach it too.\n */\nexport async function resolveCommandDriver(\n producer: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<BoundMigrationDriver> {\n const read: CatalogRead = (sql, params) => producer._executeRaw(sql, params);\n if (!readsCommandNamespace(migrationDriver)) {\n await migrationDriver.proveNamespaceExists(read);\n return migrationDriver;\n }\n\n const spelling = await migrationDriver.resolveCommandNamespace(read);\n const command: BoundMigrationDriver = Object.create(migrationDriver);\n Object.defineProperty(command, \"namespace\", {\n value: spelling,\n enumerable: true,\n });\n Object.freeze(command);\n return command;\n}\n\n/**\n * Whether a group of `transactional` work runs in a transaction on this\n * producer: never on MySQL, nor without transactions. Asked of each group\n * right before it runs, which is where a PostgreSQL command hears of stepwise\n * work and takes the session lock it needs (plan D1).\n */\nexport function mayWrapTransaction(\n producer: Pick<AnyDriver, \"supportsTransactions\">,\n dialect: string,\n transactional: boolean\n): boolean {\n if (!transactional) LOCKED.get(producer)?.w();\n return transactional && dialect !== \"mysql\" && producer.supportsTransactions;\n}\n\n/**\n * Runs one program of a command, the one owner of how it runs: on MySQL as a\n * sequential program; else, given its `program`, in a transaction where\n * {@link mayWrapTransaction} admits one, SQLite's foreign-key pragmas lifted\n * around it (a recreation is refused where nothing can lift them), and\n * directly otherwise; without one, directly. `atomic` tells the body which.\n * Once a given program has committed, what it left building is waited for\n * (`awaitIndexBuilds`), the lock still held.\n * `phase` records how far a transaction got: past its body and checks\n * (`committing`), past its COMMIT (`committed`), for a caller that classifies\n * a failure at COMMIT (plan S3).\n */\nexport async function runProgram<T>(\n pinned: AnyDriver,\n command: BoundMigrationDriver,\n program:\n | {\n readonly transactional: boolean;\n readonly statements: string[];\n readonly phase?: { committing: boolean; committed: boolean };\n }\n | undefined,\n body: (producer: AnyDriver, atomic: boolean) => Promise<T>\n): Promise<T> {\n const { dialect } = command.target;\n if (dialect === \"mysql\") {\n return runSequentialProgram(pinned, command, (producer) =>\n body(producer, false)\n );\n }\n if (!program) return body(pinned, false);\n const { bracket } = liftForeignKeyPragmas(pinned, program.statements);\n // What the program builds in the background, once it has committed.\n const settle = () => command.awaitIndexBuilds?.(pinned, program.statements);\n // Neki refuses any statement after a schema change in its transaction:\n // the body's own ledger and marker writes run outside one.\n if (\n !mayWrapTransaction(\n pinned,\n dialect,\n program.transactional && !command.commitsSchemaChangesAlone()\n )\n ) {\n // A statement that fails leaves the ones before it committed, builds too:\n // they are waited for, and the statement's failure stays the one reported.\n const result = await body(pinned, false).catch(async (failure) => {\n await settle()?.catch((wait) => {\n throw withSuppressedFailure(failure, wait);\n });\n throw failure;\n });\n await settle();\n return result;\n }\n const { phase } = program;\n return withForeignKeysLifted(pinned, bracket, async (inside) => {\n const result = await pinned.withTransaction(async (transaction) => {\n const value = await inside(transaction, (producer) =>\n body(producer, true)\n );\n if (phase) phase.committing = true;\n return value;\n });\n if (phase) phase.committed = true;\n await settle();\n return result;\n });\n}\n\n/**\n * Runs a MySQL sequential program on `producer`, after the command's\n * `programPreamble`, and reports the boundary it reached (§6.2, §6.3): MySQL\n * commits DDL as each statement runs, so a failure part-way through is the\n * partial commit it is, recorded by the producer the body runs on.\n */\nexport async function runSequentialProgram<T>(\n producer: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n body: (recording: AnyDriver) => Promise<T>\n): Promise<T> {\n const preamble = await migrationDriver.programPreamble(producer);\n /** The last statement that RAN TO COMPLETION, which here IS committed. */\n let committed: string | undefined;\n const recording: AnyDriver = Object.create(producer);\n Object.defineProperty(recording, \"_executeRaw\", {\n value: async (sql: string, params?: unknown[]) => {\n const result = await producer._executeRaw(sql, params);\n committed = sql;\n return result;\n },\n });\n\n try {\n for (const statement of preamble) {\n await recording._executeRaw(statement);\n }\n return await body(recording);\n } catch (cause) {\n throw partialProgramFailure(cause, committed);\n }\n}\n\n/**\n * The honest report for a program that cannot be undone (§6.2, §6.3): the\n * last statement known to have completed, no claim of a rollback, and the\n * provider's failure as the cause.\n */\nfunction partialProgramFailure(\n cause: unknown,\n committed: string | undefined\n): MigrationError {\n return new MigrationError(\n `MySQL migration failed partway (not rolled back). Last completed: ${committed ?? \"(none)\"}.`,\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT,\n { cause: errorCause(cause), meta: providerFacts(cause) }\n );\n}\n\n/**\n * Acquires the lock and PROVES it. The target is selected after the lock\n * (§5.3), by the caller's scope that releases.\n */\nasync function acquireLock(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl,\n statement = migrationDriver.generateAcquireLock(MIGRATION_LOCK_ID)\n): Promise<void> {\n if (!(await lockHeld(pinned, migrationDriver, control, statement))) {\n throw lockNotConfirmed(migrationDriver);\n }\n}\n\n/** Runs one lock statement: whether the provider proved the lock held. */\nasync function lockHeld(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl,\n statement: string | null\n): Promise<boolean> {\n if (statement === null) {\n return true;\n }\n\n const executor = createQueryExecutor(pinned);\n let rows: unknown[];\n try {\n rows = await executor(statement);\n } catch (error) {\n // A lost connection is retryable, not a lock failure.\n if (control.lost(error)) throw error;\n throw lockStatementFailed(migrationDriver, error);\n }\n return migrationDriver.provesLockAcquired(rows);\n}\n\nfunction lockError(message: string, error?: unknown): MigrationError {\n return new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n error === undefined\n ? undefined\n : { cause: errorCause(error), meta: providerFacts(error) }\n );\n}\n\nfunction lockNotConfirmed(\n migrationDriver: BoundMigrationDriver\n): MigrationError {\n return lockError(\n `Migration lock not confirmed for ${describeEstate(migrationDriver)}.`\n );\n}\n\nfunction lockStatementFailed(\n migrationDriver: BoundMigrationDriver,\n error: unknown\n): MigrationError {\n return lockError(\n `Migration lock failed for ${describeEstate(migrationDriver)}.`,\n error\n );\n}\n\n/**\n * Releases the lock after the protected work FAILED: the release still runs\n * and its own failure is recorded beside `cause` (§3.5), never replacing it.\n * A lost session holds no lock to release (plan S2).\n */\nasync function releaseAfterFailure(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl,\n cause: unknown\n): Promise<void> {\n if (control.lost(cause)) return;\n try {\n await releaseLock(pinned, migrationDriver, control);\n } catch (releaseFailure) {\n throw withSuppressedFailure(cause, releaseFailure);\n }\n}\n\n/**\n * Releases the lock and PROVES the release, through the driver the command\n * was GIVEN (only it names the lock acquired); an unproven release condemns\n * the producer.\n */\nasync function releaseLock(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl\n): Promise<void> {\n const statement = migrationDriver.generateReleaseLock(MIGRATION_LOCK_ID);\n if (statement === null) {\n return;\n }\n\n const executor = createQueryExecutor(pinned);\n let rows: unknown[];\n try {\n rows = await control.cleanup(() => executor(statement));\n } catch (error) {\n control.discard();\n if (control.lost(error)) throw error;\n throw lockError(\n `Failed to release migration lock for ${describeEstate(migrationDriver)}; session discarded.`,\n error\n );\n }\n\n if (!migrationDriver.provesLockReleased(rows)) {\n control.discard();\n throw lockError(\n `Migration lock release not confirmed for ${describeEstate(migrationDriver)}; session discarded.`\n );\n }\n}\n\n/** The estate a lock failure is about. */\nfunction describeEstate(migrationDriver: BoundMigrationDriver): string {\n const { target } = migrationDriver;\n if (target.dialect === \"sqlite\") return \"the SQLite database\";\n if (target.dialect === \"surrealql\") return \"the SurrealDB database\";\n return target.dialect === \"postgresql\"\n ? `schema \"${target.namespace}\"`\n : `database \"${migrationDriver.namespace ?? \"(unbound)\"}\"`;\n}\n","import { readArrayLiteralText } from \"../adapters/databases/postgres/array-literal\";\nimport { sqliteGeoPointEncoding } from \"../adapters/databases/sqlite/storage/geo-point\";\nimport { decodeProviderTimestamp } from \"../validation/primitives/datetime-physical-codec\";\n/**\n * Live schema fingerprint and push target identity.\n *\n * The target identity names the database itself (dialect, database and\n * namespace), never a client instance: a consent previewed by one client is\n * replayed by any other on the same database, and the plan hash it carries\n * still binds it to the exact live fingerprint and statements. This module\n * hashes the snapshot it is given; callers strip control tables before\n * fingerprinting.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeJson, canonicalizeJsonText } from \"./canonical-json\";\nimport type { IndexPredicateCanonicalizer } from \"./differ\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"./drivers\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport { canPinSession, runsMigrationBatches } from \"./pinned-session\";\nimport type { IndexDef, SchemaSnapshot, TableDef, ViewDef } from \"./types\";\nimport { encodeSnapshot, omitUndefinedKeys } from \"./v1-parse-snapshot\";\nimport type { MarkerIndexPredicateV1, PushTargetIdentity } from \"./v1-types\";\n\nexport async function pushTargetIdentity(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PushTargetIdentity> {\n if (driver.target.dialect === \"postgresql\") {\n const result = await producer._executeRaw<{ database: unknown }>(\n \"SELECT current_database() AS database\"\n );\n const database = result.rows[0]?.database;\n if (typeof database !== \"string\" || database.length === 0) {\n throw new MigrationError(\n \"PostgreSQL did not return its current database identity\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n dialect: \"postgresql\",\n database,\n namespace: driver.namespace ?? driver.target.namespace,\n };\n }\n if (driver.target.dialect === \"mysql\") {\n if (!driver.namespace) {\n throw new MigrationError(\n \"MySQL push has no resolved database identity\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n dialect: \"mysql\",\n database: driver.namespace,\n };\n }\n return (\n (await driver.pushTarget?.((sql, params) =>\n producer._executeRaw(sql, params)\n )) ?? { dialect: \"sqlite\", location: null }\n );\n}\n\nexport function hashSnapshot(snapshot: SchemaSnapshot): Sha256 {\n return encodeSnapshot(snapshot).snapshotHash;\n}\n\nexport function bindIndexPredicateCanonicalizer(\n producer: AnyDriver,\n driver: MigrationDriver\n): IndexPredicateCanonicalizer | undefined {\n const canonicalize = driver.canonicalizeIndexPredicates;\n if (!canonicalize) return;\n return async (tableName, predicates) => {\n const run = (on: AnyDriver) =>\n canonicalize.call(\n driver,\n tableName,\n predicates,\n (sql, params) => on._executeRaw(sql, params),\n runsMigrationBatches(on)\n ? <T>(statements: readonly string[]) =>\n on._executeBatch<T>(statements.map((sql) => ({ sql })))\n : undefined\n );\n try {\n // Its scratch views exist only inside their transaction, so on a\n // pool, or behind a transaction pooler, its statements share one. A\n // locked command's pinned producer is already inside one (plan D1).\n // With no session at all, each pass is one request (plan D7).\n return await (canPinSession(producer) && producer.supportsTransactions\n ? producer.withTransaction(run)\n : run(producer));\n } catch {\n return predicates.map(() => undefined);\n }\n };\n}\n\nexport async function canonicalizeSnapshotPredicates(\n snapshot: SchemaSnapshot,\n canonicalize: IndexPredicateCanonicalizer | undefined\n): Promise<SchemaSnapshot> {\n if (!canonicalize) return snapshot;\n const tables: TableDef[] = [];\n for (const table of snapshot.tables) {\n const indexes = await canonicalIndexes(\n table.name,\n table.indexes,\n canonicalize\n );\n tables.push(indexes === table.indexes ? table : { ...table, indexes });\n }\n if (snapshot.views === undefined) return { ...snapshot, tables };\n // A materialized view's partial index is spelled by the database as a\n // table's is.\n const views: ViewDef[] = [];\n for (const view of snapshot.views) {\n const indexes =\n view.indexes &&\n (await canonicalIndexes(view.name, view.indexes, canonicalize));\n views.push(indexes === view.indexes ? view : { ...view, indexes });\n }\n return { ...snapshot, tables, views };\n}\n\n/** One relation's indexes, each partial one's predicate as the database spells it. */\nasync function canonicalIndexes(\n relation: string,\n indexes: IndexDef[],\n canonicalize: IndexPredicateCanonicalizer\n): Promise<IndexDef[]> {\n const pending = indexes.filter((index) => index.where);\n if (pending.length === 0) return indexes;\n const spellings = await canonicalize(\n relation,\n pending.map((index) => index.where!)\n );\n let next = 0;\n return indexes.map((index) => {\n if (!index.where) return index;\n const spelling = spellings[next++];\n return spelling === undefined ? index : { ...index, where: spelling };\n });\n}\n\nexport async function fingerprintLive(\n snapshot: SchemaSnapshot,\n driver: MigrationDriver,\n producer: AnyDriver\n): Promise<Sha256> {\n return fingerprintSnapshot(\n await canonicalizeSnapshotPredicates(\n snapshot,\n bindIndexPredicateCanonicalizer(producer, driver)\n ),\n driver\n );\n}\n\n/**\n * `fingerprintSnapshot` with each partial-index predicate as PostgreSQL\n * deparsed it, from the record beside the marker: what the catalog digest\n * hashes when it reads predicates as deparsed. `undefined` when the record\n * lacks one of them.\n */\nexport function fingerprintDeparsed(\n snapshot: SchemaSnapshot,\n predicates: readonly MarkerIndexPredicateV1[],\n driver: MigrationDriver\n): Sha256 | undefined {\n let recorded = true;\n // A materialized view's partial index is recorded under the view's name.\n const deparsed = <T extends { name: string; indexes?: IndexDef[] }>(\n relation: T\n ): T => ({\n ...relation,\n ...(relation.indexes && {\n indexes: relation.indexes.map((index) => {\n if (!index.where) return index;\n const where = predicates.find(\n (record) =>\n record.table === relation.name && record.index === index.name\n )?.deparsed;\n recorded &&= where !== undefined;\n return { ...index, where };\n }),\n }),\n });\n const tables = snapshot.tables.map(deparsed);\n const views = snapshot.views?.map(deparsed);\n return recorded\n ? fingerprintSnapshot(\n { ...snapshot, tables, ...(views ? { views } : {}) },\n driver\n )\n : undefined;\n}\n\nexport function fingerprintSnapshot(\n snapshot: SchemaSnapshot,\n driver: MigrationDriver\n): Sha256 {\n const tables = canonicalUniqueEntities(snapshot)\n .tables.map((table) => ({\n name: table.name,\n columns: table.columns\n .map((column) => ({\n name: column.name,\n type: normalizeType(column.type),\n nullable: column.nullable,\n default: normalizeDefault(column.default, column.type) ?? null,\n autoIncrement: column.autoIncrement ?? false,\n ...(sqliteGeoPointEncoding(column)\n ? { geoPointEncoding: sqliteGeoPointEncoding(column) }\n : {}),\n }))\n .sort(byName),\n primaryKey: table.primaryKey\n ? {\n columns: table.primaryKey.columns,\n ...(driver.dialect === \"postgresql\"\n ? { name: table.primaryKey.name || `${table.name}_pkey` }\n : {}),\n // Present only where set, so every other key hashes as before.\n ...(table.primaryKey.withoutRowid ? { withoutRowid: true } : {}),\n }\n : null,\n indexes: table.indexes.map(indexProjection).sort(byName),\n foreignKeys: table.foreignKeys\n .map((foreignKey) => ({\n name: driver.capabilities.introspectionReadsConstraintNames\n ? foreignKey.name\n : null,\n columns: foreignKey.columns,\n referencedTable: foreignKey.referencedTable,\n referencedColumns: foreignKey.referencedColumns,\n onDelete: foreignKey.onDelete ?? \"noAction\",\n onUpdate: foreignKey.onUpdate ?? \"noAction\",\n }))\n .sort(byCanonicalValue),\n uniqueConstraints: table.uniqueConstraints\n .map((constraint) => ({\n name: driver.capabilities.introspectionReadsConstraintNames\n ? constraint.name\n : null,\n columns: constraint.columns,\n }))\n .sort(byCanonicalValue),\n }))\n .sort(byName);\n const enums = [...(snapshot.enums ?? [])]\n .map((item) => ({ name: item.name, values: item.values }))\n .sort(byName);\n // A view is its name and hash, and a materialized one its kind and indexes\n // (which no hash holds); present only where one is, so a schema without a\n // view, or without a materialized one, keeps its fingerprint. A view kept\n // by triggers adds its indexes and the objects that keep it, which a hand\n // can drop.\n const views = [...(snapshot.views ?? [])]\n .map((view) => ({\n name: view.name,\n hash: view.hash,\n ...(view.materialized || view.auto\n ? {\n ...(view.materialized ? { materialized: true } : {}),\n indexes: (view.indexes ?? []).map(indexProjection).sort(byName),\n }\n : {}),\n ...(view.auto\n ? {\n auto: view.auto.objects.map(({ kind, name, table }) => ({\n kind,\n name,\n ...(table === undefined ? {} : { table }),\n })),\n }\n : {}),\n }))\n .sort(byName);\n return domainHash(\n HASH_DOMAIN.snapshot,\n canonicalizeJson(\n views.length > 0 ? { tables, enums, views } : { tables, enums }\n )\n );\n}\n\n/**\n * An index as the fingerprint hashes it. A raw index is its text: what the\n * database calls its method, its uniqueness or its predicate is the text's,\n * and the hash says it.\n */\nfunction indexProjection(index: IndexDef) {\n return index.raw\n ? { name: index.name, raw: index.raw.hash, columns: index.columns }\n : {\n name: index.name,\n columns: index.columns,\n unique: index.unique ?? false,\n type: index.type ?? \"btree\",\n where: index.where?.trim() || null,\n };\n}\n\n/** A total btree unique index and a unique constraint enforce the same key. */\nexport function canonicalUniqueEntities(\n snapshot: SchemaSnapshot\n): SchemaSnapshot {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) => ({\n ...table,\n uniqueConstraints: [\n ...table.uniqueConstraints,\n ...table.indexes\n .filter(\n (index) =>\n index.unique &&\n !index.where &&\n (!index.type || index.type === \"btree\")\n )\n .map((index) => ({ name: index.name, columns: index.columns })),\n ],\n indexes: table.indexes.filter(\n (index) =>\n !(\n index.unique &&\n !index.where &&\n (!index.type || index.type === \"btree\")\n )\n ),\n })),\n };\n}\n\nexport function normalizeType(type: string): string {\n const tokens =\n type.trim().match(/'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"|[^'\"]+/g) ?? [];\n return tokens\n .map((token) => {\n if (token.startsWith(\"'\") || token.startsWith('\"')) return token;\n return token\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .replace(/\\s*,\\s*/g, \",\")\n .replace(/\\s+\\[\\]/g, \"[]\")\n .replace(/\\bcharacter varying\\b/g, \"varchar\")\n .replace(/\\bcharacter\\b/g, \"char\")\n .replace(/\\bbit varying\\b/g, \"varbit\")\n .replace(/\\btimestamptz(\\(\\d+\\))?/g, \"timestamp$1 with time zone\")\n .replace(/\\btimetz(\\(\\d+\\))?/g, \"time$1 with time zone\")\n .replace(/\\b(timestamp|time)(\\(\\d+\\))? without time zone/g, \"$1$2\")\n .replace(/\\bint4\\b/g, \"integer\")\n .replace(/\\bint8\\b/g, \"bigint\")\n .replace(/\\bint2\\b/g, \"smallint\")\n .replace(/\\bfloat4\\b/g, \"real\")\n .replace(/\\bfloat8\\b/g, \"double precision\")\n .replace(/\\bbool\\b/g, \"boolean\");\n })\n .join(\"\");\n}\n\nconst UTC_NOW_DEFAULT =\n /^(?:now\\(\\) at time zone 'utc'|timezone\\(\\s*'utc'\\s*,\\s*now\\(\\)\\s*\\))$/;\nconst MILLISECOND_NOW_DEFAULT =\n /^date_trunc\\(\\s*'milliseconds'\\s*,([\\s\\S]+)\\)$/;\nconst UTC_CURRENT_TIME_DEFAULT =\n /^timezone\\(\\s*'utc'\\s*,\\s*current_time(?:\\(3\\))?\\s*\\)$/;\nconst NUMERIC_PHYSICAL_TYPE =\n /^(integer|bigint|smallint|real|double precision|float|int|tinyint)/;\nconst INTEGER_PHYSICAL_TYPE = /^(integer|bigint|smallint|int|tinyint)/;\nconst INTEGER_LITERAL = /^[-+]?\\d+$/;\nconst TEMPORAL_PHYSICAL_TYPE = /^(timestamp|time|date)/;\nconst ISO_UTC_SUFFIX = /Z$/;\nconst TEMPORAL_UTC_SUFFIX = /(?:Z|[+]00(?::00)?)$/;\nconst MINUTE_CLOCK_SUFFIX = /(^| )(\\d{2}:\\d{2})(?=$|[+-])/;\nconst TRAILING_FRACTION_ZEROES = /(\\.\\d*?)0+(?=$|[+-])/;\nconst EMPTY_FRACTION = /\\.(?=$|[+-])/;\nconst BARE_FUNCTION_DEFAULT = /^[a-z_][a-z0-9_]*\\(\\)$/;\nconst NUMBER_LITERAL = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n\nfunction stripDefaultParentheses(value: string): string {\n let text = value.trim();\n while (text.startsWith(\"(\") && text.endsWith(\")\")) {\n const structural = text.replace(\n /'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"/g,\n (literal) => \" \".repeat(literal.length)\n );\n let depth = 0;\n let whole = true;\n for (let index = 0; index < structural.length; index++) {\n if (structural[index] === \"(\") depth++;\n else if (structural[index] === \")\") depth--;\n if (depth === 0 && index < structural.length - 1) {\n whole = false;\n break;\n }\n }\n if (!whole || depth !== 0) break;\n text = text.slice(1, -1).trim();\n }\n return text;\n}\n\nexport function normalizeDefault(\n value: string | undefined,\n type?: string\n): string | undefined {\n if (value === undefined) return;\n const spelling = stripDefaultParentheses(value);\n const normalized = spelling.toLowerCase();\n if (normalized === \"null\") return;\n const utcNow = normalized\n .replaceAll(\"::text\", \"\")\n .replaceAll(\"current_timestamp\", \"now()\");\n if (UTC_NOW_DEFAULT.test(utcNow)) return \"now() at time zone 'utc'\";\n const truncated = MILLISECOND_NOW_DEFAULT.exec(utcNow);\n if (truncated?.[1]) {\n const clock = normalizeDefault(truncated[1], type);\n if (clock === \"now()\" || clock === \"now() at time zone 'utc'\")\n return `date_trunc('milliseconds',${clock})`;\n }\n if (UTC_CURRENT_TIME_DEFAULT.test(utcNow))\n return utcNow.includes(\"current_time(3)\")\n ? \"timezone('utc',current_time(3))\"\n : \"timezone('utc',current_time)\";\n if (normalized === \"current_timestamp\" || normalized === \"now()\")\n return \"now()\";\n const boolean = type === undefined || normalizeType(type) === \"boolean\";\n if (\n boolean &&\n (normalized === \"true\" || normalized === \"'t'\" || normalized === \"1\")\n )\n return \"true\";\n if (\n boolean &&\n (normalized === \"false\" || normalized === \"'f'\" || normalized === \"0\")\n )\n return \"false\";\n if (BARE_FUNCTION_DEFAULT.test(normalized)) return normalized;\n const unquoted =\n normalized.startsWith(\"'\") && normalized.endsWith(\"'\")\n ? normalized.slice(1, -1)\n : normalized;\n const physical = type === undefined ? \"\" : normalizeType(type);\n if (spelling.startsWith(\"'\") && spelling.endsWith(\"'\")) {\n const literal = spelling.slice(1, -1).replaceAll(\"''\", \"'\");\n if (physical.endsWith(\"[]\")) {\n const values = readArrayLiteralText(literal);\n if (values)\n return canonicalizeJsonText(\n values.map((value) =>\n value === null\n ? null\n : normalizeDefault(\n `'${(physical.slice(0, -2) === \"boolean\" && (value === \"t\" || value === \"f\") ? (value === \"t\" ? \"true\" : \"false\") : value).replaceAll(\"'\", \"''\")}'`,\n physical.slice(0, -2)\n )\n )\n );\n }\n if (physical === \"json\" || physical === \"jsonb\") {\n try {\n return canonicalizeJsonText(JSON.parse(literal));\n } catch {\n /* A SQL expression is not a JSON document literal. */\n }\n }\n }\n if (NUMERIC_PHYSICAL_TYPE.test(physical) && NUMBER_LITERAL.test(unquoted)) {\n // BigInt keeps integer columns exact; a float catalog spells 1e21 as\n // '1000000000000000000000', which only Number() reads back as 1e+21.\n return INTEGER_PHYSICAL_TYPE.test(physical) &&\n INTEGER_LITERAL.test(unquoted)\n ? BigInt(unquoted).toString()\n : String(Number(unquoted));\n }\n if (\n TEMPORAL_PHYSICAL_TYPE.test(physical) &&\n spelling.startsWith(\"'\") &&\n spelling.endsWith(\"'\")\n ) {\n let temporal = spelling\n .slice(1, -1)\n .replace(\"T\", \" \")\n .replace(ISO_UTC_SUFFIX, \"+00:00\");\n const era = temporal.endsWith(\" BC\") ? \" BC\" : \"\";\n if (era) temporal = temporal.slice(0, -3);\n if (\n physical.includes(\"with time zone\") &&\n physical.startsWith(\"timestamp\")\n ) {\n const instant = decodeProviderTimestamp(`${temporal}${era}`);\n if (instant) return instant.toISOString();\n }\n temporal = temporal\n .replace(TEMPORAL_UTC_SUFFIX, \"\")\n .replace(MINUTE_CLOCK_SUFFIX, \"$1$2:00\")\n .replace(TRAILING_FRACTION_ZEROES, \"$1\")\n .replace(EMPTY_FRACTION, \"\");\n return `${temporal}${era}`;\n }\n return spelling;\n}\n\nexport const canonicalValue = omitUndefinedKeys;\n\nexport function freezeDeep<T>(value: T): T {\n if (typeof value !== \"object\" || value === null) return value;\n if (ArrayBuffer.isView(value)) return value;\n for (const member of Object.values(value)) freezeDeep(member);\n return Object.freeze(value);\n}\n\nfunction byName(\n left: { readonly name: string },\n right: { readonly name: string }\n): number {\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;\n}\n\nfunction byCanonicalValue(left: unknown, right: unknown): number {\n const a = canonicalizeJsonText(left);\n const b = canonicalizeJsonText(right);\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","/**\n * How a refused PostgreSQL catalog read is reported. Apart from\n * introspection, so the shared control-table read (`control.ts`) brings no\n * PostgreSQL introspection into another dialect's bundle.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { providerRefused } from \"../../execute-dispatch\";\n\n/**\n * A catalog read the provider refused, thrown named with its SQLSTATE: a\n * server that speaks PostgreSQL but not all of its catalog SQL (PlanetScale's\n * Neki) must say which read it refused, not that the estate is wrong. The\n * server's own text stays in the cause, disclosed as the driver's diagnostics\n * allow. A transport failure is not a refusal, nor is a migration error\n * already named: the caller handles them.\n */\nexport function throwIfCatalogRefusal(query: string, error: unknown): void {\n // A migration outcome raised before the read was sent (the lock protocol's\n // own statements, such as the session's limits) is not the read's refusal.\n if (!providerRefused(error) || error instanceof MigrationError) return;\n const { providerCode, providerSqlState } = error.meta;\n throw new MigrationError(\n `PostgreSQL catalog query \"${query}\" failed with SQLSTATE ${String(providerSqlState ?? providerCode)}: ${error.message}`,\n VibORMErrorCode.MIGRATION_FAILED,\n { cause: error, meta: { providerCode, providerSqlState } }\n );\n}\n","import { normalizeType } from \"./push-fingerprint\";\n/**\n * Marker and ledger control tables: one reserved pair.\n * Read-only commands never bootstrap. Parsers in v1-parse own row truth.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { isRetryableError, MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport {\n boundNamespace,\n qualifiedName,\n tableExistsProbe,\n} from \"./catalog-probes\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { throwIfCatalogRefusal } from \"./drivers/postgres/catalog-refusal\";\nimport { providerFacts } from \"./execute-dispatch\";\nimport { isSha256, type Sha256 } from \"./identity\";\nimport { withManagedTables } from \"./target\";\nimport type { SchemaSnapshot, TableDef } from \"./types\";\nimport { encodePathHash, eventIdFor, parseLedgerEvent } from \"./v1-parse\";\nimport { parseMarkerPayload } from \"./v1-parse-control\";\nimport { readFlag } from \"./v1-parse-shared\";\nimport type {\n LedgerEventV1,\n MarkerIndexPredicateV1,\n MigrationMarkerV1,\n} from \"./v1-types\";\n\n/** The reserved control pair: the marker's table and the ledger's. */\nexport const CONTROL_TABLES: { readonly state: string; readonly log: string } =\n Object.freeze({\n state: \"_viborm_migration_state\",\n log: \"_viborm_migration_log\",\n });\n\nconst CHECK_PREFIX = /^\\s*check\\s*/i;\nconst CHECK_FORMATTING = /[\\s()\"`]/g;\n\nexport type ControlPresence =\n | { readonly kind: \"missing-table\"; readonly table: \"state\" | \"log\" | \"both\" }\n | { readonly kind: \"recoverable-state-only\" }\n | { readonly kind: \"present\" };\n\nfunction placeholder(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n index: number\n): string {\n if (dialect === \"surrealql\") return `$p${index}`;\n return dialect === \"postgresql\" ? `$${index}` : \"?\";\n}\n\ntype ControlTable = keyof typeof CONTROL_TABLES;\n\n/**\n * The one declaration of a control table: its columns, primary key first,\n * with the types VibORM's DDL spells.\n */\nfunction controlColumns(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n table: ControlTable\n): readonly (readonly [name: string, type: string])[] {\n if (table === \"state\") {\n return [\n [\"singleton\", \"INTEGER\"],\n [\"payload\", \"TEXT\"],\n ];\n }\n const id = dialect === \"mysql\" ? \"VARCHAR(64)\" : \"TEXT\";\n return [\n [\"event_id\", id],\n [\"attempt_id\", id],\n [\"kind\", dialect === \"mysql\" ? \"VARCHAR(32)\" : \"TEXT\"],\n [\"payload\", \"TEXT\"],\n ];\n}\n\n/** The parenthesized definition `CREATE TABLE` writes for one control table. */\nfunction controlDefinition(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n table: ControlTable\n): string {\n const check = table === \"state\" ? \" CHECK (singleton = 1)\" : \"\";\n const columns = controlColumns(dialect, table).map(([name, type], index) =>\n index === 0\n ? `${name} ${type} PRIMARY KEY${check}`\n : `${name} ${type} NOT NULL`\n );\n return `(\\n ${columns.join(\",\\n \")}\\n )`;\n}\n\n/** A control table in SurrealQL: its columns are fields, its key a unique index. */\nfunction surrealControlDefinition(\n driver: BoundMigrationDriver,\n table: ControlTable\n): string {\n const name = qualifiedName(driver, CONTROL_TABLES[table]);\n const key = table === \"state\" ? \"singleton\" : \"event_id\";\n const fields =\n table === \"state\"\n ? [\"singleton TYPE int ASSERT $value = 1\", \"payload TYPE string\"]\n : [\n \"event_id TYPE string\",\n \"attempt_id TYPE string\",\n \"kind TYPE string\",\n \"payload TYPE string\",\n ];\n return [\n `DEFINE TABLE ${name} SCHEMAFULL;`,\n ...fields.map((field) => {\n const [column, ...rest] = field.split(\" \");\n return `DEFINE FIELD ${column} ON ${name} ${rest.join(\" \")};`;\n }),\n `DEFINE INDEX ${CONTROL_TABLES[table]}_key ON ${name} FIELDS ${key} UNIQUE;`,\n ].join(\" \");\n}\n\n/** Exact writer-owned state definition; the control owner authenticates its contents separately. */\nexport function isSqliteStateControlDefinition(\n name: string,\n sql: string | null\n): boolean {\n return (\n name === CONTROL_TABLES.state &&\n sql !== null &&\n sqliteDefinitionBody(sql) ===\n sqliteDefinitionBody(controlDefinition(\"sqlite\", \"state\"))\n );\n}\n\nexport function createControlTableSQL(driver: BoundMigrationDriver): {\n state: string;\n log: string;\n} {\n const create = (table: ControlTable) =>\n driver.target.dialect === \"surrealql\"\n ? surrealControlDefinition(driver, table)\n : `CREATE TABLE IF NOT EXISTS ${qualifiedName(driver, CONTROL_TABLES[table])} ${controlDefinition(driver.target.dialect, table)}`;\n return { state: create(\"state\"), log: create(\"log\") };\n}\n\nfunction invalidState(message: string): MigrationError {\n return new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE);\n}\n\nexport function refusePartialControl(presence: ControlPresence): void {\n if (presence.kind === \"recoverable-state-only\") {\n throw invalidState(\n \"Control tables inconsistent: log missing after interrupted bootstrap\"\n );\n }\n if (presence.kind === \"missing-table\" && presence.table !== \"both\") {\n throw invalidState(\n `Control tables inconsistent: ${presence.table} missing`\n );\n }\n}\n\n/** The events of attempts that never reached a state. */\nconst CLOSED_WITHOUT_STATE: ReadonlySet<string> = new Set(\n \"started step-confirmed failed rolled-back resolved\".split(\" \")\n);\n\n/**\n * Without a marker, history may only hold attempts closed by `failed`,\n * `rolled-back` or `resolved`, so `apply` can start again (plan S4). An\n * unfinished attempt is its caller's refusal.\n */\nexport function refuseIncompatibleHistory(\n marker: MigrationMarkerV1 | null,\n ledger: readonly LedgerEventV1[]\n): void {\n if (marker !== null) return;\n if (unfinishedAttempts(ledger).length > 0) return;\n if (ledger.every((event) => CLOSED_WITHOUT_STATE.has(event.kind))) return;\n throw invalidState(\n \"Migration ledger history exists without a current marker\"\n );\n}\n\n/**\n * Which control tables exist. PostgreSQL answers from `catalog`, the one\n * statement that also authenticates them (plan D5), read here when not given.\n */\nexport async function inspectControlPresence(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n catalog?: PostgresControlCatalog\n): Promise<ControlPresence> {\n const read = catalog ?? (await postgresControlCatalog(producer, driver));\n const stateMissing = read\n ? !read.state\n : await isTableMissing(producer, driver, CONTROL_TABLES.state);\n const logMissing = read\n ? !read.log\n : await isTableMissing(producer, driver, CONTROL_TABLES.log);\n if (stateMissing && logMissing)\n return { kind: \"missing-table\", table: \"both\" };\n if (stateMissing) return { kind: \"missing-table\", table: \"state\" };\n if (logMissing) {\n // Bootstrap creates state before log. If the second CREATE failed, the\n // empty state table is the one recognizable partial state that can be\n // completed idempotently. A marker row means this is real history with a\n // missing ledger and must remain a hard refusal.\n await assertControlTablesAuthentic(producer, driver, \"state\", read);\n if (await isStateControlEmpty(producer, driver)) {\n return { kind: \"recoverable-state-only\" };\n }\n return { kind: \"missing-table\", table: \"log\" };\n }\n return { kind: \"present\" };\n}\n\n/**\n * Introspects with the managed-table scope narrowed to the two control tables.\n *\n * Every dialect's introspection already reads an unselected table without\n * interpreting it (no refusal of its indexes, types or defaults), so a managed\n * table's state — an INVALID index left by an interrupted `CREATE INDEX\n * CONCURRENTLY` among them — can no longer make the control plane unreadable\n * and take `status()` and `log()` down with it. The view restates `target`\n * only, the way every execution view in this layer restates one member.\n */\nfunction introspectControlTables(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<SchemaSnapshot> {\n return withManagedTables(driver, [\n CONTROL_TABLES.log,\n CONTROL_TABLES.state,\n ]).introspect((sql, params) => producer._executeRaw(sql, params));\n}\n\nconst unauth = (\n scope: \"pair\" | \"state\",\n kind: \"unreadable\" | \"unexpected\" | \"attached\"\n) =>\n `${scope === \"state\" ? \"Partial state control table\" : \"Control tables\"} ${\n kind === \"unreadable\"\n ? \"cannot be authenticated\"\n : kind === \"unexpected\"\n ? \"unexpected definition\"\n : \"have executable attachments\"\n }`;\n\n/**\n * Proves that both reserved control tables — or, with `scope` \"state\", the\n * state table bootstrap left without its log — still have VibORM's exact\n * shape. PostgreSQL reads `catalog` when presence already read it.\n */\nexport async function assertControlTablesAuthentic(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n scope: \"pair\" | \"state\" = \"pair\",\n catalog?: PostgresControlCatalog\n): Promise<void> {\n if (driver.target.dialect === \"postgresql\") {\n assertPostgresControlAuthentic(\n catalog ?? (await readPostgresControlCatalog(producer, driver)),\n scope\n );\n return;\n }\n if (driver.target.dialect === \"surrealql\") {\n await assertSurrealControlAuthentic(producer, driver, scope);\n return;\n }\n let snapshot: SchemaSnapshot;\n try {\n snapshot = await introspectControlTables(producer, driver);\n } catch (failure) {\n if (failure instanceof MigrationError && scope === \"pair\") throw failure;\n throw unreadable(unauth(scope, \"unreadable\"), failure);\n }\n const matches = (name: string) =>\n snapshot.tables.filter((table) => table.name === name);\n const [state, ...otherStates] = matches(CONTROL_TABLES.state);\n const [log, ...otherLogs] = matches(CONTROL_TABLES.log);\n if (\n !state ||\n otherStates.length > 0 ||\n !hasExpectedShape(state, driver, \"state\") ||\n (scope === \"pair\" &&\n !(log && otherLogs.length === 0 && hasExpectedShape(log, driver, \"log\")))\n ) {\n throw invalidState(unauth(scope, \"unexpected\"));\n }\n let hasSingletonCheck: boolean;\n try {\n hasSingletonCheck = await hasExpectedSingletonCheck(producer, driver);\n } catch (failure) {\n throw unreadable(unauth(scope, \"unreadable\"), failure);\n }\n if (!hasSingletonCheck) throw invalidState(unauth(scope, \"unexpected\"));\n let hasAttachments: boolean;\n try {\n hasAttachments = await hasControlAttachments(producer, driver);\n } catch (failure) {\n if (failure instanceof MigrationError) throw failure;\n throw unreadable(unauth(scope, \"unreadable\"), failure);\n }\n if (hasAttachments) throw invalidState(unauth(scope, \"attached\"));\n}\n\nasync function assertSurrealControlAuthentic(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n scope: \"pair\" | \"state\"\n): Promise<void> {\n for (const table of scope === \"pair\"\n ? ([\"state\", \"log\"] as const)\n : ([\"state\"] as const)) {\n const name = qualifiedName(driver, CONTROL_TABLES[table]);\n let info: {\n readonly fields: readonly { readonly name: string }[];\n readonly indexes: readonly { readonly name: string }[];\n readonly events: readonly unknown[];\n };\n try {\n const { rows } = await producer._executeRaw<typeof info>(\n `RETURN [(INFO FOR TABLE ${name} STRUCTURE).{ fields, indexes, events }]`\n );\n info = rows[0]!;\n } catch (failure) {\n throw unreadable(unauth(scope, \"unreadable\"), failure);\n }\n const expected =\n table === \"state\"\n ? [\"payload\", \"singleton\"]\n : [\"attempt_id\", \"event_id\", \"kind\", \"payload\"];\n const fields = info.fields.map((field) => field.name).sort();\n if (\n fields.join() !== expected.join() ||\n info.indexes.length !== 1 ||\n info.indexes[0]?.name !== `${CONTROL_TABLES[table]}_key`\n )\n throw invalidState(unauth(scope, \"unexpected\"));\n if (info.events.length > 0) throw invalidState(unauth(scope, \"attached\"));\n }\n}\n\n/**\n * The definition VibORM creates, as introspection reads it back: the declared\n * columns, NOT NULL with no default (SQLite's TEXT key aside), and the primary\n * key alone. MySQL reports\n * the singleton's INTEGER as `int`.\n */\nfunction hasExpectedShape(\n table: TableDef,\n driver: BoundMigrationDriver,\n kind: ControlTable\n): boolean {\n const mysql = driver.target.dialect === \"mysql\";\n const columns = controlColumns(driver.target.dialect, kind);\n return (\n table.columns.length === columns.length &&\n table.columns.every((column, index) => {\n const [name, type] = columns[index]!;\n return (\n column.name === name &&\n (name === \"singleton\"\n ? normalizeType(column.type) === normalizeType(mysql ? \"INT\" : type)\n : column.type.toLowerCase() === type.toLowerCase()) &&\n // SQLite lets a rowid table's key hold NULL unless it is the rowid\n // alias, and the definition writes the key without NOT NULL.\n column.nullable ===\n (driver.target.dialect === \"sqlite\" &&\n index === 0 &&\n type !== \"INTEGER\") &&\n column.default === undefined &&\n column.autoIncrement !== true &&\n column.decimal === undefined\n );\n }) &&\n table.primaryKey?.name ===\n (mysql ? \"PRIMARY\" : `${CONTROL_TABLES[kind]}_pkey`) &&\n table.primaryKey.columns.length === 1 &&\n table.primaryKey.columns[0] === columns[0]![0] &&\n table.indexes.length === 0 &&\n table.foreignKeys.length === 0 &&\n table.uniqueConstraints.length === 0 &&\n table.relationStorage === undefined\n );\n}\n\nasync function hasExpectedSingletonCheck(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<boolean> {\n if (driver.target.dialect === \"sqlite\") {\n const result = await producer._executeRaw<{ sql: unknown }>(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\",\n [CONTROL_TABLES.state]\n );\n const sql = result.rows[0]?.sql;\n return (\n result.rows.length === 1 &&\n typeof sql === \"string\" &&\n isSqliteStateControlDefinition(CONTROL_TABLES.state, sql)\n );\n }\n const result = await producer._executeRaw<{ definition: unknown }>(\n `SELECT cc.CHECK_CLAUSE AS definition\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.CHECK_CONSTRAINTS cc\n ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA\n AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\nWHERE tc.CONSTRAINT_SCHEMA = ?\n AND tc.TABLE_NAME = ?\n AND tc.CONSTRAINT_TYPE = 'CHECK'\nORDER BY tc.CONSTRAINT_NAME`,\n [driver.namespace, CONTROL_TABLES.state]\n );\n return (\n result.rows.length === 1 &&\n normalizeSingletonCheck(result.rows[0]?.definition) === \"singleton=1\"\n );\n}\n\nfunction sqliteDefinitionBody(sql: string): string {\n const body = sql.slice(sql.indexOf(\"(\"));\n return body.replace(/[\\s\"`]/g, \"\").toLowerCase();\n}\n\nfunction normalizeSingletonCheck(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n return value\n .replace(CHECK_PREFIX, \"\")\n .replace(CHECK_FORMATTING, \"\")\n .toLowerCase();\n}\n\nasync function hasControlAttachments(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<boolean> {\n const names = [CONTROL_TABLES.state, CONTROL_TABLES.log];\n const result =\n driver.target.dialect === \"sqlite\"\n ? await producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND tbl_name IN (?, ?)) AS attached\",\n names\n )\n : await producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = ? AND EVENT_OBJECT_TABLE IN (?, ?)) AS attached\",\n [driver.namespace, ...names]\n );\n if (result.rows.length !== 1) {\n throw invalidState(\"Control attachment probe must return 1 row\");\n }\n const attached = readFlag(Object.values(result.rows[0]!)[0]);\n if (attached !== undefined) return attached;\n throw invalidState(\"Control attachment probe returned invalid flag\");\n}\n\nasync function isStateControlEmpty(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<boolean> {\n const table = qualifiedName(driver, CONTROL_TABLES.state);\n try {\n const result = await producer._executeRaw(\n `SELECT payload FROM ${table} WHERE singleton = 1`\n );\n return result.rows.length === 0;\n } catch (failure) {\n throw unreadable(\n \"Partial state control table cannot be proven empty\",\n failure\n );\n }\n}\n\n/**\n * The refusal `message` for a control-table read that failed, or the failure\n * itself when it says nothing about the tables: the migration lock not taken\n * (the read may be the statement that reopens a command's locked transaction,\n * after a commit let the lock go), a lost connection or another retryable\n * failure, which the caller retries.\n */\nfunction unreadable(message: string, failure: unknown): unknown {\n const transient =\n isRetryableError(failure) ||\n (failure instanceof MigrationError &&\n failure.code === VibORMErrorCode.MIGRATION_LOCK_FAILED);\n return transient\n ? failure\n : new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE, {\n cause: errorCause(failure),\n meta: providerFacts(failure),\n });\n}\n\nexport async function isTableMissing(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n tableName: string\n): Promise<boolean> {\n const probe = tableExistsProbe(driver, tableName, true);\n const result = await producer._executeRaw<Record<string, unknown>>(\n probe.sql,\n probeParameters(probe.parameters)\n );\n if (result.rows.length !== 1) {\n throw invalidState(\"Control catalog probe must return 1 row\");\n }\n return readFlag(Object.values(result.rows[0]!)[0]) !== true;\n}\n\nfunction probeParameters(\n parameters: ReturnType<typeof tableExistsProbe>[\"parameters\"]\n): unknown[] {\n return parameters.map((parameter) => {\n if (parameter.kind !== \"string\") {\n throw new MigrationError(\n \"Control catalog probe parameters must be strings\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return parameter.value;\n });\n}\n\nexport interface MigrationControlRead {\n readonly presence: ControlPresence;\n readonly marker: MigrationMarkerV1 | null;\n /**\n * The ledger events, in causal order (`inCausalOrder`): every event, or\n * with `{ ledger: \"open\" }` those of an unfinished attempt and the latest\n * `failed` one (plan D5, new defect 6). Without a marker the history may\n * only hold attempts that never reached a state, and all of it is read so\n * `refuseIncompatibleHistory` can say so.\n */\n readonly ledger: readonly LedgerEventV1[];\n}\n\n/** The event kinds that open an attempt, and those that close one. */\nconst OPENING_KINDS: ReadonlySet<string> = new Set(\n \"started reset-started\".split(\" \")\n);\nconst CLOSING_KINDS: ReadonlySet<string> = new Set(\n \"applied rolled-back failed baselined reanchored resolved reset-applied\".split(\n \" \"\n )\n);\n\n/**\n * Reads the control-plane view. A present pair is authenticated once before\n * either table is trusted; callers decide whether total absence or the\n * recoverable bootstrap arm is valid for their command.\n */\nexport async function readControlState(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n { ledger: scope = \"all\" }: { readonly ledger?: \"open\" | \"all\" } = {}\n): Promise<MigrationControlRead> {\n const catalog = await postgresControlCatalog(producer, driver);\n const presence = await inspectControlPresence(producer, driver, catalog);\n if (presence.kind !== \"present\") {\n return { presence, marker: null, ledger: [] };\n }\n await assertControlTablesAuthentic(producer, driver, \"pair\", catalog);\n const markerResult = await producer._executeRaw<{ payload: unknown }>(\n `SELECT payload FROM ${qualifiedName(driver, CONTROL_TABLES.state)} WHERE singleton = 1`\n );\n // Without a marker every event is read: `refuseIncompatibleHistory` judges\n // the whole history then.\n const all = scope === \"all\" || markerResult.rows.length === 0;\n const ledgerResult = await producer._executeRaw<{ payload: unknown }>(\n ledgerSql(driver, all)\n );\n const { marker, ledger } = decodeControlRows(\n markerResult.rows,\n ledgerResult.rows\n );\n return { presence, marker, ledger };\n}\n\n/**\n * The ledger events a command reads, selected by their columns, which the\n * one writer (`appendLedger`) fills from the event it appends: every event,\n * or those of an unfinished attempt and the latest `failed` one (plan D5,\n * new defect 6).\n */\nfunction ledgerSql(driver: BoundMigrationDriver, all: boolean): string {\n const log = qualifiedName(driver, CONTROL_TABLES.log);\n // Which attempts are open is `unfinishedAttempts`'s to read: a subquery here\n // answers rows, not the list SQL's `IN` reads.\n if (all || driver.target.dialect === \"surrealql\")\n return `SELECT payload FROM ${log}`;\n return `SELECT payload FROM ${log} WHERE ${openAttempt(log)}\n OR event_id = (SELECT event_id FROM ${log} WHERE kind = 'failed' ORDER BY ${jsonField(driver.target.dialect, \"startedAt\")} DESC, event_id DESC LIMIT 1)`;\n}\n\n/** The ledger rows of an unfinished attempt, as `unfinishedAttempts` reads them. */\nfunction openAttempt(log: string): string {\n const list = (kinds: ReadonlySet<string>) =>\n [...kinds].map((kind) => `'${kind}'`).join(\", \");\n return `(attempt_id IN (SELECT attempt_id FROM ${log} WHERE kind IN (${list(OPENING_KINDS)}))\n AND attempt_id NOT IN (SELECT attempt_id FROM ${log} WHERE kind IN (${list(CLOSING_KINDS)})))`;\n}\n\n/**\n * `assertLockedSinceDecision` as a condition one request asserts under its\n * own lock (plan D7): the marker is still `expected`, or there is none when\n * that is null, and no attempt is open.\n */\nexport function markerUnmovedCondition(\n driver: BoundMigrationDriver,\n expected: MarkerIdentity | null\n): { readonly sql: string; readonly params: unknown[] } {\n const log = qualifiedName(driver, CONTROL_TABLES.log);\n const at = expected && markerAt(driver.target.dialect, 1, expected);\n const marker = `EXISTS (SELECT 1 FROM ${qualifiedName(driver, CONTROL_TABLES.state)}${at ? ` WHERE singleton = 1 AND ${at.sql}` : \"\"})`;\n return {\n sql: `(${at ? \"\" : \"NOT \"}${marker} AND NOT EXISTS (SELECT 1 FROM ${log} WHERE ${openAttempt(log)}))`,\n params: at ? at.params : [],\n };\n}\n\n/** What identifies a marker: `markerAt` matches it in SQL, `sameMarker` in JS. */\nexport type MarkerIdentity = Pick<MigrationMarkerV1, \"revision\" | \"pathHash\">;\n\n/** The marker row is `expected`, bound from `$first` on. */\nfunction markerAt(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n first: number,\n { revision, pathHash }: MarkerIdentity\n): { readonly sql: string; readonly params: unknown[] } {\n const slot = placeholder(dialect, first);\n if (dialect === \"surrealql\")\n return {\n sql: `encoding::json::decode(payload).revision = ${slot} AND encoding::json::decode(payload).pathHash = ${placeholder(dialect, first + 1)}`,\n params: [revision, pathHash],\n };\n const revisionMatch =\n dialect === \"postgresql\"\n ? `(payload::json->>'revision')::bigint = ${slot}`\n : dialect === \"mysql\"\n ? `CAST(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.revision')) AS UNSIGNED) = ${slot}`\n : `CAST(json_extract(payload, '$.revision') AS INTEGER) = ${slot}`;\n return {\n sql: `${revisionMatch} AND ${jsonField(dialect, \"pathHash\")} = ${placeholder(dialect, first + 1)}`,\n params: [revision, pathHash],\n };\n}\n\nfunction decodeControlRows(\n markerRows: readonly { readonly payload: unknown }[],\n ledgerRows: readonly { readonly payload: unknown }[]\n): {\n readonly marker: MigrationMarkerV1 | null;\n readonly predicates: readonly MarkerIndexPredicateV1[];\n readonly ledger: readonly LedgerEventV1[];\n} {\n const markerRow = markerRows[0];\n const stored =\n markerRow && parseMarkerPayload(parsePayload(markerRow.payload));\n return {\n marker: stored ? stored.marker : null,\n predicates: stored ? stored.predicates : [],\n ledger: inCausalOrder(\n ledgerRows.map((row) => parseLedgerEvent(parsePayload(row.payload)))\n ),\n };\n}\n\n/**\n * Plan D5: what a PostgreSQL no-op decides on, in two statements: the control\n * tables' definition, then the marker, the open attempts and the catalog\n * digest, read together and so in one snapshot, provided `lockFree` (the\n * migration lock taken and released at once) holds. Without a marker there is\n * no no-op to prove, so the ledger is never read whole here. `undefined`\n * unless both control tables are present, so no statement here names a table\n * that is not there, and while another command holds the lock; a pair that is\n * not exactly VibORM's is refused. The digest hashes partial-index predicates\n * as the server deparses them, for comparison with those recorded beside the\n * marker.\n */\nexport async function readPostgresDecision(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n lockFree: string\n): Promise<\n | {\n readonly marker: MigrationMarkerV1 | null;\n readonly predicates: readonly MarkerIndexPredicateV1[];\n readonly ledger: readonly LedgerEventV1[];\n readonly digest: Sha256 | undefined;\n }\n | undefined\n> {\n const catalog = await readPostgresControlCatalog(producer, driver);\n if (!(catalog.state && catalog.log)) return;\n assertPostgresControlAuthentic(catalog, \"pair\");\n // Only PostgreSQL reads a decision in one statement: its driver owns this.\n const digest = driver.catalogDigestQuery!(CONTROL_TABLES, true);\n const { rows } = await producer._executeRaw<{\n marker: unknown;\n ledger: unknown;\n digest: unknown;\n }>(\n `SELECT (SELECT json_agg(json_build_object('payload', marker.payload)) FROM (SELECT payload FROM ${qualifiedName(driver, CONTROL_TABLES.state)} WHERE singleton = 1) marker)::text AS marker,\n (SELECT json_agg(json_build_object('payload', ledger.payload)) FROM (${ledgerSql(driver, false)}) ledger)::text AS ledger,\n (${digest.sql}) AS digest WHERE ${lockFree}`,\n digest.parameters\n );\n if (rows.length === 0) return;\n return {\n ...decodeControlRows(\n readPayloadRows(rows[0]?.marker),\n readPayloadRows(rows[0]?.ledger)\n ),\n digest: isSha256(rows[0]?.digest) ? rows[0].digest : undefined,\n };\n}\n\n/** The `{ payload }` rows a JSON aggregate carries; none for SQL NULL. */\nfunction readPayloadRows(value: unknown): { readonly payload: unknown }[] {\n const rows: unknown = readCatalogJson(value);\n return Array.isArray(rows)\n ? rows.flatMap((row: unknown) =>\n isRecord(row) ? [{ payload: row.payload }] : []\n )\n : [];\n}\n\n/**\n * The ledger in causal order (new defect 6). Without a sequence column the\n * clock is the order, and it ties: one millisecond can hold a whole\n * transactional group, or one attempt's close and the next one's start. The\n * events of one instant come attempt by attempt — the one opened earliest\n * first, then along the state chain (an attempt leaving the state another one\n * arrives at follows it), then by attempt id — and inside an attempt as it\n * ran: it opens, confirms steps, then closes. Only a cycle of attempts within\n * one millisecond (up, down, up) falls back to attempt ids.\n */\nfunction inCausalOrder(events: readonly LedgerEventV1[]): LedgerEventV1[] {\n const opened = new Map<Sha256, string>();\n for (const { attemptId, startedAt } of events) {\n const first = opened.get(attemptId);\n if (first === undefined || startedAt < first) {\n opened.set(attemptId, startedAt);\n }\n }\n const byTime = [...events].sort((left, right) =>\n compareText(left.startedAt, right.startedAt)\n );\n const ordered: LedgerEventV1[] = [];\n for (let start = 0; start < byTime.length; ) {\n const instant = byTime[start]!.startedAt;\n let end = start;\n while (byTime[end]?.startedAt === instant) end += 1;\n ordered.push(...instantInOrder(byTime.slice(start, end), opened));\n start = end;\n }\n return ordered;\n}\n\nfunction instantInOrder(\n events: readonly LedgerEventV1[],\n opened: ReadonlyMap<Sha256, string>\n): LedgerEventV1[] {\n const pending = new Map<Sha256, LedgerEventV1[]>();\n for (const event of events) {\n const attempt = pending.get(event.attemptId);\n if (attempt) attempt.push(event);\n else pending.set(event.attemptId, [event]);\n }\n const follows = ({ attemptId, fromState }: LedgerEventV1) =>\n fromState !== null &&\n [...pending.values()].some(\n ([other]) =>\n other!.attemptId !== attemptId && other!.toState === fromState\n );\n const ordered: LedgerEventV1[] = [];\n while (pending.size > 0) {\n const [next] = [...pending.values()]\n .map(([first]) => first!)\n .sort(\n (left, right) =>\n compareText(\n opened.get(left.attemptId)!,\n opened.get(right.attemptId)!\n ) ||\n Number(follows(left)) - Number(follows(right)) ||\n compareText(left.attemptId, right.attemptId)\n );\n ordered.push(\n ...pending\n .get(next!.attemptId)!\n .sort(\n (left, right) =>\n causalRank(left) - causalRank(right) ||\n compareText(left.eventId, right.eventId)\n )\n );\n pending.delete(next!.attemptId);\n }\n return ordered;\n}\n\nfunction compareText(left: string, right: string): number {\n return Number(left > right) - Number(left < right);\n}\n\nfunction causalRank(event: LedgerEventV1): number {\n if (OPENING_KINDS.has(event.kind)) return 0;\n return CLOSING_KINDS.has(event.kind) ? 2 : 1;\n}\n\n/** The text of one top-level field of a JSON payload, per dialect. */\nfunction jsonField(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n field: string\n): string {\n if (dialect === \"postgresql\") return `payload::json->>'${field}'`;\n if (dialect === \"mysql\") {\n return `JSON_UNQUOTE(JSON_EXTRACT(payload, '$.${field}'))`;\n }\n return `json_extract(payload, '$.${field}')`;\n}\n\n/** One control table as the PostgreSQL catalog read reports it. */\ninterface PostgresControlTable {\n readonly kind: unknown;\n readonly partition: unknown;\n readonly columns: unknown;\n readonly constraints: unknown;\n readonly indexes: unknown;\n readonly executable: unknown;\n}\n\ninterface PostgresControlCatalog {\n readonly state: PostgresControlTable | undefined;\n readonly log: PostgresControlTable | undefined;\n}\n\n/**\n * Both control tables' definitions in one statement (plan D5): the columns,\n * the constraints but PostgreSQL 18's catalogued NOT NULLs, how many indexes,\n * and whether a trigger, rule, policy or row security is attached. It reads\n * these two relations only, so no managed table's state — an INVALID index\n * among them (plan S7) — can make the control plane unreadable.\n */\nconst POSTGRES_CONTROL_CATALOG = `SELECT control.position,c.relkind::text AS kind,c.relispartition AS partition,(SELECT json_agg(json_build_array(a.attname::text,pg_catalog.format_type(a.atttypid,a.atttypmod),a.attnotnull,a.atthasdef,a.attidentity::text,a.attgenerated::text) ORDER BY a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped)::text AS columns,(SELECT json_agg(json_build_array(k.contype::text,k.conname::text,pg_catalog.pg_get_constraintdef(k.oid,true)) ORDER BY k.conname) FROM pg_catalog.pg_constraint k WHERE k.conrelid = c.oid AND k.contype <> 'n')::text AS constraints,(SELECT count(*) FROM pg_catalog.pg_index i WHERE i.indrelid = c.oid)::text AS indexes,(EXISTS (SELECT 1 FROM pg_catalog.pg_trigger g WHERE g.tgrelid = c.oid AND NOT g.tgisinternal) OR EXISTS (SELECT 1 FROM pg_catalog.pg_rewrite w WHERE w.ev_class = c.oid AND w.rulename <> '_RETURN') OR EXISTS (SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = c.oid) OR c.relrowsecurity OR c.relforcerowsecurity) AS executable FROM (VALUES (1,$2::text),(2,$3::text)) AS control(position,name) LEFT JOIN pg_catalog.pg_class c ON c.relname = control.name AND c.relkind IN ('r','p') AND c.relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = $1::text) ORDER BY control.position`;\n\n/** {@link readPostgresControlCatalog} on PostgreSQL; nothing elsewhere. */\nfunction postgresControlCatalog(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PostgresControlCatalog | undefined> {\n return driver.target.dialect === \"postgresql\"\n ? readPostgresControlCatalog(producer, driver)\n : Promise.resolve(undefined);\n}\n\nasync function readPostgresControlCatalog(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PostgresControlCatalog> {\n let rows: readonly Record<string, unknown>[];\n try {\n ({ rows } = await producer._executeRaw<Record<string, unknown>>(\n POSTGRES_CONTROL_CATALOG,\n [boundNamespace(driver), CONTROL_TABLES.state, CONTROL_TABLES.log]\n ));\n } catch (failure) {\n throwIfCatalogRefusal(\"control catalog\", failure);\n throw unreadable(unauth(\"pair\", \"unreadable\"), failure);\n }\n if (rows.length !== 2) {\n throw invalidState(\"Control catalog read must return 2 rows\");\n }\n return {\n state: presentControlTable(rows[0]),\n log: presentControlTable(rows[1]),\n };\n}\n\nfunction presentControlTable(row: unknown): PostgresControlTable | undefined {\n if (!isRecord(row) || row.kind === null || row.kind === undefined) return;\n const { kind, partition, columns, constraints, indexes, executable } = row;\n return { kind, partition, columns, constraints, indexes, executable };\n}\n\nfunction assertPostgresControlAuthentic(\n { state, log }: PostgresControlCatalog,\n scope: \"pair\" | \"state\"\n): void {\n const pair = scope === \"pair\";\n if (\n !(\n state &&\n hasPostgresShape(state, \"state\") &&\n (!pair || (log && hasPostgresShape(log, \"log\")))\n )\n )\n throw invalidState(unauth(scope, \"unexpected\"));\n if (\n readFlag(state.executable) !== false ||\n (pair && readFlag(log?.executable) !== false)\n )\n throw invalidState(unauth(scope, \"attached\"));\n}\n\n/**\n * The exact definition VibORM creates: an ordinary table of NOT NULL columns\n * with no default, identity or generation, its primary key, the state\n * table's one `singleton = 1` CHECK, and no other constraint or index.\n */\nfunction hasPostgresShape(\n table: PostgresControlTable,\n kind: ControlTable\n): boolean {\n const columns = controlColumns(\"postgresql\", kind);\n const constraints = readCatalogRows(table.constraints);\n if (constraints === undefined) return false;\n const checks = constraints.filter((constraint) => constraint[0] === \"c\");\n const keys = constraints.filter((constraint) => constraint[0] === \"p\");\n return (\n table.kind === \"r\" &&\n readFlag(table.partition) === false &&\n String(table.indexes) === \"1\" &&\n canonicalizeJsonText(readCatalogJson(table.columns)) ===\n canonicalizeJsonText(\n columns.map(([name, type]) => [\n name,\n type.toLowerCase(),\n true,\n false,\n \"\",\n \"\",\n ])\n ) &&\n constraints.length === keys.length + checks.length &&\n keys.length === 1 &&\n keys[0]?.[1] === `${CONTROL_TABLES[kind]}_pkey` &&\n keys[0]?.[2] === `PRIMARY KEY (${columns[0]![0]})` &&\n checks.length === (kind === \"state\" ? 1 : 0) &&\n checks.every((check) => normalizeSingletonCheck(check[2]) === \"singleton=1\")\n );\n}\n\n/** A JSON column of the catalog read, or `null` when it is not JSON text. */\nfunction readCatalogJson(value: unknown): unknown {\n if (typeof value !== \"string\") return null;\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n}\n\n/** A JSON array of arrays (no rows: SQL NULL), or `undefined`. */\nfunction readCatalogRows(\n value: unknown\n): readonly (readonly unknown[])[] | undefined {\n if (value === null) return [];\n const rows: unknown = readCatalogJson(value);\n if (!Array.isArray(rows)) return undefined;\n const checked: (readonly unknown[])[] = [];\n for (const row of rows) {\n const entry: unknown = row;\n if (!Array.isArray(entry)) return undefined;\n checked.push(entry);\n }\n return checked;\n}\n\n/**\n * Creates the pair, or completes the one a failed bootstrap left, under the\n * migration lock: no other command bootstraps between the presence read and\n * the CREATE, so presence is read once.\n */\nexport async function ensureControlTables(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<void> {\n const catalog = await postgresControlCatalog(producer, driver);\n const presence = await inspectControlPresence(producer, driver, catalog);\n if (presence.kind === \"present\") {\n await assertControlTablesAuthentic(producer, driver, \"pair\", catalog);\n return;\n }\n if (presence.kind === \"missing-table\") refusePartialControl(presence);\n else {\n await producer._executeRaw(\n `${driver.target.dialect === \"surrealql\" ? \"REMOVE TABLE\" : \"DROP TABLE\"} ${qualifiedName(driver, CONTROL_TABLES.state)}`\n );\n }\n const sql = createControlTableSQL(driver);\n await producer._executeRaw(sql.state);\n await producer._executeRaw(sql.log);\n await assertControlTablesAuthentic(producer, driver);\n}\n\n/**\n * Moves the marker. `predicates`, recorded beside it, are the partial-index\n * predicates of `next`'s snapshot as PostgreSQL deparsed them; a marker\n * without them proves its no-op under the lock.\n */\nexport async function casMarker(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n expected: MarkerIdentity | null,\n next: MigrationMarkerV1,\n predicates: readonly MarkerIndexPredicateV1[] = []\n): Promise<void> {\n const { sql, params } = markerWrite(driver, expected, next, predicates);\n if (expected === null) {\n let result: { readonly rowCount: number };\n try {\n result = await producer._executeRaw(sql, params);\n } catch (error) {\n if (error instanceof MigrationError) throw error;\n throw new MigrationError(\n \"Marker CAS failed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n if (result.rowCount !== 1) {\n throw new MigrationError(\n \"Marker insert did not create singleton row\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n return;\n }\n const result = await producer._executeRaw(sql, params);\n if (result.rowCount !== 1) {\n throw new MigrationError(\n \"Marker CAS failed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n}\n\n/**\n * The statement {@link casMarker} sends: the first marker's INSERT, or the\n * UPDATE that matches only the `expected` marker. One request (plan D7)\n * sends it after asserting that marker under its lock.\n */\nexport function markerWrite(\n driver: BoundMigrationDriver,\n expected: MarkerIdentity | null,\n next: MigrationMarkerV1,\n predicates: readonly MarkerIndexPredicateV1[] = []\n): { readonly sql: string; readonly params: unknown[] } {\n const table = qualifiedName(driver, CONTROL_TABLES.state);\n const payload = canonicalizeJsonText(\n predicates.length > 0 ? { ...next, predicates } : next\n );\n const dialect = driver.target.dialect;\n const at = expected && markerAt(dialect, 2, expected);\n return at\n ? {\n sql: `UPDATE ${table} SET payload = ${placeholder(dialect, 1)} WHERE singleton = 1 AND ${at.sql}`,\n params: [payload, ...at.params],\n }\n : {\n sql: `INSERT INTO ${table} (singleton, payload) VALUES (1, ${placeholder(dialect, 1)})`,\n params: [payload],\n };\n}\n\n/** Appends events in one statement, in their order. */\nexport async function appendLedger(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n ...events: readonly LedgerEventV1[]\n): Promise<void> {\n const table = qualifiedName(driver, CONTROL_TABLES.log);\n const dialect = driver.target.dialect;\n const rows = events.map((_, index) =>\n [1, 2, 3, 4].map((column) => placeholder(dialect, index * 4 + column))\n );\n await producer._executeRaw(\n `INSERT INTO ${table} (event_id, attempt_id, kind, payload) VALUES ${rows.map((row) => `(${row.join(\", \")})`).join(\", \")}`,\n events.flatMap((event) => [\n event.eventId,\n event.attemptId,\n event.kind,\n canonicalizeJsonText(event),\n ])\n );\n}\n\nexport function markerFromPath(\n estateHash: Sha256,\n snapshotHash: Sha256,\n path: MigrationMarkerV1[\"path\"],\n revision: number\n): MigrationMarkerV1 {\n const stateId = path.length === 0 ? null : path.at(-1)!.stateId;\n return {\n format: \"1\",\n estateHash,\n stateId,\n snapshotHash,\n path,\n pathHash: encodePathHash(path),\n revision,\n updatedAt: new Date().toISOString(),\n };\n}\n\n/** Every ledger event's sealed fields: format, times, tool version and id. */\nexport function ledgerEvent({\n open = false,\n failure = null,\n ...fields\n}: Omit<\n LedgerEventV1,\n \"format\" | \"eventId\" | \"toolVersion\" | \"startedAt\" | \"finishedAt\" | \"failure\"\n> & { failure?: string | null; open?: boolean }): LedgerEventV1 {\n const startedAt = new Date().toISOString();\n const event = {\n format: \"1\" as const,\n ...fields,\n startedAt,\n finishedAt: open ? null : startedAt,\n toolVersion: \"v1\",\n failure,\n };\n return { ...event, eventId: eventIdFor(event) };\n}\n\n/** The fields every event of one attempt carries. */\ntype AttemptSeed = Pick<\n LedgerEventV1,\n | \"estateHash\"\n | \"snapshotHash\"\n | \"sqlHash\"\n | \"fromState\"\n | \"toState\"\n | \"transitionHash\"\n | \"direction\"\n>;\n\n/** An attempt's id: the id of its `started` event under the zero attempt. */\nexport function attemptIdFor(seed: AttemptSeed): Sha256 {\n return ledgerEvent({\n ...seed,\n attemptId: \"0\".repeat(64),\n kind: \"started\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n open: true,\n }).eventId;\n}\n\n/** The builder of one attempt's ledger events. */\nexport interface AttemptEvents {\n readonly attemptId: Sha256;\n event(\n kind: LedgerEventV1[\"kind\"],\n effectState: LedgerEventV1[\"effectState\"],\n step?: {\n readonly operationId: string | null;\n readonly dispatchId: Sha256 | null;\n },\n failure?: string\n ): LedgerEventV1;\n}\n\n/**\n * One attempt's events: each carries `seed` (and a reset plan, when it has\n * one) and `attemptId`, by default the id of the attempt's own `started`\n * event. An opening kind leaves its event unfinished.\n */\nexport function attemptEvents(\n seed: AttemptSeed & Pick<LedgerEventV1, \"resetPlan\">,\n attemptId: Sha256 = attemptIdFor(seed)\n): AttemptEvents {\n return {\n attemptId,\n event: (kind, effectState, step, failure) =>\n ledgerEvent({\n ...seed,\n attemptId,\n kind,\n effectState,\n operationId: step?.operationId ?? null,\n dispatchId: step?.dispatchId ?? null,\n failure,\n open: OPENING_KINDS.has(kind),\n }),\n };\n}\n\n/** Whether a read marker is the one expected; two absent markers are. */\nexport function sameMarker(\n marker: MarkerIdentity | null,\n expected: MarkerIdentity | null\n): boolean {\n return (\n marker?.revision === expected?.revision &&\n marker?.pathHash === expected?.pathHash\n );\n}\n\n/** Compare-and-swaps the marker from `current` to the one `path` ends at. */\nexport async function advanceMarker(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n estateHash: Sha256,\n current: MigrationMarkerV1 | null,\n path: MigrationMarkerV1[\"path\"],\n snapshotHash: Sha256,\n revisionStep = 1,\n predicates?: readonly MarkerIndexPredicateV1[]\n): Promise<MigrationMarkerV1> {\n const next = markerFromPath(\n estateHash,\n snapshotHash,\n path,\n (current?.revision ?? 0) + revisionStep\n );\n await casMarker(producer, driver, current, next, predicates);\n return next;\n}\n\nfunction parsePayload(value: unknown): unknown {\n if (typeof value === \"string\") return JSON.parse(value);\n return value;\n}\n\nexport function unfinishedAttempts(\n events: readonly LedgerEventV1[]\n): readonly LedgerEventV1[] {\n const started = new Map<string, LedgerEventV1>();\n const closed = new Set<string>();\n for (const event of events) {\n if (OPENING_KINDS.has(event.kind)) started.set(event.attemptId, event);\n if (CLOSING_KINDS.has(event.kind)) closed.add(event.attemptId);\n }\n return [...started.values()].filter((event) => !closed.has(event.attemptId));\n}\n","/**\n * Migration Estate Target\n *\n * ONE resolver derives the durable estate target from a concrete execution\n * driver, and ONE pair of readers reaches the two runtime facts installed on\n * the adapter and the driver (`adapter.namespace`,\n * `driver.migrationNamespaceAttestation`). Every migration verb, the registry\n * binding, and the live-capability admission owner reach those facts through\n * here, so no command re-decides dialect, namespace or attestation for itself.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { CONTROL_TABLES } from \"./control\";\nimport { snapshotExactArray } from \"./input-boundary\";\nimport type { MigrationTarget, SchemaSnapshot } from \"./types\";\nimport { normalizeDialect } from \"./utils\";\n\nexport const MANAGED_TABLES = Symbol(\"migration managed tables\");\n/** The client's resolved limits (plans S1, T5a), bound with its driver. */\nexport const MIGRATION_LIMITS = Symbol(\"migration limits\");\n\nconst invalidState = (message: string, meta?: Record<string, unknown>) =>\n new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n meta ? { meta } : undefined\n );\nconst targetMismatch = (message: string) =>\n new MigrationError(message, VibORMErrorCode.MIGRATION_DIALECT_MISMATCH);\n\n/** Exact physical membership, authenticated as part of the estate target. */\nexport function normalizeManagedTables(\n value: unknown\n): readonly string[] | undefined {\n if (value === undefined) return;\n const entries = snapshotExactArray(value, \"managed tables\", (message) => {\n throw invalidState(message);\n });\n const names: string[] = [];\n for (const name of entries) {\n if (typeof name !== \"string\" || name.length === 0 || name.includes(\"\\0\"))\n throw invalidState(\n \"Managed tables must contain non-empty physical names\"\n );\n if (names.includes(name))\n throw invalidState(`Managed table \"${name}\" is repeated`);\n names.push(name);\n }\n return Object.freeze(names.sort());\n}\n\nexport function selectManagedSnapshot(\n snapshot: SchemaSnapshot,\n target: MigrationTarget,\n desired = false\n): SchemaSnapshot {\n const names = target.tables;\n if (names === undefined) return snapshot;\n // Control authenticity reads the same inventory, independently of user scope.\n const selected = (name: string) =>\n names.includes(name) ||\n name === CONTROL_TABLES.state ||\n name === CONTROL_TABLES.log;\n if (desired && snapshot.tables.some((table) => !names.includes(table.name)))\n throw invalidState(\"Schema table outside managed tables\");\n if (desired && snapshot.views?.some((view) => !names.includes(view.name)))\n throw invalidState(\"Schema view outside managed tables\");\n // A control-only selection (the control-table read) draws no user\n // boundary: a user table's keys must not make the control plane unreadable,\n // whatever scope the command selects.\n const userScope = names.some(\n (name) => name !== CONTROL_TABLES.state && name !== CONTROL_TABLES.log\n );\n for (const table of userScope ? snapshot.tables : [])\n for (const fk of table.foreignKeys) {\n if (selected(table.name) !== selected(fk.referencedTable))\n throw invalidState(\n `FK \"${table.name}.${fk.name}\" crosses the managed-table boundary`\n );\n }\n const tables = snapshot.tables.filter((table) => selected(table.name));\n const used = new Set(\n tables.flatMap((table) =>\n table.columns.map((column) =>\n column.type.endsWith(\"[]\") ? column.type.slice(0, -2) : column.type\n )\n )\n );\n const enums = snapshot.enums?.filter((item) => used.has(item.name));\n for (const table of snapshot.tables.filter(\n (table) => !selected(table.name)\n )) {\n if (\n target.dialect === \"postgresql\" &&\n table.columns.some((column) =>\n enums?.some(\n (item) =>\n (column.type.endsWith(\"[]\")\n ? column.type.slice(0, -2)\n : column.type) === item.name\n )\n )\n )\n throw invalidState(\n `Table \"${table.name}\" shares a managed enum across boundary`\n );\n }\n const views = snapshot.views?.filter((view) => selected(view.name));\n return {\n ...snapshot,\n tables,\n ...(enums === undefined ? {} : { enums }),\n ...(views === undefined\n ? {}\n : { views: views.length > 0 ? views : undefined }),\n };\n}\n\n/**\n * The live namespace the adapter is bound to, or undefined when the adapter\n * exposes none.\n *\n * Module-private on purpose: `resolveMigrationEstate` is the ONE reader of this\n * fact in the whole migration layer, so no second caller can take a second look\n * at a value a custom adapter may answer differently each time.\n *\n * The property is read reflectively for one reason: it is an OPTIONAL runtime\n * fact whose declaration lives on the adapter contract, and reading it as\n * untyped data keeps the migration layer from claiming any adapter it is handed\n * — including a caller-supplied custom adapter — has already declared it. A\n * present-but-non-string value is the same as absent: unproven.\n *\n * So is the EMPTY STRING. §1.3 settles it for the shipped path — an empty\n * candidate \"is not passed to identifier validation\" and preserves unbound mode\n * — and `normalizeNamespace` (`src/schema/identifier.ts`) rejects `\"\"` against\n * the identifier grammar, so no stock constructor can produce one. A custom\n * adapter can, and this reader is the seam that admits it: an empty name proves\n * no schema and no database, and reading it as proven would qualify every live\n * statement with an EMPTY quoted segment (`\"\".\"users\"`).\n */\nfunction readAdapterNamespace(driver: AnyDriver): string | undefined {\n const value: unknown = Reflect.get(driver.adapter, \"namespace\");\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * The driver's immutable non-redirecting migration-namespace attestation, or\n * undefined when the driver makes no such claim.\n *\n * Only the exact string `\"non-redirecting\"` is an attestation. There is no\n * provider-name fallback and no inference from class, URL, handshake or\n * server version: a driver that does not carry this exact value is unproven,\n * which is what keeps PlanetScale (and any MySQL2 connection reaching Vitess\n * through the ordinary MySQL protocol) out of effectful migration work.\n */\nexport function readNamespaceAttestation(\n driver: AnyDriver\n): \"non-redirecting\" | undefined {\n const value: unknown = Reflect.get(driver, \"migrationNamespaceAttestation\");\n return value === \"non-redirecting\" ? value : undefined;\n}\n\n/**\n * Reads one catalog statement with its bound values.\n *\n * The same shape the dialect base class's `proveNamespaceExists` takes, spelled\n * here so the migration layer's shared owners can name a catalog read without\n * importing a dialect module for the type.\n */\nexport type CatalogRead = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * A dialect whose CONFIGURED namespace and the server's own spelling of it can\n * differ, and which therefore answers one command-local spelling (§5.2).\n *\n * MySQL is the only such dialect: `lower_case_table_names` can make a\n * differently cased configured value name the same physical database, so\n * catalog resolution accepts a single case-folded candidate — and every later\n * statement of that command has to speak the spelling the SERVER answered with,\n * not the one the configuration carried. `information_schema` rows carry the\n * server's spelling, and on a case-sensitive server so does `USE`.\n *\n * PostgreSQL has no such projection (its `pg_namespace` proof is byte-exact)\n * and SQLite has no namespace at all, so both answer nothing here and their\n * commands keep the exact bound driver they started with.\n *\n * The capability is STRUCTURAL, exactly like the pinned-session hook: a dialect\n * declares it by implementing it. This interface is what the implementation is\n * checked against; {@link readsCommandNamespace} is what a shared owner asks.\n */\nexport interface CommandNamespaceResolver {\n resolveCommandNamespace(read: CatalogRead): Promise<string>;\n}\n\n/**\n * Whether this migration driver resolves a command-local namespace spelling.\n *\n * Read as an optional runtime capability rather than declared on the dialect\n * base class, for the same reason `adapter.namespace` is read reflectively\n * above: it is a fact only one dialect has, and a base-class declaration would\n * make every dialect — including a caller-supplied one — answer for it.\n */\nexport function readsCommandNamespace<T extends object>(\n migrationDriver: T\n): migrationDriver is T & CommandNamespaceResolver {\n return (\n typeof Reflect.get(migrationDriver, \"resolveCommandNamespace\") ===\n \"function\"\n );\n}\n\n/**\n * The two estate facts a bound migration driver carries, derived together.\n *\n * `target` is the DURABLE estate generated artifacts claim;\n * `namespace` is the LIVE execution destination. They coincide for PostgreSQL\n * and deliberately differ for MySQL, whose artifacts are database-relative, so\n * both have to be published — but both come from ONE read of the adapter.\n */\nexport interface MigrationEstate {\n readonly target: MigrationTarget;\n readonly namespace: string | undefined;\n}\n\n/**\n * Derives the one frozen estate target and the one live namespace for a\n * concrete execution driver, from a SINGLE read of `adapter.namespace`.\n *\n * The single read is load-bearing, not tidiness. A custom adapter may expose\n * `namespace` as an accessor; two reads could answer two different strings, and\n * the durable target would then name one estate while live DDL rendered\n * another. Reading once and publishing both facts from that one value makes the\n * disagreement structurally impossible (plan §14).\n *\n * The dialect goes through `normalizeDialect` here and nowhere else in the\n * migration layer's target decisions, so a driver cannot resolve to two targets\n * by being read raw on one path and normalized on another.\n *\n * A PostgreSQL driver whose adapter exposes no namespace is UNPROVEN and\n * refused. It must not silently acquire the `\"public\"` default: generated\n * PostgreSQL SQL contains the schema, so a defaulted target would write a\n * durable claim nothing established.\n */\nexport function resolveMigrationEstate(driver: AnyDriver): MigrationEstate {\n const dialect = normalizeDialect(driver.dialect);\n const namespace = readAdapterNamespace(driver);\n\n if (dialect === \"postgresql\") {\n if (namespace === undefined) {\n throw invalidState(\n `PostgreSQL \"${driver.driverName}\" has no adapter namespace.`,\n { driver: driver.driverName, dialect }\n );\n }\n return { target: Object.freeze({ dialect, namespace }), namespace };\n }\n\n // MySQL and SQLite estates are namespace-free BY DESIGN. MySQL artifacts are\n // database-relative so one history deploys to several database names; SQLite\n // has no namespace concept at all. The live MySQL destination rides beside\n // the target on the bound view, never inside it.\n return { target: Object.freeze({ dialect }), namespace };\n}\n\n/**\n * Human-readable estate description for refusal messages and safe metadata.\n *\n * The live namespace is a SECOND argument because the two facts are separate\n * for MySQL: its durable target is namespace-free by design (§3.1), so the\n * database a command actually touches rides beside it on the bound view. A\n * caller that has it passes it; a caller describing a stored estate target —\n * which carries no database name and must not appear to — does not.\n *\n * Naming it matters wherever the description is what a person consents to: the\n * CLI's `--force-reset` confirmation used to read \"This will DROP ALL TABLES in\n * mysql\", which identifies nothing on the one dialect whose estate target is\n * namespace-free (DECISIONS N6: the confirmation \"must name the target\n * namespace\").\n */\nexport function formatMigrationTarget(\n target: MigrationTarget,\n namespace?: string\n): string {\n if (target.dialect === \"postgresql\") {\n return `${target.dialect} schema \"${target.namespace}\"`;\n }\n return namespace === undefined\n ? target.dialect\n : `${target.dialect} database \"${namespace}\"`;\n}\n\n/**\n * A stored estate is bound to one durable target. PostgreSQL artifacts are\n * schema-qualified, so `alpha` cannot generate or apply as `beta`. MySQL and\n * SQLite compare dialect only.\n *\n * A managed-table list may only grow: the client's list is the estate's\n * frozen list plus tables it adds (adopted or created later). A name of the\n * estate's list missing from the client's, or a list on one side only,\n * refuses.\n */\nexport function assertEstateTargetMatches(\n stored: MigrationTarget,\n live: MigrationTarget\n): void {\n if ((stored.tables === undefined) !== (live.tables === undefined)) {\n throw targetMismatch(\n stored.tables === undefined\n ? \"Estate scope mismatch: estate manages whole DB, client passes tables\"\n : \"Estate scope mismatch: estate has tables list, client passes none\"\n );\n }\n const missing =\n stored.tables?.filter((name) => !live.tables?.includes(name)) ?? [];\n if (missing.length > 0) {\n throw targetMismatch(\n `Estate scope mismatch: tables omits ${missing.map((name) => `\"${name}\"`).join(\", \")}.`\n );\n }\n if (stored.dialect !== live.dialect) {\n throw targetMismatch(\"Estate target dialect mismatch\");\n }\n if (\n stored.dialect === \"postgresql\" &&\n live.dialect === \"postgresql\" &&\n stored.namespace !== live.namespace\n ) {\n throw targetMismatch(\"Estate target namespace mismatch\");\n }\n}\n\n/**\n * The tables a history command manages: the estate's frozen list, every table\n * and view of `snapshots`, less `unmanaged` (a table adopted by a transition, on the\n * side where it is not yet managed). Undefined for an estate without a list,\n * which manages the whole database. Never the client's list: a name only the\n * client lists is a table nothing adopted yet, and it stays the user's.\n */\nexport function managedTables(\n listed: readonly string[] | undefined,\n snapshots: readonly SchemaSnapshot[],\n unmanaged: readonly string[] = []\n): readonly string[] | undefined {\n if (listed === undefined) return;\n const names = new Set(listed);\n for (const snapshot of snapshots) {\n for (const table of snapshot.tables) names.add(table.name);\n for (const view of snapshot.views ?? []) names.add(view.name);\n }\n for (const name of unmanaged) names.delete(name);\n return Object.freeze([...names].sort());\n}\n\n/**\n * A view of `driver` whose target selects `tables` (the whole namespace when\n * undefined): every inventory it reads — introspection, the PostgreSQL\n * catalog digest, invalid indexes, the reset inventory — selects that set.\n * Like every execution view of this layer, it restates `target` only.\n */\nexport function withManagedTables<\n D extends { readonly target: MigrationTarget },\n>(driver: D, tables: readonly string[] | undefined): D {\n const { tables: _replaced, ...target } = driver.target;\n const scoped: D = Object.create(driver);\n Object.defineProperty(scoped, \"target\", {\n value: Object.freeze(tables === undefined ? target : { ...target, tables }),\n enumerable: true,\n });\n return Object.freeze(scoped);\n}\n","/**\n * The one conversion no dialect can perform in SQL: a column BECOMING binary.\n *\n * Every generated `ALTER COLUMN` is a blind re-reading of the bytes already\n * stored. That is harmless when the two types share a reading — `varchar(40)`\n * and `text` are the same characters, `numeric(10,2)` and `numeric(12,2)` the\n * same number — and it is data loss the moment the target is a BINARY column,\n * because the only cast a dialect offers there re-encodes the source's own\n * spelling:\n *\n * · PostgreSQL's `USING col::bytea` writes the ASCII of the old text. A\n * 26-character ULID becomes 26 bytes, not the 16 its codec reads, and every\n * later read is refused as \"not in this column's declared identifier\n * domain\" (measured live on PostgreSQL 16).\n * · SQLite's table rebuild copies the value VERBATIM into the new BLOB\n * column, so `typeof()` still answers `'text'` afterwards — the migration\n * type and the engine binding disagree with no error at all.\n * · MySQL's `MODIFY COLUMN … BINARY(n)` truncates or pads to the declared\n * width without a word in a non-strict `sql_mode`.\n *\n * So the conversion is REFUSED where it is generated, with the manual route\n * named. This is the rule `docs/architecture/native-ids-plan.md` §3 states for\n * an identifier (\"a blind `USING col::bytea` would re-encode text bytes, so it\n * is never emitted\"), and it is stated here in the terms a migration driver\n * actually has: the two column TYPES. A snapshot carries no logical marker that\n * would say \"this BLOB decodes identifiers\", and it does not need one — a\n * verbatim copy into a binary column is unreadable whatever the column holds.\n *\n * PostgreSQL's `uuid` target is deliberately NOT here. `col::uuid` is a real\n * conversion PostgreSQL performs value by value: it succeeds for an estate of\n * canonical uuids and aborts the whole transaction for one that is not, leaving\n * the column as it was. That is a conversion with a wrong answer for nobody.\n *\n * Pure and connection-free, like every other module in this layer.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { Dialect } from \"./drivers/types\";\n\n/** MySQL's two width-carrying binary column spellings. */\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\(\\d+\\)$/i;\nconst MYSQL_BLOB_FAMILY = /^(?:TINYBLOB|BLOB|MEDIUMBLOB|LONGBLOB)$/i;\n\n/** Whether this dialect spells `type` as a column of raw bytes. */\nfunction isBinaryColumnType(type: string, dialect: Dialect): boolean {\n const spelling = type.trim();\n switch (dialect) {\n case \"postgresql\":\n return spelling.toLowerCase() === \"bytea\";\n case \"mysql\":\n return (\n MYSQL_SIZED_BINARY.test(spelling) || MYSQL_BLOB_FAMILY.test(spelling)\n );\n default:\n return spelling.toUpperCase() === \"BLOB\";\n }\n}\n\n/**\n * Refuse an alteration that turns a non-binary column into a binary one.\n *\n * Both sides binary is a WIDTH change and is left alone: `VARBINARY(100)` to\n * `VARBINARY(200)` re-reads the same bytes as the same bytes, which is the\n * property this refusal exists to require.\n */\nexport function refuseBinaryReencoding(\n table: string,\n column: string,\n fromType: string,\n toType: string,\n dialect: Dialect\n): void {\n if (!isBinaryColumnType(toType, dialect)) return;\n if (isBinaryColumnType(fromType, dialect)) return;\n throw new MigrationError(\n `Cannot alter \"${table}\".\"${column}\" from ${fromType} to ${toType}: cast would re-encode bytes.`,\n VibORMErrorCode.INVALID_INPUT\n );\n}\n","/**\n * MigrationDriver Base Class\n *\n * Abstract base class for database-specific migration drivers.\n * Each driver implements DDL generation and introspection for its database.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport type { SqlDialect } from \"@drivers/types\";\nimport type { Schema } from \"@schema/hydration\";\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { refinedStringDefault } from \"@schema/validation/rules/model\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport type {\n AnyDriver,\n SqliteMigrationCapability,\n} from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport type { ResolvedSchemaViews } from \"../../query-engine/raptor3/shared/schema\";\nimport type { ViewColumnSql } from \"../../query-engine/raptor3/view-body\";\nimport { refuseBinaryReencoding } from \"../binary-conversion\";\nimport type { Sha256 } from \"../identity\";\nimport type { ResolvedMigrationLimits } from \"../limits\";\nimport {\n applyNativeRename,\n type NativeRenameOperation,\n} from \"../native-rename\";\nimport type {\n AutoViewCascade,\n AutoViewObject,\n AutoViewStorage,\n DiffOperation,\n EnumDependentCheck,\n IndexDef,\n MigrationTarget,\n SchemaSnapshot,\n TableDef,\n} from \"../types\";\nimport { defaultGeneratedPrimaryKeyName, derivedMigrationName } from \"../utils\";\nimport type { PushTargetIdentity } from \"../v1-types\";\nimport type { BoundMigrationDriver } from \".\";\nimport type { Dialect, MigrationCapabilities } from \"./types\";\n\nconst ARRAY_TYPE = /\\[\\]$/;\n\n/** How the serializer ends an index, unique or foreign key name it derives. */\nconst DERIVED_TAIL = /_(?:idx|f?key)$/;\n\n/** A feature of a live table that its adoption would take over unseen. */\nexport interface AdoptionHazard {\n readonly table: string;\n readonly feature: string;\n}\n\n/** A name a native rename carries along, and the statement kind that does. */\nexport interface DerivedRename {\n readonly kind: \"constraint\" | \"index\" | \"type\";\n readonly to: string;\n}\n\n/** The two control tables the fingerprint leaves out. */\nexport interface ControlTableNames {\n readonly state: string;\n readonly log: string;\n}\n\n/**\n * Context passed to DDL generation methods.\n * Contains information needed for operations that require knowledge of the current schema.\n */\nexport interface DDLContext {\n /**\n * Where the rendered statement is going.\n *\n * REQUIRED, and deliberately not defaulted anywhere: an artifact is durable\n * and a live statement is not, and the two differ for MySQL (relative\n * artifacts, qualified live SQL). A dispatcher default would reintroduce\n * exactly the implicit mode this fact replaces, so every caller states it.\n * Generation and generated rollback pass `\"artifact\"`; push, live reset and\n * every immediate DDL path pass `\"live\"`. SQLite ignores the distinction.\n */\n readonly destination: \"artifact\" | \"live\";\n\n /**\n * Current database schema snapshot.\n * Required for SQLite table recreation operations.\n */\n currentSchema?: SchemaSnapshot;\n\n /**\n * The operations of this batch that run *before* the one being generated.\n *\n * `currentSchema` is introspected once, before the batch starts, so on its\n * own it describes the database as it was — not as the statements already\n * emitted have left it. A SQLite table recreation has to name the indexes the\n * table holds at the moment it runs, because `DROP TABLE` takes them with it;\n * see `SQLite3MigrationDriver.getCurrentTable`.\n */\n precedingOperations?: DiffOperation[];\n /** Remaining intent in this same compilation batch, for physical coalescing. */\n followingOperations?: readonly DiffOperation[];\n}\n\n// Extract individual operation types from the DiffOperation union\nexport type CreateTableOperation = Extract<\n DiffOperation,\n { type: \"createTable\" }\n>;\nexport type DropTableOperation = Extract<DiffOperation, { type: \"dropTable\" }>;\nexport type RenameTableOperation = Extract<\n DiffOperation,\n { type: \"renameTable\" }\n>;\nexport type AddColumnOperation = Extract<DiffOperation, { type: \"addColumn\" }>;\nexport type DropColumnOperation = Extract<\n DiffOperation,\n { type: \"dropColumn\" }\n>;\nexport type RenameColumnOperation = Extract<\n DiffOperation,\n { type: \"renameColumn\" }\n>;\nexport type AlterColumnOperation = Extract<\n DiffOperation,\n { type: \"alterColumn\" }\n>;\nexport type CreateIndexOperation = Extract<\n DiffOperation,\n { type: \"createIndex\" }\n>;\nexport type DropIndexOperation = Extract<DiffOperation, { type: \"dropIndex\" }>;\nexport type AddForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"addForeignKey\" }\n>;\nexport type DropForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"dropForeignKey\" }\n>;\nexport type AddUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"addUniqueConstraint\" }\n>;\nexport type DropUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"dropUniqueConstraint\" }\n>;\nexport type AddPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"addPrimaryKey\" }\n>;\nexport type DropPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"dropPrimaryKey\" }\n>;\nexport type CreateViewOperation = Extract<\n DiffOperation,\n { type: \"createView\" }\n>;\nexport type DropViewOperation = Extract<DiffOperation, { type: \"dropView\" }>;\nexport type CreateEnumOperation = Extract<\n DiffOperation,\n { type: \"createEnum\" }\n>;\nexport type DropEnumOperation = Extract<DiffOperation, { type: \"dropEnum\" }>;\nexport type AlterEnumOperation = Extract<DiffOperation, { type: \"alterEnum\" }>;\n\n/**\n * What a dialect states one operation compiles to: one statement, or the\n * ordered statements it needs. {@link MigrationDriver.compileStatements}\n * filters blanks once for every operation.\n */\ntype GeneratedStatements = string | readonly string[];\n\n/**\n * Abstract base class for migration drivers.\n *\n * Each database (PostgreSQL, SQLite, LibSQL, etc.) extends this class\n * to provide database-specific DDL generation and schema introspection.\n */\n/** The schema a view's body is written over. */\nexport interface ViewWriteContext {\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\n/** A view's body as its database takes it. */\nexport interface WrittenView {\n /** The body in the driver's language, without parameter, wrapper or marker. */\n readonly sql: string;\n /** The decoder shape of a view row, as JSON data: part of the view's identity. */\n readonly shape: unknown;\n /** Physical names of every table and view the body reads, each once. */\n readonly reads: readonly string[];\n}\n\n/**\n * A SQL dialect's view writer, as data: the read compiler writes the body on\n * `adapter`, and its values as `dialect`'s literals (`writeView`,\n * `view-definition.ts`). Data and not a function, so that a migration driver\n * imports no compiler: whatever registers a driver would load the engine.\n */\nexport interface SqlViewWriter {\n readonly dialect: SqlDialect;\n /** Made for one body: its table renderer is wrapped to note what the body reads. */\n readonly adapter: DatabaseAdapter;\n /** How the dialect spells an aggregated view's columns: its migration driver. */\n readonly columns: ViewColumnSql;\n}\n\n/** A driver that writes a view's body in its own language (SurrealDB). */\nexport interface ViewBodyWriter {\n /**\n * The body of `view`, a view of `context.schema`: refused, with the view\n * named, where its query says what a view cannot hold on this database.\n */\n write(context: ViewWriteContext, view: AnyModel): WrittenView;\n}\n\n/** See {@link MigrationDriver.viewWriter}. */\nexport type ViewWriter = SqlViewWriter | ViewBodyWriter;\n\nexport abstract class MigrationDriver {\n /**\n * The SQL dialect this driver targets.\n */\n abstract readonly dialect: Dialect;\n\n /**\n * The specific driver name (e.g., \"pg\", \"postgres\", \"pglite\", \"sqlite3\", \"libsql\").\n * Used for driver-specific registration and lookup.\n */\n abstract readonly driverName: string;\n\n /**\n * Capabilities supported by this driver.\n */\n abstract readonly capabilities: MigrationCapabilities;\n\n // ===========================================================================\n // ESTATE BINDING (installed by the registry, never mutated on a singleton)\n // ===========================================================================\n\n // All three are `declare`: the class DECLARES the shape a bound view has and\n // emits no field for it. Under `useDefineForClassFields` (tsconfig target\n // es2022) an ordinary optional field would install a writable, enumerable own\n // property valued `undefined` on the REGISTERED SINGLETON — module-level\n // state that `Reflect.set` could then fill in, which §3.1 forbids. With\n // `declare`, `\"namespace\" in postgresMigrationDriver` is false, and the only\n // instances carrying these facts are the frozen views the registry defines\n // them on.\n\n /**\n * The estate target this instance is bound to.\n *\n * Absent on the REGISTERED singleton, which stays stateless: binding happens\n * at lookup and produces a separate frozen view whose prototype is the\n * singleton. Renderers that need the estate must handle the unbound case\n * rather than assume one, because a singleton reached by name renders\n * artifact SQL with no estate behind it.\n */\n declare readonly target?: MigrationTarget;\n\n /**\n * The exact concrete execution driver this instance was bound to, retained\n * for live admission (its immutable attestation) and for the adapter's\n * capabilities. Absent on the unbound singleton.\n */\n declare readonly executionDriver?: AnyDriver;\n\n /**\n * The bound SQLite driver's migration capability, read once at binding.\n * Absent on the unbound singleton and on every other dialect.\n */\n declare readonly sqliteMigrationCapability?: SqliteMigrationCapability;\n\n /**\n * The live execution namespace read once from the bound adapter.\n *\n * Present for PostgreSQL (its target proved it) and for a bound MySQL\n * adapter; absent for an unbound MySQL adapter used for artifact-only work\n * and for SQLite, which has no namespace.\n */\n declare readonly namespace?: string;\n\n /**\n * The limits of the command this instance is bound for (plans S1, T5a).\n * Absent on the unbound singleton, which renders under the defaults.\n */\n declare readonly limits?: ResolvedMigrationLimits;\n\n /**\n * Who writes a view's body, made for one body, or nothing where VibORM\n * creates no view. A SQL dialect answers with its own adapter, so a bundle\n * of one dialect's migrations carries one, under one fixed configuration\n * of the dialect, so that two drivers of it write one text (no shared\n * relation bodies, no bound a transport puts on a statement: D1's\n * expression depth and compound terms, Neki's relations; every tier a\n * column of the schema may need). SurrealDB answers with a writer of its\n * own language.\n */\n viewWriter(): ViewWriter | undefined {\n return;\n }\n\n /**\n * Whether a view declared `.materialized()` is a materialized view here:\n * stored, indexed and refreshed (PostgreSQL). Everywhere else it is an\n * ordinary view, by the maintainer's choice, and `.materialized()` and its\n * indexes change nothing a migration writes: not the snapshot, not the\n * view's identity, not the program.\n */\n materializesViews(): boolean {\n return false;\n }\n\n /**\n * Whether a view declared `.materialized({ refresh: \"auto\" })` is a table\n * here, which triggers on its source keep current at each write (every SQL\n * dialect VibORM creates views on). Elsewhere it is what `.materialized()`\n * makes it: SurrealDB keeps every view current itself.\n */\n keepsViewsByTriggers(): boolean {\n return false;\n }\n\n /**\n * The objects beside its table that keep a `refresh: \"auto\"` view named\n * `view` current here, sorted by kind then name: what a snapshot records\n * and introspection finds of it.\n */\n autoViewObjects(_view: string, _storage: AutoViewStorage): AutoViewObject[] {\n return [];\n }\n\n /**\n * What a `refresh: \"auto\"` view named `view` needs where a cascade fires no\n * trigger (MySQL): a trigger before each delete of a parent whose cascade\n * reaches the view's source, refusing what such triggers cannot do. None\n * where a cascade fires the triggers of the rows it changes.\n */\n autoViewCascades(\n _view: string,\n _storage: AutoViewStorage,\n _tables: readonly TableDef[]\n ): AutoViewCascade[] | undefined {\n return;\n }\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Introspects the current database schema.\n *\n * @param executeRaw - Function to execute raw SQL queries\n * @returns The current schema snapshot\n */\n abstract introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<SchemaSnapshot>;\n\n /**\n * Proves external physical requirements encoded by authenticated snapshots.\n * Dialects with no such requirement keep the no-op owner here.\n *\n * `program` is the statement list the command is about to run (empty when\n * it runs none), so a dialect can refuse what that program would destroy\n * (SQLite: a recreation's dependent triggers and views). Required: a caller\n * cannot skip these refusals by leaving it out.\n *\n * Answers whether the program must commit where `catalogCommitBoundaries`\n * names (PlanetScale's Neki). A caller that `splits` commits there itself\n * and is told so; any other is refused such a program before effects.\n */\n async preflightSchemaRequirements(\n _snapshots: readonly SchemaSnapshot[],\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n _program: readonly string[],\n _splits?: boolean\n ): Promise<boolean> {\n // Most dialects have no external schema requirement to prove.\n return false;\n }\n\n /**\n * What each named live table carries that changes how it behaves and that\n * no snapshot describes, so the adoption proof cannot see it (a trigger, a\n * conflict clause, a collation the declaration does not state): one entry\n * per table and feature, none when there is nothing. Asked of the tables a\n * command's path adopts (`assertAdoptable`, `proof.ts`): a managed table\n * keeps whatever it has, and `verify` never asks. `introspectSchema` asks it\n * of every table it reads, whose document cannot carry these either.\n */\n async adoptionHazards(\n _tables: readonly string[],\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<readonly AdoptionHazard[]> {\n return [];\n }\n\n /**\n * Returns this database's own spelling of each declared partial-index\n * predicate, so the differ can compare a declaration against what the catalog\n * gave back (Decision 7.4).\n *\n * Optional, and implemented only where the two spellings can differ.\n * PostgreSQL deparses through `pg_get_expr`, so a declared `active = true`\n * reads back as `(active = true)` and every push re-creates the index;\n * SQLite stores the CREATE INDEX statement verbatim and has nothing to\n * reconcile; MySQL refuses a partial index outright.\n *\n * `executeRaw` runs on ONE pinned connection for the whole call — the\n * canonicalization may need session-local scratch objects, which a pooled\n * connection per statement would scatter. Positional result; `undefined` at\n * a position means the database did not answer, and the differ then refuses\n * to call that predicate equal to anything. `executeBatch` is given where\n * no connection can be pinned (Neon HTTP): each request may be a new\n * session, so session-local work goes out as one request.\n */\n canonicalizeIndexPredicates?(\n tableName: string,\n predicates: readonly string[],\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n executeBatch?: <T>(\n statements: readonly string[]\n ) => Promise<ReadonlyArray<{ rows: T[] }>>\n ): Promise<ReadonlyArray<string | undefined>>;\n\n /**\n * The CHECK constraints on the columns of each named enum, read from the\n * live catalog for `push`: a schema snapshot models none, and an enum\n * recreation must drop and re-add them around its text conversion. Optional,\n * and implemented only by PostgreSQL, the one dialect that recreates a type\n * under its columns.\n */\n readEnumDependentChecks?(\n enumNames: readonly string[],\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<ReadonlyArray<EnumDependentCheck & { readonly enumName: string }>>;\n\n /**\n * The live managed schema's fingerprint in one statement, where this\n * dialect can compute it (PostgreSQL, `postgres/catalog-digest.ts`): the\n * statement for a caller that embeds it, and the digest read, `undefined`\n * where it abstains. Absent elsewhere, and the caller introspects. The bound\n * driver owns it, so another dialect's bundle never carries it.\n */\n catalogDigestQuery?(\n this: BoundMigrationDriver,\n control: ControlTableNames,\n deparsedPredicates?: boolean\n ): { readonly sql: string; readonly parameters: unknown[] };\n catalogDigest?(\n this: BoundMigrationDriver,\n producer: AnyDriver,\n control: ControlTableNames\n ): Promise<Sha256 | undefined>;\n\n /**\n * Explains why one inverted operation cannot be rendered as an automatic\n * rollback on this dialect. Generation owns the persisted rollback policy;\n * the driver owns the physical boundary that makes an inverse unsafe.\n */\n getIrreversibleRollbackReason(_operation: DiffOperation): string | undefined {\n return undefined;\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n /**\n * Maps a VibORM scalar type to the native database column type.\n *\n * @param scalar - The scalar definition\n * @param scalarState - The scalar state with type info\n * @returns The native column type string\n */\n /**\n * `idDomain` is the identifier domain this column holds, which a foreign key\n * DERIVES from the key it references and therefore cannot be read off the\n * scalar. The physical type comes from the one storage owner\n * ({@link idStorageOf}), so the column this creates and the parameter the\n * engine binds into it are one decision.\n */\n abstract mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string;\n\n /**\n * Final pass over a serialized table before diffing/DDL generation.\n * Lets drivers apply table-aware type adjustments (e.g. MySQL rewrites\n * keyed TEXT columns to VARCHAR, since TEXT cannot be indexed without a\n * key length). Default: identity.\n */\n finalizeTable(table: TableDef): TableDef {\n return table;\n }\n\n /** A generated junction, before {@link finalizeTable}. */\n markJunction?(table: TableDef): TableDef;\n\n /** Whether these operations, after a reset or not, cannot share a transaction. */\n buildsApart?(operations: readonly DiffOperation[], reset?: boolean): boolean;\n\n /** A driver's own answer to what a push targets, where it has one. */\n pushTarget?(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<PushTargetIdentity>;\n\n /**\n * What a committed program of `statements` left running, waited for before\n * the command goes on (SurrealDB's indexes built in the background).\n */\n awaitIndexBuilds?(\n producer: AnyDriver,\n statements: readonly string[]\n ): Promise<void>;\n\n /** A driver's own hold on a command, where no pinned session can take one. */\n holdLock?<T>(\n driver: AnyDriver,\n lockWait: number,\n run: () => Promise<T>\n ): Promise<T>;\n\n /** The exact generated PK name used by this driver's DDL and its inverse. */\n generatedPrimaryKeyName(tableName: string, name?: string): string {\n return defaultGeneratedPrimaryKeyName(tableName, name);\n }\n\n /** Project exactly this driver's compiled rename before diffing or inversion. */\n projectNativeRename(\n snapshot: SchemaSnapshot,\n operation: NativeRenameOperation\n ): SchemaSnapshot {\n const projected = applyNativeRename(snapshot, operation);\n const renames = derivedRenamesOf(this, operation, snapshot);\n if (renames.size === 0) return projected;\n const name = (from: string) => renames.get(from)?.to ?? from;\n const renamed = <T extends { readonly name: string }>(\n items: readonly T[]\n ) => items.map((item) => ({ ...item, name: name(item.name) }));\n const owner =\n operation.type === \"renameTable\" ? operation.to : operation.tableName;\n return {\n ...projected,\n ...(projected.enums ? { enums: renamed(projected.enums) } : {}),\n tables: projected.tables.map((table) => {\n if (table.name !== owner) return table;\n const { primaryKey } = table;\n return {\n ...table,\n columns: table.columns.map((column) => {\n const element = column.type.replace(ARRAY_TYPE, \"\");\n const type = name(element) + column.type.slice(element.length);\n return { ...column, type };\n }),\n ...(primaryKey?.name\n ? { primaryKey: { ...primaryKey, name: name(primaryKey.name) } }\n : {}),\n indexes: renamed(table.indexes),\n uniqueConstraints: renamed(table.uniqueConstraints),\n foreignKeys: renamed(table.foreignKeys),\n };\n }),\n };\n }\n\n /**\n * The statements that move `renames`, the names a native rename of `owner`\n * carries along, on a dialect whose renames carry them (PostgreSQL,\n * MySQL). `table` is the owner as the rename leaves it, still holding the\n * old names. Absent where a rename leaves every name as it is (SQLite).\n */\n protected renameDerivedNames?(\n owner: string,\n renames: ReadonlyMap<string, DerivedRename>,\n table: TableDef,\n context: DDLContext\n ): string[];\n\n /**\n * The raw indexes a column rename leaves with a stale marker, as the rename\n * leaves them: the database's index follows the column, but the marker\n * beside it still names the old one, so each driver writes it again (a\n * comment, or the index re-created). One the program drops anyway is left\n * to that drop.\n */\n protected rawIndexesRenamedBy(\n op: RenameColumnOperation,\n context: DDLContext\n ): IndexDef[] {\n let indexes =\n this.schemaAtOperation(context)?.tables.find(\n ({ name }) => name === op.tableName\n )?.indexes ?? [];\n // The indexes the program already dropped or created on the table (a\n // rollback restores the old index before it renames its column back).\n for (const operation of context.precedingOperations ?? []) {\n if (\n operation.type === \"dropIndex\" &&\n operation.tableName === op.tableName\n )\n indexes = indexes.filter(({ name }) => name !== operation.indexName);\n if (\n operation.type === \"createIndex\" &&\n operation.tableName === op.tableName\n )\n indexes = [...indexes, operation.index];\n }\n const dropped = new Set(\n (context.followingOperations ?? []).flatMap((operation) =>\n operation.type === \"dropIndex\" && operation.tableName === op.tableName\n ? [operation.indexName]\n : []\n )\n );\n return indexes.flatMap((index) =>\n index.raw && index.columns.includes(op.from) && !dropped.has(index.name)\n ? [\n {\n ...index,\n columns: index.columns.map((column) =>\n column === op.from ? op.to : column\n ),\n },\n ]\n : []\n );\n }\n\n /** Native identity and PK effects needed by rename and enum DDL at this prefix. */\n protected schemaAtOperation(context: DDLContext): SchemaSnapshot | undefined {\n let snapshot = context.currentSchema;\n if (!snapshot) return undefined;\n for (const operation of context.precedingOperations ?? []) {\n if (\n operation.type === \"renameTable\" ||\n operation.type === \"renameColumn\"\n ) {\n snapshot = this.projectNativeRename(snapshot, operation);\n } else if (operation.type === \"createTable\") {\n const table = operation.table;\n snapshot = {\n ...snapshot,\n tables: [\n ...snapshot.tables,\n table.primaryKey\n ? {\n ...table,\n primaryKey: {\n ...table.primaryKey,\n name: this.generatedPrimaryKeyName(\n table.name,\n table.primaryKey.name\n ),\n },\n }\n : table,\n ],\n };\n } else if (operation.type === \"dropTable\") {\n snapshot = {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) => table.name !== operation.tableName\n ),\n };\n } else if (\n operation.type === \"addPrimaryKey\" ||\n operation.type === \"dropPrimaryKey\"\n ) {\n snapshot = {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? {\n ...table,\n primaryKey:\n operation.type === \"addPrimaryKey\"\n ? {\n ...operation.primaryKey,\n name: this.generatedPrimaryKeyName(\n operation.tableName,\n operation.primaryKey.name\n ),\n }\n : undefined,\n }\n : table\n ),\n };\n }\n }\n return snapshot;\n }\n\n // Note: getDefaultExpression is implemented below as a common method\n // Override it in subclasses only if database-specific behavior is needed\n\n /**\n * Gets the column type for an enum field.\n *\n * @param tableName - The table name\n * @param columnName - The column name\n * @param values - The enum values\n * @returns The column type (e.g., \"users_status_enum\" for PG, \"TEXT\" for SQLite)\n */\n abstract getEnumColumnType(\n tableName: string,\n columnName: string,\n values: string[]\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n abstract generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropTable(\n op: DropTableOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateRenameTable(\n op: RenameTableOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n abstract generateAddColumn(\n op: AddColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropColumn(\n op: DropColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateRenameColumn(\n op: RenameColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n abstract generateCreateIndex(\n op: CreateIndexOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropIndex(\n op: DropIndexOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n abstract generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n abstract generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n abstract generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - View Operations\n // ===========================================================================\n\n /**\n * `CREATE VIEW`, its body wrapped by `wrappedViewBody` so it carries its\n * marker; a materialized view's creation is followed by its indexes.\n */\n abstract generateCreateView(\n op: CreateViewOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropView(\n op: DropViewOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n abstract generateCreateEnum(\n op: CreateEnumOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropEnum(\n op: DropEnumOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL COMPILATION\n // ===========================================================================\n\n protected filterStatements(\n statements: readonly (string | null | undefined)[]\n ): string[] {\n return statements.filter(\n (statement): statement is string =>\n statement !== null &&\n statement !== undefined &&\n statement.trim().length > 0\n );\n }\n abstract escapeIdentifier(name: string): string;\n abstract getDefaultExpression(\n _scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined;\n\n /** Literal defaults cross the scalar's authoritative write admission once. */\n protected literalDefaultValue(state: ScalarState): unknown {\n const value = state.default;\n if (\n value == null ||\n typeof value === \"function\" ||\n state.autoGenerate ||\n jsonNullKindOf(value) ||\n state.decimal !== undefined\n )\n return value;\n if (typeof value === \"number\" && !Number.isFinite(value))\n throw new MigrationError(\n `Invalid default value: ${value} is not a finite number`,\n VibORMErrorCode.INVALID_INPUT\n );\n const result = state.base[\"~standard\"].validate(value);\n // A string's own validator judges its default where a create takes it;\n // the column still holds one it refuses (`refinedStringDefault`).\n if (!(\"value\" in result) && refinedStringDefault(state)) return value;\n if (!(\"value\" in result))\n throw new MigrationError(\n `Invalid ${state.type} literal default; the declared scalar schema refused it before DDL.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return result.value;\n }\n\n // ===========================================================================\n // LIVE CONTROL AND NAMESPACE\n // ===========================================================================\n\n /**\n * Proves the configured namespace exists before an empty inventory or an\n * empty applied set may be published.\n *\n * A catalog-driven read cannot otherwise tell a configured-but-absent\n * namespace from an existing namespace holding zero managed objects, and\n * PostgreSQL reports a missing schema and a missing table with the same\n * SQLSTATE. Default: nothing to prove — SQLite has no namespace, and this\n * is not a SQLite namespace feature. PostgreSQL (`pg_namespace`) and MySQL\n * (`information_schema.SCHEMATA`) install their proofs in their own units.\n */\n proveNamespaceExists(\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<void> {\n return Promise.resolve();\n }\n\n // ===========================================================================\n // PUSH PROBES\n // ===========================================================================\n\n /** Whether a table holds any row, which `push` reads before adding a required field. */\n abstract tableHoldsRows(producer: AnyDriver, table: string): Promise<boolean>;\n /** A stored value of `column` that `declared` does not hold, if a row has one. */\n abstract undeclaredValue(\n producer: AnyDriver,\n table: string,\n column: string,\n declared: readonly string[]\n ): Promise<{ readonly stored: unknown } | undefined>;\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n /**\n * Generates SQL for acquiring a migration lock, with a stable `acquired`\n * alias so the caller reads one known column rather than a provider-shaped\n * name derived from the expression text.\n *\n * Returns null when this dialect takes no session lock (SQLite/LibSQL, which\n * keep their own single-connection queue).\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateAcquireLock(lockId: number): string | null;\n\n /**\n * Generates SQL for releasing a migration lock, with a stable `released`\n * alias. Returns null on the dialects that take no lock.\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateReleaseLock(lockId: number): string | null;\n\n /**\n * Whether the provider's answer to {@link generateAcquireLock} PROVES the\n * lock is held.\n *\n * Asked only when a lock statement was emitted, so the dialects that emit\n * none never reach it. The default is `false` because a lock nobody proved is\n * a lock nobody holds: MySQL's `GET_LOCK` returns `0` on timeout and `NULL`\n * on error, and the previous owner discarded that answer entirely and ran the\n * \"protected\" work anyway.\n */\n provesLockAcquired(_rows: readonly unknown[]): boolean {\n return false;\n }\n\n /**\n * Whether the provider's answer to {@link generateReleaseLock} PROVES the\n * lock was released. A false answer condemns the session: it is holding a\n * lock nobody will release, and returning it to a pool would strand it.\n */\n provesLockReleased(_rows: readonly unknown[]): boolean {\n return false;\n }\n\n /**\n * Selects the live migration target on a pinned session, or null when this\n * dialect has nothing to select.\n *\n * MySQL is the only arm: its generated artifacts are database-relative, so\n * the target has to be selected on the connection that executes them. Every\n * other dialect qualifies its statements and must never touch session state\n * (§13).\n */\n generateSelectTarget(): string | null {\n return null;\n }\n\n /**\n * Whether this server holds one command's migration lock as the session\n * lock alone, taken once before its first transaction and never mixed with\n * the transaction lock (PlanetScale's Neki). Asked once per command, on its\n * pinned session, before any lock. Default: no.\n */\n holdsSessionLock(\n _read: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<boolean> {\n return Promise.resolve(false);\n }\n\n /**\n * Whether this command's server refuses to plan a statement against any\n * relation in a transaction that changed the schema (PlanetScale's Neki,\n * `NK013` \"[817] … earlier DDL in this transaction is not reflected in the\n * router's schema view\"), VibORM's own ledger and marker writes included:\n * its work then runs stepwise, each statement committed alone, its control\n * writes in their own. Known once {@link holdsSessionLock} answered for the\n * command. Default: no.\n */\n commitsSchemaChangesAlone(): boolean {\n return false;\n }\n\n /**\n * The session lock PostgreSQL stepwise work keeps (plan D1), taken while\n * the session holds the transaction lock on the same key (or alone, where\n * {@link holdsSessionLock}); null elsewhere.\n */\n generateSessionLock(_lockId: number): string | null {\n return null;\n }\n\n /**\n * A condition true while no command holds the migration lock (plan D5).\n * The default never proves it: only PostgreSQL can ask.\n */\n generateLockFree(_lockId: number): string {\n return \"false\";\n }\n\n /**\n * Proves a locked session may run this command's work, once, after its\n * target is selected, and returns the driver the command renders from.\n * Default: nothing to prove.\n */\n proveSession(\n _read: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<this> {\n return Promise.resolve(this);\n }\n\n /** The statements a sequential program runs first, on its producer. */\n programPreamble(_producer: AnyDriver): Promise<readonly string[]> {\n return Promise.resolve([]);\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n /**\n * The live-namespace table inventory: the exact set of tables a reset may\n * drop, as a BOUND read.\n *\n * `{ sql, params }` rather than a bare string because §4.2/§5.2 require the\n * namespace to reach a catalog predicate through the parameter channel: a\n * bare-string seam has nothing to bind through, so it can only splice the\n * name into the statement as an escaped literal.\n *\n * @returns Bound SELECT returning rows with a `name` column\n */\n abstract generateInventoryTables(): { sql: string; params: unknown[] };\n\n /**\n * The live-namespace enum inventory, or null for dialects with no standalone\n * enum types.\n */\n abstract generateInventoryEnums(): {\n sql: string;\n params: unknown[];\n } | null;\n abstract generateDropTableSQL(tableName: string): string;\n abstract generateDropEnumSQL(enumName: string): string | null;\n\n // ===========================================================================\n // DISPATCH (final - not meant to be overridden)\n // ===========================================================================\n\n /**\n * The one owner of provider statement boundaries for generated DDL.\n */\n compileStatements(\n operation: DiffOperation,\n context: DDLContext\n ): readonly string[] {\n const generated = generateOperationOf(this, operation, context);\n const statements = typeof generated === \"string\" ? [generated] : generated;\n return this.filterStatements(\n operation.type === \"renameTable\" || operation.type === \"renameColumn\"\n ? [...statements, ...compileDerivedRenamesOf(this, operation, context)]\n : statements\n );\n }\n\n /**\n * Generates display DDL for a diff operation.\n */\n generateDDL(operation: DiffOperation, context: DDLContext): string {\n return this.compileStatements(operation, context).join(\";\\n\");\n }\n}\n\nfunction derivedRenamesOf(\n driver: MigrationDriver,\n operation: NativeRenameOperation,\n snapshot: SchemaSnapshot | undefined\n): Map<string, DerivedRename> {\n const [from, to] =\n operation.type === \"renameTable\"\n ? [operation.from, operation.to]\n : [operation.tableName, operation.tableName];\n const renamed = (column: string) =>\n operation.type === \"renameColumn\" && column === operation.from\n ? operation.to\n : column;\n const renames = new Map<string, DerivedRename>();\n const follow = (\n kind: DerivedRename[\"kind\"],\n name: string | undefined,\n derive: (table: string, column: (name: string) => string) => string,\n tailed = false\n ) => {\n if (name === undefined) return;\n const tail = name.slice(from.length);\n const next =\n name === derive(from, (column) => column)\n ? derive(to, renamed)\n : tailed &&\n name.startsWith(`${from}_`) &&\n DERIVED_TAIL.test(tail) &&\n derivedMigrationName(to + tail) === to + tail\n ? to + tail\n : name;\n if (next !== name) renames.set(name, { kind, to: next });\n };\n const named =\n (columns: readonly string[], suffix: string) =>\n (owner: string, column: (name: string) => string) =>\n derivedMigrationName(\n `${owner}_${columns.map(column).join(\"_\")}_${suffix}`\n );\n const table = snapshot?.tables.find((item) => item.name === from);\n if (!(table && driver[\"renameDerivedNames\"])) return renames;\n follow(\"constraint\", table.primaryKey?.name, (owner) =>\n driver.generatedPrimaryKeyName(owner)\n );\n for (const column of table.columns) {\n follow(\"type\", column.type.replace(ARRAY_TYPE, \"\"), (owner, renamedTo) =>\n driver.getEnumColumnType(owner, renamedTo(column.name), [])\n );\n }\n for (const index of table.indexes) {\n if (index.raw) continue;\n follow(\"index\", index.name, named(index.columns, \"idx\"), true);\n }\n for (const unique of table.uniqueConstraints) {\n follow(\"index\", unique.name, named(unique.columns, \"key\"), true);\n }\n for (const key of table.foreignKeys) {\n follow(\"constraint\", key.name, named(key.columns, \"fkey\"), true);\n }\n return renames;\n}\n\nfunction compileDerivedRenamesOf(\n driver: MigrationDriver,\n operation: NativeRenameOperation,\n context: DDLContext\n): string[] {\n const snapshot = driver[\"schemaAtOperation\"](context);\n const renames = derivedRenamesOf(driver, operation, snapshot);\n if (renames.size === 0) return [];\n const owner =\n operation.type === \"renameTable\" ? operation.to : operation.tableName;\n const table = applyNativeRename(snapshot!, operation).tables.find(\n (item) => item.name === owner\n )!;\n return driver[\"renameDerivedNames\"]!(owner, renames, table, context);\n}\n\nfunction generateOperationOf(\n driver: MigrationDriver,\n operation: DiffOperation,\n context: DDLContext\n): GeneratedStatements {\n switch (operation.type) {\n case \"createTable\":\n return driver.generateCreateTable(operation, context);\n case \"dropTable\":\n return driver.generateDropTable(operation, context);\n case \"renameTable\":\n return driver.generateRenameTable(operation, context);\n case \"addColumn\":\n return driver.generateAddColumn(operation, context);\n case \"dropColumn\":\n return driver.generateDropColumn(operation, context);\n case \"renameColumn\":\n return driver.generateRenameColumn(operation, context);\n case \"alterColumn\":\n refuseBinaryReencoding(\n operation.tableName,\n operation.columnName,\n operation.from.type,\n operation.to.type,\n driver.dialect\n );\n return driver.generateAlterColumn(operation, context);\n case \"createIndex\":\n return driver.generateCreateIndex(operation, context);\n case \"dropIndex\":\n return driver.generateDropIndex(operation, context);\n case \"addForeignKey\":\n return driver.generateAddForeignKey(operation, context);\n case \"dropForeignKey\":\n return driver.generateDropForeignKey(operation, context);\n case \"addUniqueConstraint\":\n return driver.generateAddUniqueConstraint(operation, context);\n case \"dropUniqueConstraint\":\n return driver.generateDropUniqueConstraint(operation, context);\n case \"addPrimaryKey\":\n return driver.generateAddPrimaryKey(operation, context);\n case \"dropPrimaryKey\":\n return driver.generateDropPrimaryKey(operation, context);\n case \"createView\":\n return driver.generateCreateView(operation, context);\n case \"dropView\":\n return driver.generateDropView(operation, context);\n case \"createEnum\":\n return driver.generateCreateEnum(operation, context);\n case \"dropEnum\":\n return driver.generateDropEnum(operation, context);\n case \"alterEnum\":\n return driver.generateAlterEnum(operation, context);\n default:\n throw new MigrationError(\n `Unknown operation type: ${(operation as any).type}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n}\n","/**\n * Migration Driver Registry\n *\n * Central registry for migration drivers. Drivers are registered by their\n * driver name and can be looked up by driver name or dialect.\n *\n * This module registers nothing: the entry an application imports does\n * (`dialects/*.ts`), so a bundle carries only the dialects it registers.\n */\n\nimport type {\n AnyDriver,\n SqliteMigrationCapability,\n} from \"../../drivers/driver\";\nimport {\n type DiagnosticDisclosure,\n MigrationError,\n VibORMErrorCode,\n} from \"../../errors\";\nimport {\n DEFAULT_MIGRATION_LIMITS,\n type ResolvedMigrationLimits,\n} from \"../limits\";\nimport { resolveMigrationEstate, selectManagedSnapshot } from \"../target\";\nimport type { MigrationTarget } from \"../types\";\nimport type { MigrationDriver } from \"./base\";\nimport type { Dialect } from \"./types\";\n\nexport type {\n AddColumnOperation,\n AddForeignKeyOperation,\n AddPrimaryKeyOperation,\n AddUniqueConstraintOperation,\n AlterColumnOperation,\n AlterEnumOperation,\n CreateEnumOperation,\n CreateIndexOperation,\n CreateTableOperation,\n DDLContext,\n DropColumnOperation,\n DropEnumOperation,\n DropForeignKeyOperation,\n DropIndexOperation,\n DropPrimaryKeyOperation,\n DropTableOperation,\n DropUniqueConstraintOperation,\n RenameColumnOperation,\n RenameTableOperation,\n} from \"./base\";\n// Export base class and types\nexport { MigrationDriver } from \"./base\";\nexport type { Dialect, MigrationCapabilities } from \"./types\";\n\n// =============================================================================\n// REGISTRY\n// =============================================================================\n\n/**\n * Registry of migration drivers by driver name.\n */\nconst driverRegistry = new Map<string, MigrationDriver>();\n\n/**\n * The implementation each stock SQLite driver binds to, by name.\n *\n * SQLite is the one dialect with two implementations, so a SQLite driver never\n * binds by dialect: a driver declaring `sqliteMigrationCapability` binds to\n * `sqlite3` whatever its name (so a declaring libSQL subclass never reaches the\n * libsql implementation's unvalidated native ALTER COLUMN), an undeclared stock\n * driver binds here, and an undeclared custom one has no binding at all.\n * Binding is not admission: effectful work still needs the declaration\n * (`admission.ts`). PostgreSQL and MySQL have one implementation each,\n * registered under the dialect's name.\n */\nconst STOCK_SQLITE_BINDINGS: ReadonlyMap<string, string> = new Map([\n [\"sqlite3\", \"sqlite3\"],\n [\"bun-sqlite\", \"sqlite3\"],\n [\"libsql\", \"libsql\"],\n]);\n\n/**\n * The closed table of admitted declarations, as bound: stock SQLite, a\n * Durable Object, and D1 (read-only). They restate the drivers' own\n * declarations in `src/drivers/driver.ts`, spelled here so the migration\n * bundle does not import the driver module.\n */\nconst SQLITE_MIGRATION_CAPABILITIES: readonly SqliteMigrationCapability[] = [\n Object.freeze({\n foreignKeys: \"pragma\",\n reservedTablePrefixes: \"none\",\n exclusion: \"database-write-lock\",\n }),\n Object.freeze({\n foreignKeys: \"pragma\",\n reservedTablePrefixes: \"_cf_\",\n exclusion: \"frame\",\n }),\n Object.freeze({\n foreignKeys: \"none\",\n reservedTablePrefixes: \"_cf_\",\n exclusion: \"none\",\n }),\n];\n\n/**\n * Registers a migration driver.\n *\n * @param driver - The migration driver to register\n */\nexport function registerMigrationDriver(driver: MigrationDriver): void {\n driverRegistry.set(driver.driverName, driver);\n}\n\n/**\n * A migration driver bound to one estate.\n *\n * Binding narrows two of the base class's optional facts — the durable target\n * and the execution driver — to present ones, so an admitted live boundary\n * never has to ask whether its driver knows which estate it serves. The live\n * `namespace` stays optional: an unbound MySQL adapter binds to a real estate,\n * and refusing it for effectful work belongs to the admission owner.\n */\nexport interface BoundMigrationDriver extends MigrationDriver {\n readonly target: MigrationTarget;\n readonly executionDriver: AnyDriver;\n /** The SQLite capability read once at binding; admission decides from it. */\n readonly sqliteMigrationCapability: SqliteMigrationCapability | undefined;\n /** The command's limits: the client's own, or the defaults. */\n readonly limits: ResolvedMigrationLimits;\n /**\n * What the command's failures disclose: its client's own instrumentation\n * `diagnostics`, carried by the session its statements run on.\n */\n readonly diagnostics: DiagnosticDisclosure | undefined;\n}\n\n/**\n * Looks up the dialect implementation and returns it BOUND to this driver's\n * estate.\n *\n * The registry stays the dialect implementation registry and its entries stay\n * stateless: binding never mutates a registered singleton and never parks an\n * active namespace in module-level state. The bound value is a frozen view\n * whose prototype is the registered instance, so two clients on two schemas\n * hold two immutable targets over one implementation.\n *\n * This is the ONE place a driver becomes a migration estate. Resolving the\n * estate here is what makes an unproven PostgreSQL adapter fail at lookup\n * rather than at some later statement.\n *\n * The durable target and the live namespace are BOTH taken from one\n * `resolveMigrationEstate` call, which reads `adapter.namespace` exactly once.\n * Binding must never read that fact a second time: an accessor-backed custom\n * adapter could answer differently, and the frozen view would then name one\n * estate in its target and render another in its DDL.\n *\n * @throws MigrationError if no implementation is registered, or if the estate\n * target cannot be proven\n */\nexport function getMigrationDriver(\n driver: AnyDriver,\n tables?: readonly string[],\n limits: ResolvedMigrationLimits = DEFAULT_MIGRATION_LIMITS,\n diagnostics?: DiagnosticDisclosure\n): BoundMigrationDriver {\n const { target: baseTarget, namespace } = resolveMigrationEstate(driver);\n const target =\n tables === undefined\n ? baseTarget\n : Object.freeze({ ...baseTarget, tables });\n const capability =\n target.dialect === \"sqlite\"\n ? readSqliteMigrationCapability(driver)\n : undefined;\n const implementation = findMigrationDriver(\n driver.driverName,\n target.dialect,\n capability\n );\n\n const bound: BoundMigrationDriver = Object.create(implementation);\n Object.defineProperties(bound, {\n target: { value: target, enumerable: true },\n executionDriver: { value: driver, enumerable: true },\n namespace: { value: namespace, enumerable: true },\n sqliteMigrationCapability: { value: capability, enumerable: true },\n limits: { value: limits, enumerable: true },\n diagnostics: { value: diagnostics, enumerable: true },\n introspect: {\n async value(\n this: MigrationDriver,\n executeRaw: Parameters<MigrationDriver[\"introspect\"]>[0]\n ) {\n // `this.target`, not the bound one: a history command restates the\n // managed set on a view of this driver (`withManagedTables`).\n return selectManagedSnapshot(\n await implementation.introspect.call(this, executeRaw),\n (this as BoundMigrationDriver).target\n );\n },\n },\n });\n Object.freeze(bound);\n return bound;\n}\n\n/**\n * The driver's SQLite migration capability, read ONCE, as the table's own\n * frozen entry, or undefined when it declares none of them. Only whole exact\n * declarations count: each member is a safety claim, and a mistyped or mixed\n * claim must not read as an approximate one.\n */\nfunction readSqliteMigrationCapability(\n driver: AnyDriver\n): SqliteMigrationCapability | undefined {\n const declared: unknown = driver.sqliteMigrationCapability;\n if (typeof declared !== \"object\" || declared === null) return;\n const foreignKeys: unknown = Reflect.get(declared, \"foreignKeys\");\n const reservedTablePrefixes: unknown = Reflect.get(\n declared,\n \"reservedTablePrefixes\"\n );\n const exclusion: unknown = Reflect.get(declared, \"exclusion\");\n return SQLITE_MIGRATION_CAPABILITIES.find(\n (capability) =>\n capability.foreignKeys === foreignKeys &&\n capability.reservedTablePrefixes === reservedTablePrefixes &&\n capability.exclusion === exclusion\n );\n}\n\n/** Resolves the registered implementation this driver binds to. */\nfunction findMigrationDriver(\n driverName: string,\n dialect: Dialect,\n capability: SqliteMigrationCapability | undefined\n): MigrationDriver {\n let name: string | undefined = dialect;\n if (dialect === \"sqlite\") {\n name = capability ? \"sqlite3\" : STOCK_SQLITE_BINDINGS.get(driverName);\n }\n const driver = name === undefined ? undefined : driverRegistry.get(name);\n if (driver) return driver;\n throw new MigrationError(\n name === undefined\n ? `The SQLite driver \"${driverName}\" declares no \\`sqliteMigrationCapability\\`, so no migration implementation binds to it.`\n : `No migration driver registered for \"${driverName}\" (dialect: ${dialect}).`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { driver: driverName, dialect } }\n );\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n MAX_DATETIME_EPOCH_MILLISECONDS,\n MIN_DATETIME_EPOCH_MILLISECONDS,\n} from \"@validation/primitives/datetime-values\";\nimport { createIdentifierQuoter } from \"../../../../sql/identifiers\";\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n/**\n * `abs(INT64_MIN)` raises SQLite's \"integer overflow\" error: the one abort\n * every copy and rewrite expression uses to stop on a value it cannot convert.\n */\nexport const SQLITE_ABORT = \"abs(-9223372036854775808)\";\n\nconst ISO_DATE = \"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\";\nconst ISO_TIME = \"[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\";\nconst ISO_OFFSET = \"[+-][0-9][0-9]:[0-9][0-9]\";\nconst ISO_FRACTIONS = [\"\", \".[0-9]\", \".[0-9][0-9]\", \".[0-9][0-9][0-9]\"];\n/**\n * The stored-text grammar: the client's ISO input grammar plus SQLite's own\n * zone-less spelling (`datetime('now')`, `CURRENT_TIMESTAMP`), which SQLite\n * defines as UTC.\n */\nconst ISO_TIMESTAMP_SHAPES = [\n ...ISO_FRACTIONS.map((f) => `${ISO_DATE} ${ISO_TIME}${f}`),\n ...ISO_FRACTIONS.map((f) => `${ISO_DATE}T${ISO_TIME}${f}Z`),\n ...ISO_FRACTIONS.map((f) => `${ISO_DATE}T${ISO_TIME}${f}${ISO_OFFSET}`),\n];\n\nexport function sqliteDateTimeTargetRequiresRecreation(\n from: DateTimePhysicalForm | undefined,\n to: DateTimePhysicalForm | undefined\n): boolean {\n return to !== undefined && from !== to;\n}\n\n/** SQLite spelling of JavaScript's `Math.round`, including negative halves. */\nfunction roundToInteger(expression: string): string {\n const integer = `CAST(${expression} AS INTEGER)`;\n const fraction = `(${expression} - ${integer})`;\n return (\n `(${integer} + CASE ` +\n `WHEN ${fraction} >= 0.5 THEN 1 ` +\n `WHEN ${fraction} < -0.5 THEN -1 ELSE 0 END)`\n );\n}\n\nfunction julianToEpochMilliseconds(julianDay: string): string {\n return roundToInteger(\n `((${julianDay} - ${UNIX_EPOCH_JULIAN_DAY}) * ${MILLISECONDS_PER_DAY})`\n );\n}\n\nfunction epochMillisecondsToJulian(epochMilliseconds: string): string {\n return (\n `((${epochMilliseconds} / ${MILLISECONDS_PER_DAY}.0) + ` +\n `${UNIX_EPOCH_JULIAN_DAY})`\n );\n}\n\nfunction textFractionMilliseconds(source: string): string {\n const first = `CAST(substr(${source}, 21, 1) AS INTEGER)`;\n const second = `CAST(substr(${source}, 22, 1) AS INTEGER)`;\n const third = `CAST(substr(${source}, 23, 1) AS INTEGER)`;\n return (\n `(CASE WHEN substr(${source}, 20, 1) <> '.' THEN 0 ELSE ` +\n `${first} * 100 + ` +\n `CASE WHEN substr(${source}, 22, 1) GLOB '[0-9]' THEN ${second} * 10 + ` +\n `CASE WHEN substr(${source}, 23, 1) GLOB '[0-9]' THEN ${third} ELSE 0 END ` +\n \"ELSE 0 END END)\"\n );\n}\n\n/** SQLite's zone-less UTC spelling separates date and time with a space. */\nfunction isZoneless(source: string): string {\n return `substr(${source}, 11, 1) = ' '`;\n}\n\nfunction textOffsetMilliseconds(source: string): string {\n const magnitude =\n `((CAST(substr(${source}, -5, 2) AS INTEGER) * 60 + ` +\n `CAST(substr(${source}, -2, 2) AS INTEGER)) * 60000)`;\n return (\n `(CASE WHEN substr(${source}, -1, 1) = 'Z' OR ${isZoneless(source)} THEN 0 ` +\n `WHEN substr(${source}, -6, 1) = '+' THEN ${magnitude} ` +\n `ELSE -${magnitude} END)`\n );\n}\n\n/** Epoch milliseconds without SQLite's narrower timezone-offset parser. */\nfunction textToEpochMilliseconds(source: string): string {\n const day = julianToEpochMilliseconds(\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z')`\n );\n const local =\n `(${day} + CAST(substr(${source}, 12, 2) AS INTEGER) * 3600000 + ` +\n `CAST(substr(${source}, 15, 2) AS INTEGER) * 60000 + ` +\n `CAST(substr(${source}, 18, 2) AS INTEGER) * 1000 + ` +\n `${textFractionMilliseconds(source)})`;\n return `(${local} - ${textOffsetMilliseconds(source)})`;\n}\n\n/** Canonical ISO text for an admitted SQLite-range epoch millisecond. */\nfunction epochMillisecondsToText(epochMilliseconds: string): string {\n const wholeSeconds =\n `(CASE WHEN ${epochMilliseconds} < 0 AND ` +\n `${epochMilliseconds} % 1000 <> 0 ` +\n `THEN ${epochMilliseconds} / 1000 - 1 ` +\n `ELSE ${epochMilliseconds} / 1000 END)`;\n const milliseconds = `(((${epochMilliseconds} % 1000) + 1000) % 1000)`;\n return (\n \"(\" +\n `strftime('%Y-%m-%dT%H:%M:%S', ${wholeSeconds}, 'unixepoch') || ` +\n `printf('.%03dZ', ${milliseconds})` +\n \")\"\n );\n}\n\nfunction epochMilliseconds(source: string, form: DateTimePhysicalForm): string {\n if (form === \"epochMillis\") return source;\n if (form === \"julianDay\") return julianToEpochMilliseconds(source);\n return textToEpochMilliseconds(source);\n}\n\n/** SQL transcription of the stored-text grammar (`ISO_TIMESTAMP_SHAPES`). */\nfunction isIsoTimestamp(source: string): string {\n return `(${ISO_TIMESTAMP_SHAPES.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")})`;\n}\n\n/** Component rules used by the public ISO timestamp admission boundary. */\nfunction isAdmittedIsoTimestamp(source: string): string {\n const year = `CAST(substr(${source}, 1, 4) AS INTEGER)`;\n const month = `CAST(substr(${source}, 6, 2) AS INTEGER)`;\n const day = `CAST(substr(${source}, 9, 2) AS INTEGER)`;\n const hour = `CAST(substr(${source}, 12, 2) AS INTEGER)`;\n const minute = `CAST(substr(${source}, 15, 2) AS INTEGER)`;\n const second = `CAST(substr(${source}, 18, 2) AS INTEGER)`;\n const zulu = `substr(${source}, -1, 1) = 'Z'`;\n const offsetHour = `CAST(substr(${source}, -5, 2) AS INTEGER)`;\n const offsetMinute = `CAST(substr(${source}, -2, 2) AS INTEGER)`;\n const isLeapYear = `(${year} % 4 = 0 AND (${year} % 100 <> 0 OR ${year} % 400 = 0))`;\n const lastDay =\n `(CASE ${month} ` +\n `WHEN 2 THEN CASE WHEN ${isLeapYear} THEN 29 ELSE 28 END ` +\n \"WHEN 4 THEN 30 WHEN 6 THEN 30 WHEN 9 THEN 30 WHEN 11 THEN 30 \" +\n \"ELSE 31 END)\";\n return (\n `${isIsoTimestamp(source)} AND ${month} BETWEEN 1 AND 12 AND ` +\n `${day} BETWEEN 1 AND ${lastDay} AND ${hour} BETWEEN 0 AND 23 AND ` +\n `${minute} BETWEEN 0 AND 59 AND ${second} BETWEEN 0 AND 59 AND ` +\n `(${zulu} OR ${isZoneless(source)} OR (${offsetHour} BETWEEN 0 AND 23 AND ${offsetMinute} BETWEEN 0 AND 59)) AND ` +\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z') IS NOT NULL`\n );\n}\n\nfunction sourceIsExact(\n source: string,\n form: DateTimePhysicalForm,\n epoch: string\n): string {\n if (form === \"text\") {\n return (\n `typeof(${source}) = 'text' AND ${isAdmittedIsoTimestamp(source)} AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n if (form === \"epochMillis\") {\n return (\n `typeof(${source}) = 'integer' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n return (\n `typeof(${source}) = 'real' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS} AND ` +\n `${epochMillisecondsToJulian(epoch)} = ${source}`\n );\n}\n\nfunction targetValue(epoch: string, form: DateTimePhysicalForm): string {\n if (form === \"text\") return epochMillisecondsToText(epoch);\n if (form === \"epochMillis\") return epoch;\n return epochMillisecondsToJulian(epoch);\n}\n\nfunction targetIsExact(\n epoch: string,\n form: DateTimePhysicalForm,\n value: string\n): string {\n if (form === \"text\") {\n return `${value} IS NOT NULL AND ${isIsoTimestamp(value)}`;\n }\n if (form === \"epochMillis\") return \"1\";\n return `${julianToEpochMilliseconds(value)} = ${epoch}`;\n}\n\n/**\n * Converts one copied SQLite DateTime between its declared physical forms.\n *\n * The guard is the sole integrity boundary. It accepts only a value that is an\n * exact member of the source vocabulary and whose target representation\n * decodes to the same millisecond. `abs(INT64_MIN)` is SQLite's built-in,\n * deterministic error expression; it makes malformed, out-of-range, and\n * inexact rows abort the recreation instead of being rounded or reinterpreted.\n * An authenticated snapshot proves a same-form source and can retain it\n * unchanged. A live-introspected source has no logical marker, so even a\n * same-physical-form adoption crosses this guard before it becomes DateTime.\n */\nexport function sqliteDateTimeCopyExpression(\n source: string,\n from: DateTimePhysicalForm,\n to: DateTimePhysicalForm,\n isDeclaredSource: boolean\n): string {\n if (from === to && isDeclaredSource) return source;\n const epoch = epochMilliseconds(source, from);\n const value = from === to ? source : targetValue(epoch, to);\n const exact =\n from === to\n ? sourceIsExact(source, from, epoch)\n : `${sourceIsExact(source, from, epoch)} AND ${targetIsExact(epoch, to, value)}`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL ` +\n `WHEN ${exact} THEN ${value} ` +\n `ELSE ${SQLITE_ABORT} END`\n );\n}\n\n/** A reviewed manual-migration expression; the argument is a physical column name. */\nexport function sqliteCanonicalDateTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} THEN ${value} ELSE ${SQLITE_ABORT} END`;\n}\n\n/** The Time writer, the `viborm check --db` audit and the repair share one physical grammar. */\nfunction timeSource(source: string): { valid: string; value: string } {\n const shapes = ISO_FRACTIONS.map((f) => `${ISO_TIME}${f}`);\n const valid = `typeof(${source}) = 'text' AND (${shapes.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")}) AND CAST(substr(${source},1,2) AS INTEGER) BETWEEN 0 AND 23 AND CAST(substr(${source},4,2) AS INTEGER) BETWEEN 0 AND 59 AND CAST(substr(${source},7,2) AS INTEGER) BETWEEN 0 AND 59`;\n const value = `substr(${source},1,8) || '.' || substr(CASE WHEN length(${source}) = 8 THEN '000' ELSE substr(${source},10) || '000' END,1,3)`;\n return { valid, value };\n}\n\n/** Canonical millisecond Time storage; malformed source rows abort the statement. */\nexport function sqliteCanonicalTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${valid} THEN ${value} ELSE ${SQLITE_ABORT} END`;\n}\n\n/** Exact canonical carrier predicates for `viborm check --db`: NULL passes, unknown/malformed does not. */\nexport function sqliteCanonicalDateTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n\nexport function sqliteCanonicalTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${valid} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n\ntype TemporalType = \"datetime\" | \"time\";\n\n/**\n * One text DateTime/Time column (scalar or JSON list): which rows lie outside\n * the canonical carrier, and the canonical value a row rewrites to. NULL is\n * canonical. A list is rewritten member by member, in array order; a non-text\n * member or a non-array carrier aborts like a malformed scalar.\n */\nfunction temporalCarrier(\n table: string,\n column: string,\n type: TemporalType,\n list: boolean\n): { readonly noncanonical: string; readonly canonical: string } {\n const [predicate, expression] =\n type === \"time\"\n ? [sqliteCanonicalTimePredicate, sqliteCanonicalTimeExpression]\n : [sqliteCanonicalDateTimePredicate, sqliteCanonicalDateTimeExpression];\n if (!list) {\n return {\n noncanonical: `NOT ${predicate(column)}`,\n canonical: expression(column),\n };\n }\n const quote = createIdentifierQuoter('\"');\n const name = `${quote(table)}.${quote(column)}`;\n // json_each is reached only after proving an array carrier.\n const array = `json_valid(${name}) AND json_type(${name}) = 'array'`;\n return {\n noncanonical: `CASE WHEN ${name} IS NULL THEN 0 WHEN ${array} THEN EXISTS (SELECT 1 FROM json_each(${name}) WHERE type <> 'text' OR NOT ${predicate(\"value\")}) ELSE 1 END`,\n canonical: `CASE WHEN ${array} THEN (SELECT json_group_array(CASE WHEN \"type\" = 'text' THEN ${expression(\"value\")} ELSE ${SQLITE_ABORT} END) FROM (SELECT \"value\", \"type\" FROM json_each(${name}) ORDER BY \"key\")) ELSE ${SQLITE_ABORT} END`,\n };\n}\n\n/** Counts one text DateTime/Time column's rows outside the canonical carrier. */\nexport function sqliteNoncanonicalTemporalCount(\n table: string,\n column: string,\n type: TemporalType,\n list: boolean\n): string {\n const { noncanonical } = temporalCarrier(table, column, type, list);\n return `SELECT count(*) AS noncanonical FROM ${createIdentifierQuoter('\"')(table)} WHERE ${noncanonical}`;\n}\n\n/** Rewrites one column's noncanonical rows into canonical text; a malformed value aborts the statement. */\nexport function sqliteCanonicalTemporalUpdate(\n table: string,\n column: string,\n type: TemporalType,\n list: boolean\n): string {\n const quote = createIdentifierQuoter('\"');\n const { noncanonical, canonical } = temporalCarrier(\n table,\n column,\n type,\n list\n );\n return `UPDATE ${quote(table)} SET ${quote(column)} = ${canonical} WHERE ${noncanonical}`;\n}\n","/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\nimport type { ReferentialAction } from \"../types\";\n\n/** A catalog's `ON DELETE` / `ON UPDATE` spelling, as a ReferentialAction. */\nexport function mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","import { isSqliteStateControlDefinition } from \"../../control\";\n/**\n * SQLite Schema Introspection\n *\n * Reads the current database schema from SQLite's PRAGMA statements\n * and sqlite_master, returning a normalized SchemaSnapshot.\n */\n\nimport { BATCH_REFS_TABLE } from \"@adapters/shared/batch-refs\";\nimport {\n sqliteDefinitionKeywords,\n sqliteTableDefinitions,\n} from \"../../../adapters/databases/sqlite/storage/column-constraints\";\nimport { readSqliteDecimalConstraint } from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n readSqliteGeoPointColumn,\n SQLITE_GEO_POINT_TYPE,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport { skipSqlNonStructuralRegion } from \"../../../adapters/databases/sqlite/storage/sql-lexing\";\nimport type { SqliteMigrationCapability } from \"../../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { RAW_INDEX_MARKER_PREFIX, readRawIndexMarker } from \"../../raw-index\";\nimport type {\n ColumnDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n ViewDef,\n} from \"../../types\";\nimport {\n holdsAutoViewBody,\n type LiveAutoKeeper,\n type LiveAutoTable,\n readAutoViews,\n readKeeperMarker,\n readViewMarker,\n viewMarker,\n} from \"../../view\";\nimport { mapReferentialAction } from \"../utils\";\nimport type {\n SqliteColumn,\n SqliteForeignKey,\n SqliteIndex,\n SqliteIndexColumn,\n SqliteInt,\n SqliteTable,\n} from \"./types\";\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction escapeIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * A pragma's integer column, as a number.\n *\n * SQLite reports integers, but the driver decides how they arrive: the LibSQL\n * driver runs with `intMode: \"bigint\"` (`src/drivers/libsql/index.ts`), so every\n * pragma integer reaches this file as BigInt. Read raw, each one is wrong in a\n * different way — `1n === 1` is false, so a unique index reads as non-unique\n * and a NOT NULL column reads as nullable; and `a.seqno - b.seqno` yields a\n * BigInt that `Array#sort` refuses outright, which crashes the introspection of\n * any index over two or more columns. Normalizing here, once, is what lets the\n * rest of this file compare plain numbers.\n */\nfunction int(value: SqliteInt): number {\n return Number(value);\n}\n\n/** The predicate half of a stored `CREATE INDEX … WHERE …`, if there is one. */\nconst TRAILING_WHERE = /^WHERE\\s+([\\s\\S]+)$/i;\n/** The defaults SQLite's column grammar takes without parentheses. */\n// Identifiers include NULL, TRUE, FALSE and CURRENT_*, and SQLite reads a\n// bare or double-quoted one in a default as a string literal.\nconst LITERAL_DEFAULT =\n /^(?:[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|0x[\\da-f]+|'(?:[^']|'')*'|x'[\\da-f]*'|\"(?:[^\"]|\"\")*\"|[a-z_][\\w$]*)$/i;\n\n/**\n * A column's default as DDL. `PRAGMA table_info` reports `DEFAULT (expr)`\n * without its parentheses, and an expression is a legal default only inside\n * them: a table recreation that wrote `strftime(...)` back verbatim (an\n * `s.dateTime().now()` column) was a `CREATE TABLE` SQLite refused.\n */\nfunction columnDefault(value: string | null): string | undefined {\n if (value === null) return;\n return LITERAL_DEFAULT.test(value) ? value : `(${value})`;\n}\nconst AUTOINCREMENT = /\\bAUTOINCREMENT\\b/i;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * The CHECK the SQLite driver embeds in an enum column type.\n *\n * `PRAGMA table_info` reports only `TEXT`. The values live in\n * `sqlite_master.sql` as `CHECK(\"col\" IN ('a', 'b'))`, which is the same\n * spelling `getEnumColumnType` writes into the desired snapshot. Reconstruct\n * that suffix so fingerprint and differ see one type.\n */\nfunction sqliteEnumCheckSuffix(\n tableSql: string | null,\n columnName: string\n): string | undefined {\n if (!tableSql) return;\n const quoted = escapeIdentifier(columnName);\n const match = tableSql.match(\n new RegExp(\n `CHECK\\\\(\\\\s*${escapeRegExp(quoted)}\\\\s+IN\\\\s*\\\\((\\\\s*(?:'(?:[^']|'')*'\\\\s*,\\\\s*)*'(?:[^']|'')*'\\\\s*)\\\\)\\\\s*\\\\)`,\n \"i\"\n )\n );\n const list = match?.[1];\n if (!list) return;\n const values: string[] = [];\n const literals = /'((?:[^']|'')*)'/g;\n let literal = literals.exec(list);\n while (literal) {\n const value = literal[1];\n if (value !== undefined) values.push(value.replace(/''/g, \"'\"));\n literal = literals.exec(list);\n }\n if (values.length === 0) return;\n const escaped = values\n .map((value) => `'${value.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return ` CHECK(${quoted} IN (${escaped}))`;\n}\n\n/**\n * Reads the predicate of a partial index back out of the text SQLite stored.\n *\n * SQLite keeps `sqlite_master.sql` as the statement was written and re-spells\n * nothing (measured on 3.51: the predicate, its inner spacing and its padding\n * all come back byte-identical; only the statement terminator is dropped), so\n * the predicate the differ compares is the one the serializer emitted. This\n * reads it out and does not normalize it — `indexesEqual` is the one place the\n * two snapshot producers' spellings are reconciled.\n *\n * The predicate is whatever follows the column list, not whatever follows the\n * first `WHERE` in the text: a column may be named `a WHERE b`. So walk the\n * statement to the parenthesis that closes the column list, skipping quoted\n * identifiers and string literals, and read the tail from there.\n */\n/** The marker `generateCreateIndex` ends a raw index's text with. */\nconst RAW_INDEX_TRAILER = new RegExp(\n String.raw`/\\* ${RAW_INDEX_MARKER_PREFIX}(\\{[^\\n]*\\}) \\*/\\s*$`\n);\n\n/** The raw index an index's stored text marks, when VibORM wrote it for this index. */\nfunction sqliteRawIndex(\n sql: string | null,\n name: string\n): IndexDef | undefined {\n const marker = sql === null ? undefined : RAW_INDEX_TRAILER.exec(sql)?.[1];\n return marker === undefined ? undefined : readRawIndexMarker(marker, name);\n}\n\nfunction partialIndexPredicate(sql: string | null): string | undefined {\n if (!sql) return undefined;\n\n let depth = 0;\n let cursor = 0;\n let columnListEnd = -1;\n\n while (cursor < sql.length) {\n // Quoted tokens and comments are skipped through the ONE owner of where a\n // non-structural SQLite region ends, shared with the reserved decimal-\n // constraint reader: both read text SQLite stored verbatim, and both are\n // wrong the same way if its contents are read as syntax.\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n\n const char = sql[cursor];\n\n if (char === \"(\") {\n depth++;\n } else if (char === \")\") {\n depth--;\n if (depth === 0) {\n columnListEnd = cursor;\n break;\n }\n }\n cursor++;\n }\n\n if (columnListEnd === -1) return undefined;\n\n const match = TRAILING_WHERE.exec(sql.slice(columnListEnd + 1).trimStart());\n return match?.[1];\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\n/** `CREATE TABLE … (…) WITHOUT ROWID`: the two words at the statement's top level. */\nfunction isWithoutRowid(sql: string): boolean {\n const words = sqliteDefinitionKeywords(sql);\n return words.some(\n (word, index) => word === \"WITHOUT\" && words[index + 1] === \"ROWID\"\n );\n}\n\n/**\n * What a stored `CREATE TABLE` declares beyond the snapshot's vocabulary and\n * that changes how the table behaves: `STRICT` typing, an `ON CONFLICT`\n * resolution on a key or NOT NULL (`REPLACE` overwrites a row a create would\n * have refused), and a column collation other than BINARY, which the\n * declaration never writes. A quoted collation name is not read, so it counts.\n * An indexed column's collation is refused by every reader already (V8001),\n * and a CHECK by introspection (V11009).\n */\nexport function sqliteTableHazards(sql: string): string[] {\n const hazards: string[] = [];\n if (sqliteDefinitionKeywords(sql).includes(\"STRICT\")) hazards.push(\"STRICT\");\n for (const { text, columnName } of sqliteTableDefinitions(sql)) {\n const words = sqliteDefinitionKeywords(text);\n const where =\n columnName === undefined\n ? \"a table constraint\"\n : `column \"${columnName}\"`;\n if (words.some((word, i) => word === \"ON\" && words[i + 1] === \"CONFLICT\"))\n hazards.push(`ON CONFLICT on ${where}`);\n if (\n words.some((word, i) => word === \"COLLATE\" && words[i + 1] !== \"BINARY\")\n )\n hazards.push(`a collation on ${where}`);\n }\n return hazards;\n}\n\n/**\n * Whether a column holds NULL. `PRAGMA table_info` reports what was declared,\n * and SQLite enforces more only in two places: a WITHOUT ROWID key, which it\n * already reports as `notnull = 1`, and the rowid alias — a rowid table's\n * one-column INTEGER key, the only key with no backing `pk` index (the\n * `INTEGER PRIMARY KEY DESC` quirk has one, and holds NULL). Any other key\n * column of a rowid table accepts NULL unless it is declared NOT NULL.\n */\nexport function sqliteColumnNullable(\n notnull: number,\n pk: number,\n keyIndexed: boolean\n): boolean {\n return notnull === 0 && (pk === 0 || keyIndexed);\n}\n\nexport async function introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n managedTables?: readonly string[],\n reservedTablePrefixes: SqliteMigrationCapability[\"reservedTablePrefixes\"] = \"none\"\n): Promise<SchemaSnapshot> {\n // Get all tables. `sql` rides along on the query that was already being made\n // — the reserved decimal constraints are read out of it, and a second live\n // read for them would be a raw-execution call site the architecture census\n // pins per file. The engine's batch reference scratch is not part of the\n // user's schema: it is TEMP where the transport admits temporary objects and\n // never appears here, but on D1 it is an ordinary table in `main`, and a\n // snapshot that carried it would have push and diff plan its drop.\n // Cloudflare (D1, Durable Objects) owns the `_cf_` tables and forbids their\n // PRAGMAs. Filter that exact prefix only where the driver's capability\n // reserves it; GLOB treats `_` literally, and an ordinary SQLite\n // application's similarly named tables stay visible.\n // The views and triggers ride along too: any carrying VibORM's marker belong to this schema.\n const relationsResult = await executeRaw<SqliteTable>(\n `SELECT name, sql, type, tbl_name FROM sqlite_master WHERE (type = 'table' OR type = 'view' OR type = 'trigger') AND name NOT LIKE 'sqlite_%' AND name <> ?${reservedTablePrefixes === \"_cf_\" ? \" AND name NOT GLOB '_cf_*'\" : \"\"} ORDER BY name`,\n [BATCH_REFS_TABLE]\n );\n\n const tables: TableDef[] = [];\n // SQLite does not check what a view reads when one is dropped, so its\n // reads are not read here: push takes a declared view's from its declaration.\n const views: ViewDef[] = [];\n const keepers: LiveAutoKeeper[] = [];\n\n for (const tableRow of relationsResult.rows) {\n if (tableRow.type === \"trigger\") {\n const hash = readKeeperMarker(tableRow.sql);\n if (hash !== undefined)\n keepers.push({\n kind: \"trigger\",\n name: tableRow.name,\n table: tableRow.tbl_name ?? undefined,\n hash,\n });\n continue;\n }\n if (tableRow.type === \"view\") {\n const hash = readViewMarker(tableRow.sql);\n if (hash !== undefined)\n views.push({ name: tableRow.name, hash, dependsOn: [] });\n continue;\n }\n const tableName = tableRow.name;\n\n const selected =\n managedTables === undefined || managedTables.includes(tableName);\n const definitions = sqliteTableDefinitions(tableRow.sql ?? \"\");\n if (\n selected &&\n definitions.some((definition) =>\n sqliteDefinitionKeywords(definition.text).includes(\"AS\")\n )\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has unsupported generated columns.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"generated columns\" } }\n );\n if (\n selected &&\n sqliteDefinitionKeywords((tableRow.sql ?? \"\").split(\"(\")[0]!).includes(\n \"VIRTUAL\"\n )\n )\n throw new MigrationError(\n `SQLite virtual table \"${tableName}\" is unsupported.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"virtual table\" } }\n );\n\n // Get columns using PRAGMA\n const columnsResult = await executeRaw<SqliteColumn>(\n `PRAGMA table_info(${escapeIdentifier(tableName)})`\n );\n const tableSql = tableRow.sql;\n const hasAutoincrement = AUTOINCREMENT.test(tableSql ?? \"\");\n\n // Get indexes\n const indexesResult = await executeRaw<SqliteIndex>(\n `PRAGMA index_list(${escapeIdentifier(tableName)})`\n );\n const keyIndexed = indexesResult.rows.some(({ origin }) => origin === \"pk\");\n\n // The pragma reports that an index is partial but not what its predicate\n // is; only the stored statement carries that.\n const indexSqlResult = await executeRaw<{\n name: string;\n sql: string | null;\n }>(\n \"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?\",\n [tableName]\n );\n const indexSql = new Map(\n indexSqlResult.rows.map((row) => [row.name, row.sql])\n );\n\n // Get foreign keys\n const fksResult = await executeRaw<SqliteForeignKey>(\n `PRAGMA foreign_key_list(${escapeIdentifier(tableName)})`\n );\n\n // Build columns\n const columns: ColumnDef[] = [];\n const pkColumns: { name: string; position: number }[] = [];\n\n for (const col of columnsResult.rows) {\n const pk = int(col.pk);\n const type = col.type || \"TEXT\";\n const nullable = sqliteColumnNullable(int(col.notnull), pk, keyIndexed);\n const geoPointEncoding = readSqliteGeoPointColumn(\n tableSql,\n { name: col.name, type, nullable },\n escapeIdentifier\n );\n columns.push({\n name: col.name,\n geoPointEncoding,\n type: geoPointEncoding\n ? SQLITE_GEO_POINT_TYPE\n : `${type}${sqliteEnumCheckSuffix(tableSql, col.name) ?? \"\"}`,\n nullable,\n default: columnDefault(col.dflt_value),\n autoIncrement: pk === 1 && hasAutoincrement,\n // The declared domain, recovered from the reserved CHECK constraint\n // the driver wrote. Nothing else on this dialect carries it: the type\n // is `INTEGER` (or `TEXT`) at every precision and scale, and the\n // pragma reports no constraints at all — so a side that could not\n // recover it would read as a change on every push, forever.\n decimal: readSqliteDecimalConstraint(\n tableSql,\n // The descriptor proof consumes the exact declared type PRAGMA\n // reported. The generic snapshot fallback above may call an untyped\n // column TEXT, but that normalization cannot turn BLOB affinity into\n // the writer-owned TEXT decimal-list carrier.\n { name: col.name, type: col.type, nullable },\n escapeIdentifier\n ),\n });\n\n if (pk > 0) {\n pkColumns.push({ name: col.name, position: pk });\n }\n }\n\n if (selected) {\n const checks = definitions.reduce(\n (count, definition) =>\n count +\n sqliteDefinitionKeywords(definition.text).filter(\n (word) => word === \"CHECK\"\n ).length,\n 0\n );\n const represented = columns.reduce(\n (count, column) =>\n count +\n Number(column.decimal !== undefined) +\n Number(column.geoPointEncoding !== undefined) +\n Number(sqliteEnumCheckSuffix(tableSql, column.name) !== undefined),\n 0\n );\n if (\n checks !== represented &&\n !isSqliteStateControlDefinition(tableName, tableSql)\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has unrepresented CHECK constraints.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"CHECK constraints\" } }\n );\n }\n\n // Build primary key (sort by pk position)\n let primaryKey: PrimaryKeyDef | undefined;\n if (pkColumns.length > 0) {\n pkColumns.sort((a, b) => a.position - b.position);\n primaryKey = {\n name: `${tableName}_pkey`,\n columns: pkColumns.map((p) => p.name),\n // The table's options follow its definitions, outside any paren.\n ...(isWithoutRowid(tableSql ?? \"\") ? { withoutRowid: true } : {}),\n };\n }\n\n // Build indexes and unique constraints\n const indexes: IndexDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n\n for (const idx of indexesResult.rows) {\n // A raw index is its marker, whatever its key semantics are.\n const raw = sqliteRawIndex(indexSql.get(idx.name) ?? null, idx.name);\n if (raw) {\n indexes.push(raw);\n continue;\n }\n // xinfo exposes the physical key semantics that index_info erases.\n // Auxiliary rowid columns are not key members; user expressions, DESC\n // and collations cannot be faithfully recreated by this declaration DSL.\n const indexColsResult = await executeRaw<SqliteIndexColumn>(\n `PRAGMA index_xinfo(${escapeIdentifier(idx.name)})`\n );\n const keys = indexColsResult.rows.filter(\n (column) => int(column.key) === 1\n );\n const unsupported =\n keys.length === 0 ||\n keys.some(\n (column) =>\n int(column.cid) < 0 ||\n column.name === null ||\n int(column.desc) !== 0 ||\n column.coll !== \"BINARY\"\n );\n if (unsupported) {\n if (managedTables === undefined || managedTables.includes(tableName)) {\n throw new MigrationError(\n `Unsupported SQLite index \"${tableName}.${idx.name}\"; use .rawIndex() or exclude table.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: tableName, indexName: idx.name } }\n );\n }\n continue;\n }\n // PK membership is already represented by the table's primary key.\n if (idx.origin === \"pk\") continue;\n const indexColumns = keys\n .sort((a, b) => int(a.seqno) - int(b.seqno))\n .flatMap((column) => (column.name === null ? [] : [column.name]));\n\n const unique = int(idx.unique) === 1;\n if (unique && idx.origin === \"u\") {\n // This is a unique constraint\n uniqueConstraints.push({\n name: idx.name,\n columns: indexColumns,\n });\n } else {\n indexes.push({\n name: idx.name,\n columns: indexColumns,\n unique,\n where: partialIndexPredicate(indexSql.get(idx.name) ?? null),\n });\n }\n }\n\n // Build foreign keys - group by id (constraint)\n const fkMap = new Map<number, SqliteForeignKey[]>();\n for (const fk of fksResult.rows) {\n const id = int(fk.id);\n const existing = fkMap.get(id) || [];\n existing.push(fk);\n fkMap.set(id, existing);\n }\n\n const foreignKeys: ForeignKeyDef[] = [];\n for (const [id, fkCols] of fkMap) {\n const sorted = fkCols.sort((a, b) => int(a.seq) - int(b.seq));\n const first = sorted[0];\n if (first) {\n foreignKeys.push({\n name: `${tableName}_fk_${id}`,\n columns: sorted.map((f) => f.from),\n referencedTable: first.table,\n referencedColumns: sorted.map((f) => f.to),\n onDelete: mapReferentialAction(first.on_delete),\n onUpdate: mapReferentialAction(first.on_update),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // A table whose statement opens with a view's marker holds a view kept by\n // triggers, which is the view and not a table; its keepers are the\n // triggers whose statement carries the same marker.\n const autoTables: LiveAutoTable[] = [];\n const sqlByTable = new Map(\n relationsResult.rows.map((row) => [row.name, row.sql])\n );\n for (let at = tables.length - 1; at >= 0; at--) {\n const table = tables[at]!;\n const hash = readAutoTableMarker(sqlByTable.get(table.name));\n if (hash === undefined) continue;\n autoTables.unshift({ name: table.name, hash, indexes: table.indexes });\n tables.splice(at, 1);\n }\n if (autoTables.length > 0 || keepers.length > 0 || holdsAutoViewBody(views)) {\n views.push(...readAutoViews(autoTables, keepers, views));\n views.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n }\n\n // SQLite doesn't have native enum types\n return { tables, enums: [], ...(views.length > 0 ? { views } : {}) };\n}\n\n/**\n * The hash a table's statement names in the marker it opens its column list\n * with (`CREATE TABLE \"v\" (/* viborm_view_<hash> *\\/ …`), where a view kept by\n * triggers carries it.\n */\nfunction readAutoTableMarker(\n text: string | null | undefined\n): string | undefined {\n return text?.match(AUTO_TABLE_MARKER)?.[1];\n}\n\n/** A table's marker as the comment it is, where it holds a view kept by triggers. */\nexport function autoTableComment(\n text: string | null | undefined\n): string | undefined {\n const hash = readAutoTableMarker(text);\n return hash === undefined ? undefined : viewMarker(hash);\n}\nconst AUTO_TABLE_MARKER = /^[^(]*\\(\\/\\* viborm_view_([0-9a-f]{40}) \\*\\//;\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":"45DAMA,SAAgB,GACd,EACA,EACA,EACA,EACmC,CACnC,IAAI,EACA,EAA+B,EAAE,CACrC,GAAI,CACoB,OAAO,GAAU,UAAnC,GAA+C,CAAC,MAAM,QAAQ,EAAM,GACtE,EAAc,EACd,EAAO,QAAQ,QAAQ,EAAM,QAExB,EAAS,CAChB,OAAOA,EAAO,GAAG,EAAM,yBAA0B,EAAW,EAAQ,CAAC,CAEvE,GAAI,CAAC,EAAa,OAAOA,EAAO,GAAG,EAAM,oBAAoB,CAC7D,IAAM,EAAoC,EAAE,CAC5C,IAAK,IAAM,KAAO,EAAM,CACtB,GAAI,OAAO,GAAQ,UAAY,CAAC,EAAQ,SAAS,EAAI,CACnD,OAAOA,EAAO,GAAG,EAAM,wBAAwB,OAAO,EAAI,GAAG,CAE/D,GAAI,CACF,EAAS,GAAO,QAAQ,IAAI,EAAa,EAAI,OACtC,EAAS,CAChB,OAAOA,EAAO,GAAG,EAAM,GAAG,EAAI,oBAAqB,EAAW,EAAQ,CAAC,EAG3E,OAAO,OAAO,OAAO,EAAS,CAGhC,SAAgB,GACd,EACA,EACA,EACoB,CACpB,IAAIC,EACJ,GAAI,CACE,MAAM,QAAQ,EAAM,GAAE,EAAU,MAAM,KAAK,EAAM,QAC9C,EAAS,CAChB,OAAOD,EAAO,GAAG,EAAM,oBAAqB,EAAW,EAAQ,CAAC,CAGlE,OADKC,EACE,OAAO,OAAOA,EAAQ,CADRD,EAAO,GAAG,EAAM,mBAAmB,CCU1D,MAAa,GAAoD,OAAO,OAAO,CAC7E,YAAa,I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