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
@@ -1 +0,0 @@
1
- {"version":3,"file":"libsql-DuGR904j.mjs","names":[],"sources":["../src/migrations/drivers/sqlite/index.ts","../src/migrations/drivers/libsql/index.ts"],"sourcesContent":["import { nativeTypeFor } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport { isDestructiveOperation } from \"../../differ\";\n/**\n * SQLite Migration Driver\n *\n * Implements the MigrationDriver interface for SQLite databases.\n * Uses table recreation for operations SQLite doesn't support natively.\n */\n\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { validateIsoTime } from \"@validation/primitives/iso\";\nimport {\n SQLITE_ABORT,\n sqliteDateTimeCopyExpression,\n sqliteDateTimeTargetRequiresRecreation,\n} from \"../../../adapters/databases/sqlite/storage/datetime\";\nimport {\n sqliteDecimalCheck,\n sqliteDecimalCopyExpression,\n} from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n SQLITE_GEO_POINT_TYPE,\n sqliteGeoPointCarrier,\n sqliteGeoPointCheck,\n sqliteGeoPointEncoding,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport {\n isSqliteBareIdentifierCharacter,\n readSqliteIdentifier,\n skipSqlNonStructuralRegion,\n} from \"../../../adapters/databases/sqlite/storage/sql-lexing\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n decimalConversionRequired,\n describeDecimalDomain,\n sqliteDecimalStorageKind,\n} from \"../../decimal\";\nimport { foreignKeyPragmasCannotBeLifted } from \"../../foreign-keys\";\nimport { applyNativeRename } from \"../../native-rename\";\nimport {\n RAW_INDEX_MARKER_PREFIX,\n rawIndexMarker,\n refuseRawIndexStatement,\n renderRawIndex,\n} from \"../../raw-index\";\nimport { readExecutableStatements } from \"../../statement-safety\";\nimport type {\n ColumnDef,\n DiffOperation,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\nimport type {\n AddColumnOperation,\n AddForeignKeyOperation,\n AddPrimaryKeyOperation,\n AddUniqueConstraintOperation,\n AdoptionHazard,\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\";\nimport { SqlMigrationDriver } from \"../sql\";\nimport { getSQLiteType } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { introspect, sqliteTableHazards } from \"./introspect\";\n\nconst COMPUTED_DEFAULT_PREFIX = /^(?:CURRENT_(?:TIME|DATE|TIMESTAMP)|\\()/i;\n\nconst SQLITE_AUTOINDEX_PREFIX = \"sqlite_autoindex_\";\n\n/** The name a recreation builds its replacement under before the swap. */\nconst RECREATION_PREFIX = \"__new_\";\nconst CREATE_TABLE = /^CREATE\\s+TABLE\\s+/i;\nconst ALTER_TABLE = /^ALTER\\s+TABLE\\s+/i;\nconst RENAME_TO = /^\\s+RENAME\\s+TO\\s+/i;\nconst CREATE_DEPENDENT =\n /^CREATE\\s+(?:TEMP(?:ORARY)?\\s+)?(TRIGGER|VIEW)\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?/i;\nconst DROP_DEPENDENT = /^DROP\\s+(?:TRIGGER|VIEW)\\s+(?:IF\\s+EXISTS\\s+)?/i;\nconst DROP_TABLE = /^DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?/i;\nconst IDENTIFIER_OPENERS = '\"`[';\nconst QUALIFIER_DOT = /^\\s*\\./;\n/**\n * The words SQLite never reads as a bare table name (checked on 3.53 against\n * every keyword, in FROM, INSERT, UPDATE, DELETE, JOIN and trigger `ON`). A\n * table spelled like one is quoted wherever SQL names it, so its bare spelling\n * is a keyword (`ORDER BY`), never a reference. Keywords SQLite also accepts\n * as names (`END`, `BY`, `VIEW`) stay references, the safe reading.\n */\nconst SQLITE_RESERVED_WORD =\n /^(?:add|all|alter|and|as|autoincrement|between|case|check|collate|commit|constraint|create|default|deferrable|delete|distinct|drop|else|escape|except|exists|foreign|from|group|having|in|index|insert|intersect|into|is|isnull|join|limit|not|nothing|notnull|null|on|or|order|primary|references|returning|select|set|table|then|to|transaction|union|unique|update|using|values|when|where)$/;\nconst COLUMN_CHECK = /\\s+CHECK\\s*\\(/;\nconst TEXT_AFFINITY = /CHAR|CLOB|TEXT/;\nconst REAL_AFFINITY = /REAL|FLOA|DOUB/;\n\n/**\n * A trigger or view as `sqlite_master` stores it; `table` is the lower-cased\n * `tbl_name`, a trigger's own table, unknown for one the program creates.\n */\ninterface SqliteDependent {\n readonly type: string;\n readonly name: string;\n readonly sql: string | null;\n readonly table?: string;\n}\n\n/**\n * The triggers and views a program's recreations would lose, each with the\n * live table it depends on.\n *\n * The program is walked in order from the catalog as it stands before it\n * runs, past leading comments and a `schema.` qualifier: a\n * `CREATE TRIGGER|VIEW` adds a dependent, a `DROP TRIGGER|VIEW` releases one,\n * a `DROP TABLE` releases the catalog's triggers on that table, which SQLite\n * drops with it, and each recreation — read from the one spelling\n * `compileTableRecreation` writes, `CREATE TABLE \"__new_<t>\"`, as the\n * foreign-key bracket is read from its pragmas — loses the dependents that\n * name the table at that point. A native `ALTER TABLE … RENAME TO` earlier in\n * the program maps the rebuilt name back to the live table, and both spellings\n * count, because the catalog was read before the rename rewrote it.\n */\nfunction lostDependents(\n program: readonly string[],\n catalog: readonly SqliteDependent[]\n): { readonly table: string; readonly dependent: SqliteDependent }[] {\n const dependents = new Map(\n catalog.map((row) => [row.name.toLowerCase(), row])\n );\n const formerNames = new Map<string, string>();\n const lost: { table: string; dependent: SqliteDependent }[] = [];\n for (const statement of program) {\n let text = statement.trim();\n // A leading comment does not hide the statement's head.\n let skipped = skipSqlNonStructuralRegion(text, 0);\n while (skipped > 0) {\n text = text.slice(skipped).trimStart();\n skipped = skipSqlNonStructuralRegion(text, 0);\n }\n const create = CREATE_TABLE.exec(text);\n const alter = ALTER_TABLE.exec(text);\n const created = CREATE_DEPENDENT.exec(text);\n const drop = DROP_DEPENDENT.exec(text);\n const dropTable = DROP_TABLE.exec(text);\n const head = create ?? alter ?? created ?? drop ?? dropTable;\n const name = head && readObjectName(text, head[0].length);\n if (!name) continue;\n const key = name.value.toLowerCase();\n if (created) {\n const type = created[1]!.toLowerCase();\n dependents.set(key, { type, name: name.value, sql: text });\n } else if (drop) {\n dependents.delete(key);\n } else if (dropTable) {\n const live = (formerNames.get(key) ?? name.value).toLowerCase();\n for (const [dependentKey, dependent] of dependents) {\n if (dependent.type === \"trigger\" && dependent.table === live) {\n dependents.delete(dependentKey);\n }\n }\n } else if (create && key.startsWith(RECREATION_PREFIX)) {\n const rebuilt = name.value.slice(RECREATION_PREFIX.length);\n const table = formerNames.get(rebuilt.toLowerCase()) ?? rebuilt;\n const spellings = [rebuilt.toLowerCase(), table.toLowerCase()];\n for (const [dependentKey, dependent] of dependents) {\n const sql = dependent.sql ?? \"\";\n if (!spellings.some((s) => sqlNamesTable(sql, dependent.name, s)))\n continue;\n lost.push({ table, dependent });\n dependents.delete(dependentKey);\n }\n } else if (alter && !key.startsWith(RECREATION_PREFIX)) {\n const rename = RENAME_TO.exec(text.slice(name.end));\n const to =\n rename && readSqliteIdentifier(text, name.end + rename[0].length);\n if (to)\n formerNames.set(\n to.value.toLowerCase(),\n formerNames.get(key) ?? name.value\n );\n }\n }\n return lost;\n}\n\n/** The object a statement head names, past an optional `schema.` qualifier. */\nfunction readObjectName(text: string, index: number) {\n const first = readSqliteIdentifier(text, index);\n const dot = first ? QUALIFIER_DOT.exec(text.slice(first.end)) : null;\n return first && dot\n ? readSqliteIdentifier(text, first.end + dot[0].length)\n : first;\n}\n\n/**\n * Whether a stored view or trigger names the lower-cased `table` as an\n * identifier, past its own name. String literals and comments are skipped, so\n * a trigger that writes the text 'item' does not name the table `item`, and\n * neither does a bare reserved word (`SQLITE_RESERVED_WORD`); a column spelled\n * like the table does, and refusing is the safe reading.\n */\nfunction sqlNamesTable(sql: string, ownName: string, table: string): boolean {\n let ownNamePending = true;\n let index = 0;\n while (index < sql.length) {\n const character = sql.charAt(index);\n const token =\n IDENTIFIER_OPENERS.includes(character) ||\n isSqliteBareIdentifierCharacter(character)\n ? readSqliteIdentifier(sql, index)\n : undefined;\n if (token) {\n const name = token.value.toLowerCase();\n if (ownNamePending && name === ownName.toLowerCase()) {\n ownNamePending = false;\n } else if (\n name === table &&\n (token.quoted || !SQLITE_RESERVED_WORD.test(name))\n ) {\n return true;\n }\n index = token.end;\n } else {\n index = Math.max(skipSqlNonStructuralRegion(sql, index), index + 1);\n }\n }\n return false;\n}\n\n/** SQLite's declared-type affinity rules; a column CHECK is not part of the type name. */\nfunction sqliteAffinity(type: string): string {\n const name = type.toUpperCase().split(COLUMN_CHECK)[0]!.trim();\n if (name.includes(\"INT\")) return \"INTEGER\";\n if (TEXT_AFFINITY.test(name)) return \"TEXT\";\n if (name === \"\" || name.includes(\"BLOB\")) return \"BLOB\";\n if (REAL_AFFINITY.test(name)) return \"REAL\";\n return \"NUMERIC\";\n}\n\n/**\n * The storage class a column type change converts copied values into, or\n * `undefined` when the copy keeps them as they are.\n *\n * Only a change of affinity into INTEGER, REAL or TEXT is guarded, because\n * SQLite converts into them silently and partially: an INTEGER column keeps\n * 'twelve' as TEXT and 1.5 as REAL, and a REAL one rounds an integer past\n * 2^53. A BLOB target stores values verbatim, and NUMERIC is the JSON\n * container's, whose CAST would read every JSON object as 0.\n */\nfunction sqliteConvertingAffinity(\n from: ColumnDef,\n to: ColumnDef\n): \"INTEGER\" | \"REAL\" | \"TEXT\" | undefined {\n const target = sqliteAffinity(to.type);\n if (target === sqliteAffinity(from.type)) return undefined;\n return target === \"INTEGER\" || target === \"REAL\" || target === \"TEXT\"\n ? target\n : undefined;\n}\n\n/**\n * One preceding operation of the batch, applied to the table definition a later\n * recreation will rebuild. `SQLite3MigrationDriver.getCurrentTable` explains\n * why the introspected definition alone is not enough, and what each list costs\n * when it is left behind.\n */\nfunction applyToTable(table: TableDef, op: DiffOperation): TableDef {\n if (!(\"tableName\" in op) || op.tableName !== table.name) {\n return table;\n }\n switch (op.type) {\n case \"addColumn\":\n return { ...table, columns: [...table.columns, op.column] };\n case \"dropColumn\":\n return {\n ...table,\n columns: table.columns.filter(\n (column) => column.name !== op.columnName\n ),\n };\n case \"alterColumn\":\n return {\n ...table,\n columns: table.columns.map((column) =>\n column.name === op.columnName ? op.to : column\n ),\n };\n case \"createIndex\":\n return { ...table, indexes: [...table.indexes, op.index] };\n case \"dropIndex\":\n return {\n ...table,\n indexes: table.indexes.filter((index) => index.name !== op.indexName),\n };\n case \"addForeignKey\":\n return { ...table, foreignKeys: [...table.foreignKeys, op.fk] };\n case \"dropForeignKey\":\n return {\n ...table,\n foreignKeys: table.foreignKeys.filter((fk) => fk.name !== op.fkName),\n };\n case \"addUniqueConstraint\":\n return {\n ...table,\n uniqueConstraints: [...table.uniqueConstraints, op.constraint],\n };\n case \"dropUniqueConstraint\":\n return {\n ...table,\n uniqueConstraints: table.uniqueConstraints.filter(\n (constraint) => constraint.name !== op.constraintName\n ),\n };\n case \"addPrimaryKey\":\n return { ...table, primaryKey: op.primaryKey };\n case \"dropPrimaryKey\":\n return { ...table, primaryKey: undefined };\n default:\n // `dropTable` is the only remaining operation that names this table, and\n // nothing rebuilds a table the same batch dropped.\n return table;\n }\n}\n\n/**\n * The schema-level table set after every preceding operation in the batch.\n *\n * Per-table replay cannot see a table created earlier in the same batch, and\n * retaining a dropped table invents relations the database no longer has.\n * This owner first evolves membership, then applies each operation's local and\n * inbound effects to every table that exists at that point.\n */\nfunction replaySchemaTables(\n tables: readonly TableDef[],\n operations: readonly DiffOperation[]\n): TableDef[] {\n let replayed = [...tables];\n for (const operation of operations) {\n if (operation.type === \"createTable\") {\n replayed = [...replayed, operation.table];\n continue;\n }\n if (operation.type === \"dropTable\") {\n replayed = replayed.filter((table) => table.name !== operation.tableName);\n continue;\n }\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n replayed = applyNativeRename({ tables: replayed }, operation).tables;\n continue;\n }\n replayed = replayed.map((table) => applyToTable(table, operation));\n }\n return replayed;\n}\n\n/** Whether a table carries an outbound FK or is the target of an inbound FK. */\nexport function sqliteTableBearsRelations(\n tableName: string,\n tables: readonly TableDef[],\n rebuiltTable?: TableDef,\n precedingOperations: readonly DiffOperation[] = []\n): boolean {\n if (rebuiltTable && rebuiltTable.foreignKeys.length > 0) return true;\n const replayed = replaySchemaTables(tables, precedingOperations);\n for (const table of replayed) {\n if (table.name === tableName && table.foreignKeys.length > 0) return true;\n if (\n table.foreignKeys.some(\n (foreignKey) => foreignKey.referencedTable === tableName\n )\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * SQLite3 Migration Driver\n *\n * Handles migrations for better-sqlite3 and similar synchronous SQLite drivers.\n * Uses table recreation for operations SQLite doesn't support natively:\n * - ALTER COLUMN (type, default, NOT NULL changes)\n * - ADD/DROP FOREIGN KEY\n * - ADD/DROP PRIMARY KEY\n *\n * LibSQL extends this class and overrides methods for operations it supports.\n */\nexport class SQLite3MigrationDriver extends SqlMigrationDriver {\n readonly dialect = \"sqlite\" as const;\n readonly driverName: string = \"sqlite3\";\n\n override finalizeTable(table: TableDef): TableDef {\n const increments = table.columns.filter((column) => column.autoIncrement);\n if (\n increments.length > 0 &&\n (increments.length !== 1 ||\n table.primaryKey?.columns.length !== 1 ||\n table.primaryKey.columns[0] !== increments[0]!.name ||\n increments[0]!.type.toUpperCase() !== \"INTEGER\" ||\n increments[0]!.nullable)\n ) {\n throw new MigrationError(\n `SQLite table \"${table.name}\" requires its AUTOINCREMENT column to be the sole non-null INTEGER primary key. Declare .id().autoIncrement() on that column.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { table: table.name } }\n );\n }\n return table;\n }\n\n override getIrreversibleRollbackReason(\n operation: DiffOperation\n ): string | undefined {\n if (\n operation.type === \"alterColumn\" &&\n sqliteGeoPointEncoding(operation.from) === \"binary64\" &&\n sqliteGeoPointEncoding(operation.to) === \"legacy\"\n ) {\n return `Rollback cannot downgrade GeoPoint column \"${operation.tableName}.${operation.columnName}\" to its legacy CHECK without rounding coordinates. Author an explicit manual data transition.`;\n }\n return super.getIrreversibleRollbackReason(operation);\n }\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true, // N/A but doesn't matter\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n // No `ALTER TABLE ADD FOREIGN KEY`: FKs stay inline in CREATE TABLE and\n // rely on SQLite's lazy reference resolution (forward refs are fine).\n supportsAddForeignKeyViaAlter: false,\n // `PRAGMA foreign_key_list` has no name column, and an inline\n // `CONSTRAINT x UNIQUE (...)` is only ever reported as\n // `sqlite_autoindex_<table>_<n>`. Neither name survives a round trip.\n introspectionReadsConstraintNames: false,\n };\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /** A trigger on the table, and what its stored definition declares beyond the snapshot. */\n override async adoptionHazards(\n tables: readonly string[],\n executeRaw: Parameters<typeof introspect>[0]\n ): Promise<readonly AdoptionHazard[]> {\n const hazards: AdoptionHazard[] = [];\n for (const table of tables) {\n const { rows } = await executeRaw<{\n type: string;\n name: string;\n sql: string | null;\n }>(\n \"SELECT type, name, sql FROM sqlite_master WHERE type IN ('table', 'trigger') AND lower(tbl_name) = lower(?) ORDER BY type, name\",\n [table]\n );\n for (const row of rows) {\n const features =\n row.type === \"trigger\"\n ? [`trigger \"${row.name}\"`]\n : sqliteTableHazards(row.sql ?? \"\");\n hazards.push(...features.map((feature) => ({ table, feature })));\n }\n }\n return hazards;\n }\n\n /**\n * Also refuses, by name, every trigger and view a table recreation in\n * `program` would lose. A recreation drops the table, and SQLite drops its\n * triggers with it silently; a view or another table's trigger that reads it\n * fails the swap with an error that names neither. A trigger always names\n * its own table (`ON \"t\"`), so one read of the stored SQL finds both kinds\n * (`lostDependents`). A trigger or view the program drops before the\n * recreation is its own business; one it creates earlier is checked too.\n */\n override async preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: Parameters<typeof introspect>[0],\n program: readonly string[]\n ): Promise<boolean> {\n const names = [\n ...new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n ),\n ];\n if (names.length === 0 && program.length === 0) return false;\n const objects = await executeRaw<SqliteDependent>(\n \"SELECT type, name, sql, lower(tbl_name) AS \\\"table\\\" FROM sqlite_master WHERE type IN ('view', 'trigger')\"\n );\n const collision = objects.rows.find(\n (row) => row.type === \"view\" && names.includes(row.name)\n );\n if (collision)\n throw new MigrationError(\n `SQLite relation \"${collision.name}\" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: collision.name, feature: \"view\" } }\n );\n const lost = lostDependents(program, objects.rows);\n if (lost.length > 0)\n throw new MigrationError(\n `This migration rebuilds SQLite ${lost.map(({ table, dependent }) => `table \"${table}\", which ${dependent.type} \"${dependent.name}\" depends on`).join(\"; \")}. ` +\n \"A rebuild drops the table, which silently drops its triggers and breaks every view or trigger that reads it. \" +\n \"The migration is refused before any statement runs, so the schema and data are unchanged. Drop them before this change (a SQL step earlier in the same migration path counts) and recreate them after it.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: lost[0]!.table,\n dependents: lost.map(\n ({ dependent }) => `${dependent.type}:${dependent.name}`\n ),\n feature: \"table recreation\",\n },\n }\n );\n return false;\n }\n\n introspect(\n executeRaw: Parameters<typeof introspect>[0]\n ): Promise<SchemaSnapshot> {\n return introspect(\n executeRaw,\n this.target?.tables,\n this.sqliteMigrationCapability?.reservedTablePrefixes\n );\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string {\n const declaration = scalar[\"~\"].nativeType;\n\n // See the PostgreSQL driver: one storage owner, override included.\n const idStorage =\n idDomain === undefined || scalarState.array === true\n ? undefined\n : idStorageOf(idDomain, declaration, \"sqlite\");\n if (idStorage) return idStorage.columnType;\n\n // SQLite has no native list type. A native declaration can describe one\n // scalar member only; every list keeps its container below.\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType && !scalarState.array) {\n return nativeType.type;\n }\n\n // Use centralized type mapping\n return getSQLiteType({\n type: scalarState.type,\n array: scalarState.array,\n decimal: scalarState.decimal,\n });\n }\n\n override getDefaultExpression(\n scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n if (\n scalarState.type === \"datetime\" &&\n scalarState.autoGenerate?.kind === \"now\"\n ) {\n const form = sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType);\n if (form === \"julianDay\") return \"(julianday('now'))\";\n if (form === \"epochMillis\")\n return \"(CAST(strftime('%s','now') AS INTEGER) * 1000 + CAST(substr(strftime('%f','now'),4,3) AS INTEGER))\";\n return \"(strftime('%Y-%m-%dT%H:%M:%fZ','now'))\";\n }\n if (scalarState.autoGenerate?.kind === \"now\") {\n if (scalarState.type === \"date\") return \"(strftime('%Y-%m-%d','now'))\";\n if (scalarState.type === \"time\") return \"(strftime('%H:%M:%f','now'))\";\n }\n const defaultValue =\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n !scalarState.array &&\n (scalarState.type === \"datetime\" || scalarState.type === \"time\")\n ? this.literalDefaultValue(scalarState)\n : undefined;\n if (\n scalarState.type === \"datetime\" &&\n scalarState.array !== true &&\n scalarState.autoGenerate === undefined &&\n scalarState.hasDefault &&\n typeof defaultValue === \"string\"\n ) {\n const form = sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType);\n const physical = encodePhysicalDateTime(defaultValue, form);\n return typeof physical === \"string\"\n ? this.escapeValue(physical)\n : String(physical);\n }\n if (\n scalarState.type === \"time\" &&\n !scalarState.array &&\n !scalarState.autoGenerate &&\n scalarState.hasDefault &&\n typeof defaultValue === \"string\"\n ) {\n const canonical = validateIsoTime(defaultValue);\n if (!(\"value\" in canonical))\n throw new MigrationError(\n \"Invalid Time literal default\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return this.escapeValue(canonical.value);\n }\n return super.getDefaultExpression(scalar, scalarState);\n }\n\n // Override formatBooleanDefault for SQLite's 1/0 representation\n\n /**\n * SQLite uses 1/0 for boolean values instead of true/false.\n */\n protected override formatBooleanDefault(value: boolean): string {\n return value ? \"1\" : \"0\";\n }\n\n getEnumColumnType(\n _tableName: string,\n columnName: string,\n values: string[]\n ): string {\n // SQLite uses TEXT with CHECK constraint for enum validation\n const escapedValues = values\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return `TEXT CHECK(${this.escapeIdentifier(columnName)} IN (${escapedValues}))`;\n }\n\n // ===========================================================================\n // HELPER: Column Definition\n // ===========================================================================\n\n protected generateColumnDef(column: ColumnDef, _context: DDLContext): string {\n // SQLite auto-increment only works with INTEGER PRIMARY KEY\n // Validate that autoIncrement columns use INTEGER type\n if (column.autoIncrement && column.type.toUpperCase() !== \"INTEGER\") {\n throw new MigrationError(\n \"SQLite auto-increment requires INTEGER type. \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with auto-increment. ` +\n \"Note: SQLite auto-increment is implicit when using INTEGER PRIMARY KEY.\",\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: { column: column.name, type: column.type, autoIncrement: true },\n }\n );\n }\n\n if (column.autoIncrement) {\n return `${this.escapeIdentifier(column.name)} INTEGER PRIMARY KEY AUTOINCREMENT`;\n }\n\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n if (column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE) {\n parts.push(\n sqliteGeoPointCheck(\n column,\n (name) => this.escapeIdentifier(name),\n sqliteGeoPointEncoding(column)\n )\n );\n }\n\n // The reserved decimal CHECK is a DERIVED render of the column's own\n // descriptor, emitted as a column CONSTRAINT beside the type — never\n // folded INTO `column.type`. `getEnumColumnType` above does fold its CHECK\n // into the type, and the measured cost is a full table recreation on every\n // push forever: `PRAGMA table_info.type` reports only the `type-name`\n // production, so the desired `TEXT CHECK(...)` never equals the\n // introspected `TEXT`. A named constraint reads back out of\n // `sqlite_master.sql` instead, which is where introspection recovers the\n // descriptor from.\n const kind = sqliteDecimalStorageKind(column);\n if (column.decimal && kind) {\n parts.push(\n sqliteDecimalCheck(column, column.decimal, kind, (name) =>\n this.escapeIdentifier(name)\n )\n );\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // TABLE RECREATION\n // ===========================================================================\n\n /**\n * Generates SQL for table recreation.\n * This is the Drizzle-style pattern for operations SQLite doesn't support.\n *\n * Steps:\n * 1. PRAGMA foreign_keys=OFF\n * 2. Create new table with desired schema\n * 3. Copy data from old table (using explicit column mapping by name)\n * 4. Drop old table\n * 5. Rename new table\n * 6. Recreate indexes\n * 7. PRAGMA foreign_keys=ON\n *\n * @param tableName - The table to recreate\n * @param newTable - The new table definition\n * @param currentTable - The current table definition (required for safe column mapping)\n * @param columnRenames - Optional map of old column name to new column name\n */\n protected compileTableRecreation(\n tableName: string,\n newTable: TableDef,\n currentTable: TableDef,\n context: DDLContext,\n columnRenames?: Map<string, string>,\n valueExpressions?: ReadonlyMap<string, string>\n ): string[] {\n const statements: string[] = [];\n const tempName = `${RECREATION_PREFIX}${tableName}`;\n const currentColumns = new Map(\n currentTable.columns.map((column) => [column.name, column])\n );\n const sourceNames = new Map<string, string>();\n for (const [oldName, newName] of columnRenames ?? []) {\n sourceNames.set(newName, oldName);\n }\n const usesCorrelatedListCopy = newTable.columns.some((column) => {\n const sourceName = sourceNames.get(column.name) ?? column.name;\n return (\n this.decimalConversionKind(currentColumns.get(sourceName), column) ===\n \"list\"\n );\n });\n // A list conversion opens correlated `json_each` tables whose ten virtual\n // column names are ordinary legal user column names. Every outer read is\n // qualified through this one statement-local alias so `\"value\"`, `\"key\"`,\n // and their siblings cannot be captured by the inner table. Ordinary and\n // scalar-only recreations retain their original unaliased SQL.\n const sourceAlias = \"__viborm_source\";\n\n // 1. Disable foreign keys\n statements.push(\"PRAGMA foreign_keys=OFF\");\n\n // 2. Create new table\n statements.push(\n this.generateCreateTableDef({ ...newTable, name: tempName }, context)\n );\n\n // 3. Copy data - EXPLICIT column mapping by NAME, not position\n // Build a set of current column names for quick lookup\n // For each column in the new table, find the corresponding source column.\n // `source` is an EXPRESSION, not an identifier: a decimal column whose\n // declared domain moved is converted here, inside the database, on the way\n // across.\n const copyColumns: Array<{ source: string; target: string }> = [];\n\n for (const col of newTable.columns) {\n const sourceName = sourceNames.get(col.name) ?? col.name;\n\n // Only copy if source column exists in current table\n const currentColumn = currentColumns.get(sourceName);\n if (currentColumn !== undefined) {\n const source = usesCorrelatedListCopy\n ? `${this.escapeIdentifier(sourceAlias)}.${this.escapeIdentifier(sourceName)}`\n : this.escapeIdentifier(sourceName);\n copyColumns.push({\n source:\n valueExpressions?.get(col.name) ??\n this.copySourceExpression(\n tableName,\n sourceName,\n currentColumn,\n col,\n source\n ),\n target: col.name,\n });\n } else if (!col.nullable && col.default === undefined) {\n // New NOT NULL column without default - INSERT will fail\n throw new MigrationError(\n `Cannot add NOT NULL column \"${col.name}\" without a default value during table recreation. ` +\n \"SQLite requires a default value or nullable column for table recreation.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED\n );\n }\n // New columns with defaults or nullable will get their default/NULL values\n }\n\n if (copyColumns.length > 0) {\n const selectCols = copyColumns.map((c) => c.source).join(\", \");\n const insertCols = copyColumns\n .map((c) => this.escapeIdentifier(c.target))\n .join(\", \");\n\n statements.push(\n `INSERT INTO ${this.escapeIdentifier(tempName)} (${insertCols}) ` +\n `SELECT ${selectCols} FROM ${this.escapeIdentifier(tableName)}` +\n (usesCorrelatedListCopy\n ? ` AS ${this.escapeIdentifier(sourceAlias)}`\n : \"\")\n );\n }\n\n // 4. Drop old table\n statements.push(`DROP TABLE ${this.escapeIdentifier(tableName)}`);\n\n // 5. Rename new table\n statements.push(\n `ALTER TABLE ${this.escapeIdentifier(tempName)} RENAME TO ${this.escapeIdentifier(tableName)}`\n );\n\n // 6. Recreate indexes (they were dropped with the old table)\n for (const idx of newTable.indexes) {\n statements.push(\n this.generateCreateIndex(\n { type: \"createIndex\", tableName, index: idx },\n context\n )\n );\n }\n\n // 7. Re-enable foreign keys\n statements.push(\"PRAGMA foreign_keys=ON\");\n\n return this.filterStatements(statements);\n }\n\n /**\n * What the recreation SELECTs for one column of the rebuilt table.\n *\n * Ordinarily the column itself. When the column's declared decimal domain\n * moved, it is the conversion expression instead: SQLite stores the unscaled\n * coefficient, so a scale change makes every stored integer mean a different\n * number until it is rescaled, and the whole conversion runs inside the\n * database because the rebuild is one `INSERT ... SELECT` this process never\n * reads a row of.\n *\n * A change that moves the STORAGE SHAPE — a scalar becoming a list, or the\n * other way — gets no conversion and no second guard: the value is copied as\n * it stands and the target column's own reserved CHECK refuses it, which\n * aborts the rebuild inside its transaction and leaves the old table exactly\n * as it was.\n *\n * A source column that declares NO domain is the third case, and it is a\n * conversion too. An `INTEGER` holding logical integers, adopted as\n * `decimal(p,s)`, has to become a coefficient: copied as it stands, `123`\n * would silently start reading as 1.23. Only that one adoption is converted.\n * A TEXT source or a list target has no proven logical scale, and SQLite can\n * coerce numeric text after the copy, so every other unmarked source refuses\n * here before the recreation exists.\n *\n * A decimal column leaving its domain is descaled the same way, by\n * `descaledDecimalSource`.\n *\n * A column with no decimal or DateTime target whose type changes affinity\n * (`sqliteConvertingAffinity`) is converted with a `CAST` that must compare\n * equal to the source under SQLite's own rules. A value that does not —\n * 'twelve' or 1.5 into INTEGER, a BLOB into TEXT — aborts the rebuild like\n * an inexact DateTime instead of being stored unconverted.\n */\n private copySourceExpression(\n tableName: string,\n sourceName: string,\n currentColumn: ColumnDef | undefined,\n targetColumn: ColumnDef,\n source: string\n ): string {\n if (\n targetColumn.geoPointEncoding === \"binary64\" &&\n currentColumn !== undefined &&\n sqliteGeoPointEncoding(currentColumn) === \"legacy\"\n ) {\n return `CASE WHEN ${source} IS NULL THEN NULL ELSE ${sqliteGeoPointCarrier(source)} END`;\n }\n const dateTime = targetColumn.dateTime;\n if (dateTime !== undefined) {\n const sourceForm = this.sqliteDateTimeSourceForm(currentColumn);\n if (sourceForm === undefined) {\n const sourceDomain =\n currentColumn?.decimal === undefined\n ? `${currentColumn?.type ?? \"unknown\"} storage`\n : `a fixed-decimal domain at ${describeDecimalDomain(currentColumn.decimal)}`;\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would adopt ${sourceDomain} as a SQLite DateTime. ` +\n \"Only a declared DateTime or unmarked TEXT, INTEGER epoch-millisecond, or REAL Julian-day candidate can be converted exactly. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"SQLite DateTime storage conversion\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n return sqliteDateTimeCopyExpression(\n source,\n sourceForm,\n dateTime,\n currentColumn?.dateTime !== undefined\n );\n }\n\n const to = targetColumn.decimal;\n const targetKind = sqliteDecimalStorageKind(targetColumn);\n const from = currentColumn?.decimal;\n if (to === undefined && currentColumn !== undefined && from !== undefined) {\n return this.descaledDecimalSource(\n tableName,\n sourceName,\n { ...currentColumn, decimal: from },\n targetColumn.type,\n source\n );\n }\n if (to === undefined || targetKind === undefined) {\n const affinity =\n currentColumn && sqliteConvertingAffinity(currentColumn, targetColumn);\n return affinity === undefined\n ? source\n : `CASE WHEN ${source} IS NULL THEN NULL WHEN CAST(${source} AS ${affinity}) = ${source} THEN CAST(${source} AS ${affinity}) ELSE ${SQLITE_ABORT} END`;\n }\n\n if (from === undefined) {\n const adopting =\n targetKind === \"scalar\" &&\n currentColumn?.type.toUpperCase() === \"INTEGER\";\n if (!adopting) {\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would adopt unmarked ${currentColumn?.type ?? \"unknown\"} storage as a fixed-decimal ${targetKind}. ` +\n \"Only a scalar INTEGER has one exact descriptor-free meaning that can be rescaled into the target domain. TEXT and every list container carry no proven member scale, while other SQLite affinities can already have changed the stored value. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"decimal storage adoption\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n return sqliteDecimalCopyExpression(source, undefined, to, \"scalar\");\n }\n if (sameDecimalDescriptor(from, to)) return source;\n const conversionKind = this.decimalConversionKind(\n currentColumn,\n targetColumn\n );\n if (conversionKind === undefined) return source;\n return sqliteDecimalCopyExpression(source, from, to, conversionKind);\n }\n\n /**\n * A fixed-decimal source copied into a column that declares no domain.\n *\n * SQLite stores the scaled coefficient, so the value is descaled on the way\n * across: 1.23 at scale 2 is stored as 123 and must not read back as 123.\n * Only an INTEGER target holds the result exactly, and a value with a\n * fraction — or a stored value that is no coefficient at all — aborts the\n * rebuild through `SQLITE_ABORT`. The decimal copy helper guards the same\n * way, but its sentinel relies on a reserved CHECK this target does not\n * carry.\n * Every other target (TEXT, REAL, a list) has no one exact spelling of the\n * value and is refused here, before the recreation exists.\n */\n private descaledDecimalSource(\n tableName: string,\n sourceName: string,\n currentColumn: ColumnDef & { decimal: NonNullable<ColumnDef[\"decimal\"]> },\n targetType: string,\n source: string\n ): string {\n const kind = sqliteDecimalStorageKind(currentColumn);\n if (kind === \"scalar\" && sqliteAffinity(targetType) === \"INTEGER\") {\n const factor = 10n ** BigInt(currentColumn.decimal.scale);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'integer' AND ${source} % ${factor} = 0 THEN ${source} / ${factor} ELSE ${SQLITE_ABORT} END`;\n }\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would copy a fixed-decimal ${kind ?? \"column\"} at ${describeDecimalDomain(currentColumn.decimal)} into ${targetType} storage that declares no decimal domain. ` +\n \"SQLite stores the decimal as its scaled integer coefficient, and only a scalar copied into INTEGER storage can be descaled exactly. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"decimal storage conversion\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n\n /** Physical source vocabulary for a target known to be a DateTime. */\n private sqliteDateTimeSourceForm(\n column: ColumnDef | undefined\n ): \"text\" | \"epochMillis\" | \"julianDay\" | undefined {\n if (column?.dateTime !== undefined) return column.dateTime;\n if (column?.decimal !== undefined) return undefined;\n switch (column?.type.toUpperCase()) {\n case \"TEXT\":\n return \"text\";\n case \"INTEGER\":\n return \"epochMillis\";\n case \"REAL\":\n return \"julianDay\";\n default:\n return undefined;\n }\n }\n\n /** The shared-storage decimal conversion one copied column requires. */\n private decimalConversionKind(\n currentColumn: ColumnDef | undefined,\n targetColumn: ColumnDef\n ): \"scalar\" | \"list\" | undefined {\n const from = currentColumn?.decimal;\n const to = targetColumn.decimal;\n if (\n currentColumn === undefined ||\n from === undefined ||\n to === undefined ||\n sameDecimalDescriptor(from, to)\n ) {\n return undefined;\n }\n const targetKind = sqliteDecimalStorageKind(targetColumn);\n if (\n targetKind === undefined ||\n sqliteDecimalStorageKind(currentColumn) !== targetKind\n ) {\n return undefined;\n }\n return targetKind;\n }\n\n /**\n * Refuses a domain conversion the substrate cannot rebuild safely, BEFORE\n * any statement runs.\n *\n * Every SQLite descriptor change is a table recreation, and a recreation\n * drops and rebuilds the table with foreign-key enforcement disabled. That\n * disable is only real when `PRAGMA foreign_keys=OFF` runs OUTSIDE the\n * transaction — SQLite documents it as a no-op inside one — and the lift is\n * proven only inside a transaction that can roll it back\n * (`foreignKeyPragmasCannotBeLifted`). A driver without one cannot prove it:\n * on D1 the pragma travels inside one native batch and does nothing, so\n * `DROP TABLE` either raises the constraint or silently fires the\n * referential action on every child row.\n *\n * D1 is the shipped case, and plan §7.4 states the prerequisite exactly: a\n * relation-bearing rebuild is admitted only after the foreign-key-safe\n * rebuild is proven across the ten relation shapes. Until then this refuses\n * with the substrate reason rather than shipping an unsafe drop/recreate or\n * a manual shadow-column instruction.\n *\n * Only relation-bearing tables are refused: a table with no reference in\n * either direction has nothing the disabled enforcement could damage, so\n * fresh decimal schemas and ordinary descriptor changes stay available.\n *\n * The question remains conversion-owned: decimal descriptor changes and\n * adoption, decimal carrier renames, and DateTime form/adoption transitions\n * ask this owner. A recreation requested by another column, constraint, key,\n * or enum does not become a domain conversion merely because the same table\n * also contains one of these scalars. General D1 reconstruction safety is an\n * existing migration concern outside this boundary.\n */\n private assertDomainReconstructionAdmitted(\n tableName: string,\n column: ColumnDef,\n table: TableDef,\n context: DDLContext,\n domain: \"decimal\" | \"dateTime\"\n ): void {\n let description: string;\n let feature: string;\n if (domain === \"decimal\") {\n if (column.decimal === undefined) return;\n description = `a fixed-decimal column at ${describeDecimalDomain(column.decimal)}`;\n feature = \"decimal descriptor conversion\";\n } else {\n if (column.dateTime === undefined) return;\n description = `a SQLite DateTime column in ${column.dateTime} storage`;\n feature = \"SQLite DateTime storage conversion\";\n }\n const driver = this.executionDriver;\n if (!(driver && foreignKeyPragmasCannotBeLifted(driver))) return;\n if (\n !sqliteTableBearsRelations(\n tableName,\n context.currentSchema?.tables ?? [],\n table,\n context.precedingOperations\n )\n ) {\n return;\n }\n throw new MigrationError(\n `Rebuilding \"${tableName}\".\"${column.name}\", ${description}, recreates the whole table, and the driver \"${driver.driverName}\" runs migrations without a transaction (D1 runs them as one native batch). ` +\n \"Without a transaction, `PRAGMA foreign_keys=OFF` cannot be proven before the rebuild drops a table that still has references, nor the drop rolled back — and a pragma that did not take raises on one referential action and silently deletes or nulls child rows on another. \" +\n \"The change is refused before any statement runs, so the schema and its data are exactly as they were. Recreate the table without its references, or run the change on a driver with transactions.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n driver: driver.driverName,\n table: tableName,\n column: column.name,\n feature,\n },\n }\n );\n }\n\n /**\n * Helper to generate CREATE TABLE DDL without indexes\n */\n protected generateCreateTableDef(\n table: TableDef,\n context: DDLContext\n ): string {\n const parts: string[] = [];\n\n // Columns\n for (const col of table.columns) {\n parts.push(this.generateColumnDef(col, context));\n }\n\n // Primary key (if composite or not INTEGER autoincrement)\n if (table.primaryKey) {\n const isSingleIntegerPK =\n table.primaryKey.columns.length === 1 &&\n table.columns.find(\n (c) =>\n c.name === table.primaryKey!.columns[0] &&\n c.type.toUpperCase() === \"INTEGER\" &&\n c.autoIncrement\n );\n\n if (!isSingleIntegerPK) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n parts.push(`PRIMARY KEY (${pkCols})`);\n }\n }\n\n // Unique constraints. One read back from the live table has SQLite's own\n // `sqlite_autoindex_<table>_<n>` for a name, which a recreation must not\n // carry into the new table: it is written unnamed, as SQLite reports it.\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n parts.push(\n uq.name.startsWith(SQLITE_AUTOINDEX_PREFIX)\n ? `UNIQUE (${uqCols})`\n : `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n // Foreign keys\n for (const fk of table.foreignKeys) {\n const fkCols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n\n let fkDef = `CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n fkDef += `FOREIGN KEY (${fkCols}) `;\n fkDef += `REFERENCES ${this.escapeIdentifier(fk.referencedTable)} (${refCols})`;\n\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n fkDef += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n fkDef += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n\n parts.push(fkDef);\n }\n\n // A recreation builds from this definition too, so it keeps the option.\n const options = table.primaryKey?.withoutRowid ? \" WITHOUT ROWID\" : \"\";\n return `CREATE TABLE ${this.escapeIdentifier(table.name)} (\\n ${parts.join(\",\\n \")}\\n)${options}`;\n }\n\n /**\n * The table definition a recreation has to rebuild — the introspected one,\n * moved on by every preceding operation of the same batch.\n *\n * `currentSchema` is read once, before the first statement runs, so on its own\n * it describes the table as it was. A recreation drops the table and rebuilds\n * whatever this definition names, so read raw it destroys everything the same\n * batch created earlier and resurrects everything the same batch dropped. Each\n * list is a measured hazard, not a hypothetical:\n *\n * - INDEXES. `createIndex` runs at priority 15 and `addForeignKey` at 16, and\n * SQLite recreates the table for every foreign-key change — so on a database\n * that predates the FK index each foreign-key push created the index and\n * then threw it away, forever.\n *\n * - FOREIGN KEYS. `dropForeignKey` runs at 2 and `addForeignKey` at 16, and\n * the differ plans that pair for every changed key. With the pre-batch list\n * the add rebuilt the table around the constraint the drop had just removed\n * AND its replacement: measured on better-sqlite3, `zz_posts` held 1, then\n * 2, then 3 identical foreign keys after three idempotent pushes.\n *\n * - COLUMNS. `addColumn` runs at 10 and `alterColumn` at 12, and `alterColumn`\n * is a recreation on SQLite. Measured: pushing a model that both widens one\n * column's type and adds another emitted the `ALTER TABLE ... ADD COLUMN`,\n * then rebuilt the table from the pre-batch column list — and the new column\n * was gone. The push reported success, and the next one added and lost it\n * again. Two `alterColumn`s in one batch reverted each other the same way.\n *\n * - UNIQUE CONSTRAINTS. `dropUniqueConstraint` runs at 4 and\n * `addUniqueConstraint` at 14, and both ARE recreations here — the\n * constraint is inline in `CREATE TABLE` (see\n * `generateAddUniqueConstraint`). So the pair a changed constraint plans\n * reads its own predecessor, and a later recreation at 16 has to rebuild\n * around the constraint the add put there rather than the one the drop\n * removed.\n *\n * - PRIMARY KEY. `dropPrimaryKey` runs at 5 and `addPrimaryKey` at 13, both\n * ahead of `addForeignKey`, so a later recreation would rebuild around the\n * key that was just replaced.\n *\n * - INBOUND FOREIGN KEYS. Native SQLite table and column renames rewrite\n * references stored in OTHER tables. If one of those tables is recreated\n * later in the batch, its pre-batch definition would restore the old table\n * or column name unless the same replay carries the rename's remote effect.\n *\n * These are all the operations that move any of those five out of `TableDef`,\n * plus the two native renames whose effects cross table boundaries. Replaying\n * them gives what the database actually holds when the recreation runs.\n */\n protected getCurrentTable(\n tableName: string,\n context: DDLContext\n ): TableDef | undefined {\n return replaySchemaTables(\n context.currentSchema?.tables ?? [],\n context.precedingOperations ?? []\n ).find((table) => table.name === tableName);\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): readonly string[] {\n const { table } = op;\n const statements: string[] = [this.generateCreateTableDef(table, context)];\n\n // Create indexes separately\n for (const idx of table.indexes) {\n statements.push(\n this.generateCreateIndex(\n {\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n },\n context\n )\n );\n }\n\n return statements;\n }\n\n generateDropTable(op: DropTableOperation, _context: DDLContext): string {\n return `DROP TABLE ${this.escapeIdentifier(op.tableName)}`;\n }\n\n generateRenameTable(op: RenameTableOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.from)} RENAME TO ${this.escapeIdentifier(op.to)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(\n op: AddColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n if (\n op.column.default !== undefined &&\n COMPUTED_DEFAULT_PREFIX.test(op.column.default)\n ) {\n const current = this.getCurrentTable(op.tableName, context);\n if (!current)\n throw new MigrationError(\n `Cannot add computed default: table \"${op.tableName}\" is absent`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return this.compileTableRecreation(\n op.tableName,\n { ...current, columns: [...current.columns, op.column] },\n current,\n context\n );\n }\n const colDef = this.generateColumnDef(op.column, context);\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation, _context: DDLContext): string {\n // SQLite 3.35.0+ supports DROP COLUMN\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n /**\n * Renames a column — natively first, then through a table recreation when\n * that column is a decimal.\n *\n * The descriptor rides in a CHECK constraint whose NAME contains the column\n * name, and `ALTER TABLE … RENAME COLUMN` rewrites column REFERENCES inside a\n * CHECK body but never a constraint NAME. So the native rename leaves the\n * carrier behind, pointing at a column that no longer exists: introspection\n * reads the renamed column as carrying no domain, the next push plans an\n * alteration between a domain and nothing, and the stored coefficient is\n * copied unchanged under whatever scale the schema now declares — 12345\n * meaning 123.45 silently becomes 1.2345. It is not even destructive by the\n * differ's reading, because no domain narrowed, so no prompt fires.\n *\n * The native statement has a second job a recreation cannot perform: SQLite\n * rewrites inbound foreign keys stored in OTHER tables. Only after that\n * schema-wide propagation does the ordinary recreation replace the stale\n * carrier name on the already-renamed table. The reconstruction therefore\n * copies the new column name from a current definition that already contains\n * the rename; it is not a second rename mechanism.\n */\n generateRenameColumn(\n op: RenameColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n const renamed = currentTable?.columns.find(\n (column) => column.name === op.from\n );\n // SQLite 3.25.0+ supports RENAME COLUMN\n const nativeRename = `ALTER TABLE ${this.escapeIdentifier(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n if (currentTable === undefined || renamed?.decimal === undefined) {\n // SQLite rewrites the index's text, but not the marker in its comment.\n return [\n nativeRename,\n ...this.rawIndexesRenamedBy(op, context).flatMap((index) => [\n this.generateDropIndex(\n {\n type: \"dropIndex\",\n tableName: op.tableName,\n indexName: index.name,\n },\n context\n ),\n this.generateCreateIndex(\n { type: \"createIndex\", tableName: op.tableName, index },\n context\n ),\n ]),\n ];\n }\n\n const renamedTable = applyNativeRename({ tables: [currentTable] }, op)\n .tables[0];\n if (renamedTable === undefined) {\n throw new MigrationError(\n `Cannot rename column: table \"${op.tableName}\" disappeared from the current schema.`,\n VibORMErrorCode.INTERNAL_ERROR,\n { meta: { table: op.tableName, column: op.from } }\n );\n }\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n renamed,\n renamedTable,\n context,\n \"decimal\"\n );\n return [\n nativeRename,\n ...this.compileTableRecreation(\n op.tableName,\n renamedTable,\n renamedTable,\n context\n ),\n ];\n }\n\n generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n return this.compileAlterColumnByRecreation(op, context, true);\n }\n\n /**\n * SQLite's value-preserving ALTER COLUMN implementation. `grouped` folds a\n * run of compatible changes to one table into one recreation; a dialect\n * that recreates only some changes (LibSQL) recreates each on its own.\n */\n protected compileAlterColumnByRecreation(\n op: AlterColumnOperation,\n context: DDLContext,\n grouped: boolean\n ): readonly string[] {\n const group = [op];\n if (grouped && context.followingOperations) {\n const compatible = (\n candidate: DiffOperation | undefined\n ): candidate is AlterColumnOperation =>\n candidate?.type === \"alterColumn\" &&\n candidate.tableName === op.tableName &&\n isDestructiveOperation(candidate) === isDestructiveOperation(op);\n const previous: AlterColumnOperation[] = [];\n for (const candidate of [\n ...(context.precedingOperations ?? []),\n ].reverse()) {\n if (!compatible(candidate)) break;\n previous.unshift(candidate);\n }\n const following: AlterColumnOperation[] = [];\n for (const candidate of context.followingOperations) {\n if (!compatible(candidate)) break;\n following.push(candidate);\n }\n const run = [...previous, op, ...following];\n // Repeated changes to the same column are sequential semantics, not one projection.\n if (new Set(run.map((change) => change.columnName)).size === run.length) {\n if (previous.length > 0) return [];\n group.push(...following);\n }\n }\n // SQLite doesn't support ALTER COLUMN - need table recreation\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot alter column: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const targets = new Map(\n group.map((change) => [change.columnName, change.to])\n );\n const newColumns = currentTable.columns.map(\n (column) => targets.get(column.name) ?? column\n );\n\n const newTable: TableDef = {\n ...currentTable,\n columns: newColumns,\n };\n\n for (const change of group) {\n if (decimalConversionRequired(change.from, change.to)) {\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n change.to,\n newTable,\n context,\n \"decimal\"\n );\n } else if (\n sqliteDateTimeTargetRequiresRecreation(\n change.from.dateTime,\n change.to.dateTime\n )\n ) {\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n change.to,\n newTable,\n context,\n \"dateTime\"\n );\n }\n }\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n generateCreateIndex(op: CreateIndexOperation, _context: DDLContext): string {\n const { tableName, index } = op;\n if (index.raw) {\n const rendered = renderRawIndex(index, {\n name: this.escapeIdentifier(index.name),\n table: this.escapeIdentifier(tableName),\n column: (column) => this.escapeIdentifier(column),\n });\n refuseRawIndexStatement(\n index,\n rendered,\n (text) => readExecutableStatements(text, \"sqlite\"),\n []\n );\n // SQLite keeps an index's text as written, a trailing comment included,\n // and rewrites only identifiers on a rename: the comment is its marker.\n // Every `/` is escaped so that no name can close the comment early.\n return `${rendered} /* ${RAW_INDEX_MARKER_PREFIX}${rawIndexMarker(index).replaceAll(\"/\", \"\\\\/\")} */`;\n }\n\n // Validate index type against capabilities (SQLite only supports btree)\n this.validateIndexType(index.type, index.name);\n\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n // SQLite has supported partial indexes since 3.8.0. Dropping the predicate\n // silently would build a different index from the declared one, and the\n // differ would re-create it on every push forever, because introspection\n // reads the predicate back.\n const where = index.where ? ` WHERE ${index.where}` : \"\";\n // SQLite doesn't support USING clause - it only has btree indexes\n return `CREATE ${unique}INDEX ${this.escapeIdentifier(index.name)} ON ${this.escapeIdentifier(tableName)} (${cols})${where}`;\n }\n\n generateDropIndex(op: DropIndexOperation, _context: DDLContext): string {\n return `DROP INDEX ${this.escapeIdentifier(op.indexName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"add foreign key\",\n (table) => ({\n ...table,\n foreignKeys: [...table.foreignKeys, op.fk],\n })\n );\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"drop foreign key\",\n (table) => ({\n ...table,\n foreignKeys: table.foreignKeys.filter((fk) => fk.name !== op.fkName),\n })\n );\n }\n\n /**\n * Recreates `tableName` as `change` derives it from the table the batch has\n * left, which is how SQLite changes an inline foreign key, unique or primary\n * key.\n */\n protected recreateWith(\n tableName: string,\n context: DDLContext,\n action: string,\n change: (table: TableDef) => TableDef\n ): string[] {\n const currentTable = this.getCurrentTable(tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot ${action}: table \"${tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n return this.compileTableRecreation(\n tableName,\n change(currentTable),\n currentTable,\n context\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n /**\n * A unique constraint is INLINE in `CREATE TABLE` on SQLite, so both halves\n * of the diff go through a table recreation. There is no other spelling that\n * round-trips.\n *\n * SQLite has two ways to spell \"these columns are unique\" and only one of\n * them survives introspection as a constraint. An inline\n * `CONSTRAINT x UNIQUE (...)` is reported by `PRAGMA index_list` with\n * `origin = \"u\"`, which `introspect` files under `uniqueConstraints` —\n * matched by shape against the declared one (see\n * `introspectionReadsConstraintNames`), so an unchanged schema plans nothing.\n * A standalone `CREATE UNIQUE INDEX` is reported with `origin = \"c\"` and\n * filed under `indexes` instead, where no declared unique constraint will\n * ever match it.\n *\n * Measured on better-sqlite3 at `f78fa83`, with the add as a standalone\n * index: push #2 of a model that gained `.unique([\"slug\", \"tenant\"])`\n * planned `addUniqueConstraint` and created the index; push #3 read that\n * index back under the wrong bucket and planned `addUniqueConstraint` again\n * beside `dropIndex` on the same name — and since `addUniqueConstraint` (14)\n * runs ahead of a superseded index drop (15.5), the push died on\n * `index \"…_slug_tenant_key\" already exists`. Every later push died the same\n * way. Before the shape matching landed the FK churn rebuilt the table on\n * every push and destroyed the index before push #3 could collide with it,\n * so the same schema pushed green forever and the unique was never enforced.\n *\n * The drop had no working spelling at all: every `dropUniqueConstraint` the\n * differ plans here names a constraint read out of `PRAGMA index_list` with\n * `origin = \"u\"`, i.e. `sqlite_autoindex_<table>_<n>`, and SQLite refuses\n * `DROP INDEX` on an index it created itself.\n *\n * A database written by the old add still holds the standalone index. It\n * heals on the next push: the recreation rebuilds the table with the\n * constraint inline, and the stale index — dropped with the old table and\n * re-created by step 6 of the recreation, because it is still in the\n * introspected definition — is removed by the `dropIndex` the same batch\n * plans for it.\n */\n generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"add unique constraint\",\n (table) => ({\n ...table,\n uniqueConstraints: [...table.uniqueConstraints, op.constraint],\n })\n );\n }\n\n generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"drop unique constraint\",\n (table) => ({\n ...table,\n uniqueConstraints: table.uniqueConstraints.filter(\n (constraint) => constraint.name !== op.constraintName\n ),\n })\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"add primary key\",\n (table) => ({\n ...table,\n primaryKey: op.primaryKey,\n })\n );\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"drop primary key\",\n (table) => ({\n ...table,\n primaryKey: undefined,\n })\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateCreateEnum(_op: CreateEnumOperation, _context: DDLContext): string {\n // SQLite enums use CHECK constraints embedded in column definitions\n // No separate enum type creation needed\n return \"-- SQLite: enum CHECK constraint is part of column definition\";\n }\n\n generateDropEnum(\n op: DropEnumOperation,\n context: DDLContext\n ): string | readonly string[] {\n // Dropping an enum means removing CHECK constraints from dependent columns\n // This requires table recreation for each dependent table\n const { enumName, dependentColumns } = op;\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return `-- SQLite: no dependent columns for enum \"${enumName}\"`;\n }\n\n const statements: string[] = [];\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n throw new MigrationError(\n `Table \"${dep.tableName}\" not found for enum \"${enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n // Change the column type to plain TEXT (remove CHECK constraint)\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName && col.type.includes(\"CHECK\")) {\n return { ...col, type: \"TEXT\" };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n statements.push(\n ...this.compileTableRecreation(\n dep.tableName,\n newTable,\n currentTable,\n context\n )\n );\n }\n\n return statements;\n }\n\n generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): string | readonly string[] {\n // Altering an enum means updating CHECK constraints on dependent columns\n // This requires table recreation for each dependent column\n const { enumName, newValues, dependentColumns } = op;\n const statements: string[] = [];\n\n if (!newValues || newValues.length === 0) {\n return `-- SQLite: no new values provided for enum \"${enumName}\"`;\n }\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return `-- SQLite: no dependent columns found for enum \"${enumName}\"`;\n }\n\n // Apply mappings in the reconstruction SELECT. A replacement belongs to\n // the destination CHECK, including a value introduced in this change.\n\n // Generate new CHECK constraint\n const escapedValues = newValues\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n statements.push(`-- SQLite: table \"${dep.tableName}\" not found`);\n continue;\n }\n\n // Build new CHECK constraint for this column\n const newCheckType = `TEXT CHECK(${this.escapeIdentifier(dep.columnName)} IN (${escapedValues}))`;\n\n // Update the column type with new CHECK\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName) {\n return { ...col, type: newCheckType };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n const source = this.escapeIdentifier(dep.columnName);\n const cases = this.enumReplacementCases(\n op,\n dep.tableName,\n dep.columnName\n );\n const expressions =\n cases.length === 0\n ? undefined\n : new Map([\n [\n dep.columnName,\n `CASE ${source} ${cases.join(\" \")} ELSE ${source} END`,\n ],\n ]);\n statements.push(\n ...this.compileTableRecreation(\n dep.tableName,\n newTable,\n currentTable,\n context,\n undefined,\n expressions\n )\n );\n }\n\n return statements;\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n generateAcquireLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n // Return null to signal that locking is handled differently\n return null;\n }\n\n generateReleaseLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n return null;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n generateInventoryTables(): { sql: string; params: unknown[] } {\n return {\n sql: \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n params: [],\n };\n }\n\n generateInventoryEnums(): { sql: string; params: unknown[] } | null {\n // SQLite doesn't support enums\n return null;\n }\n}\n\n// Export singleton instance\nexport const sqlite3MigrationDriver = new SQLite3MigrationDriver();\n","/**\n * LibSQL Migration Driver\n *\n * Extends SQLite3 driver with native ALTER COLUMN support.\n * LibSQL supports ALTER TABLE ALTER COLUMN syntax that SQLite doesn't,\n * avoiding expensive table recreation for column modifications.\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This differs from PostgreSQL's behavior where constraints\n * are validated against all existing rows.\n */\n\nimport { sqliteDateTimeTargetRequiresRecreation } from \"../../../adapters/databases/sqlite/storage/datetime\";\nimport { sqliteDecimalCheck } from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n SQLITE_GEO_POINT_TYPE,\n sqliteGeoPointCheck,\n sqliteGeoPointEncoding,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport {\n decimalConversionRequired,\n sqliteDecimalStorageKind,\n} from \"../../decimal\";\nimport type { ColumnDef, ReferentialAction } from \"../../types\";\nimport type {\n AddForeignKeyOperation,\n AlterColumnOperation,\n DDLContext,\n DropForeignKeyOperation,\n} from \"../base\";\nimport { SQLite3MigrationDriver } from \"../sqlite\";\nimport type { MigrationCapabilities } from \"../types\";\n\nexport class LibSQLMigrationDriver extends SQLite3MigrationDriver {\n override readonly driverName: string = \"libsql\";\n\n // Same capabilities as SQLite3 (no native enums, no arrays, btree only)\n override readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true,\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n // Adds FKs by rewriting the column (`ALTER COLUMN ... TO`), which needs the\n // existing column def — not a standalone add. Keep FKs inline in CREATE\n // TABLE and rely on lazy reference resolution (forward refs are fine).\n supportsAddForeignKeyViaAlter: false,\n // Inherits SQLite's introspection verbatim, so the same two names are\n // unreadable here.\n introspectionReadsConstraintNames: false,\n };\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: ALTER COLUMN (native support)\n // ===========================================================================\n\n /**\n * LibSQL supports ALTER TABLE ... ALTER COLUMN ... TO syntax.\n * This avoids table recreation for column type/default/nullable changes.\n *\n * Syntax: ALTER TABLE t ALTER COLUMN c TO c <new_column_def>\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This is different from PostgreSQL's behavior.\n */\n override generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n // A decimal descriptor change CONVERTS stored values — SQLite holds the\n // unscaled coefficient, so the same integer means a different number at a\n // different scale. The native ALTER rewrites the column DECLARATION and\n // copies nothing, and by LibSQL's own contract (above) it validates only\n // rows written afterwards, so every existing row would keep its old\n // coefficient under the new domain and read back wrong. Table recreation\n // is the only route that carries the values across; §9.6 states it as a\n // falsifier (\"LibSQL cannot take a native ALTER route that skips\n // conversion\").\n if (\n decimalConversionRequired(op.from, op.to) ||\n sqliteDateTimeTargetRequiresRecreation(op.from.dateTime, op.to.dateTime)\n ) {\n return this.compileAlterColumnByRecreation(op, context, false);\n }\n\n const { tableName, columnName, to } = op;\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(columnName);\n\n // Build new column definition\n const colDef = this.generateColumnDef(to, context);\n\n // LibSQL syntax: ALTER TABLE t ALTER COLUMN old_name TO new_def\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n // ===========================================================================\n // HELPER: Build column definition with optional REFERENCES\n // ===========================================================================\n\n /**\n * Builds a column definition string with optional foreign key REFERENCES clause.\n * Used for LibSQL's ALTER COLUMN TO syntax.\n */\n private buildColumnDefWithReferences(\n column: ColumnDef,\n fkRef?: {\n refTable: string;\n refCol: string;\n onDelete?: ReferentialAction;\n onUpdate?: ReferentialAction;\n }\n ): string {\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n if (column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE) {\n parts.push(\n sqliteGeoPointCheck(\n column,\n (name) => this.escapeIdentifier(name),\n sqliteGeoPointEncoding(column)\n )\n );\n }\n\n // The reserved decimal CHECK travels with the rewritten declaration.\n // `ALTER COLUMN ... TO` replaces the WHOLE column definition, so a\n // constraint this rebuild left out would be gone from the stored\n // `CREATE TABLE` — and with it the only carrier of the column's declared\n // domain, which introspection would then read as a descriptor change on\n // every push afterwards.\n const kind = sqliteDecimalStorageKind(column);\n if (column.decimal && kind) {\n parts.push(\n sqliteDecimalCheck(column, column.decimal, kind, (name) =>\n this.escapeIdentifier(name)\n )\n );\n }\n\n if (fkRef) {\n parts.push(\n `REFERENCES ${this.escapeIdentifier(fkRef.refTable)}(${this.escapeIdentifier(fkRef.refCol)})`\n );\n if (fkRef.onDelete && fkRef.onDelete !== \"noAction\") {\n parts.push(`ON DELETE ${this.formatReferentialAction(fkRef.onDelete)}`);\n }\n if (fkRef.onUpdate && fkRef.onUpdate !== \"noAction\") {\n parts.push(`ON UPDATE ${this.formatReferentialAction(fkRef.onUpdate)}`);\n }\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n /**\n * LibSQL can add foreign keys by redefining the column with REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n *\n * Note: Multi-column FKs still require table recreation.\n */\n override generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n const { tableName, fk } = op;\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateAddForeignKey(op, context);\n }\n\n // Validate columns exist FIRST (before any array access)\n const fkColumn = fk.columns[0];\n const refColumn = fk.referencedColumns[0];\n if (!(fkColumn && refColumn)) {\n throw new Error(\n `Invalid foreign key: columns array is empty for table \"${tableName}\".`\n );\n }\n\n const currentTable = this.getCurrentTable(tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add foreign key: table \"${tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext.\"\n );\n }\n\n // Find the column to alter\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot add foreign key: column \"${fkColumn}\" not found in table \"${tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Build column definition with REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column, {\n refTable: fk.referencedTable,\n refCol: refColumn,\n onDelete: fk.onDelete,\n onUpdate: fk.onUpdate,\n });\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n /**\n * LibSQL can drop foreign keys by redefining the column without REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n */\n override generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop foreign key: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n // Find the FK to drop\n const fk = currentTable.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk) {\n throw new Error(\n `Cannot drop foreign key: constraint \"${op.fkName}\" not found in table \"${op.tableName}\".`\n );\n }\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateDropForeignKey(op, context);\n }\n\n const fkColumn = fk.columns[0];\n if (!fkColumn) {\n throw new Error(\n `Invalid foreign key: columns array is empty for constraint \"${op.fkName}\".`\n );\n }\n\n // Find the column\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot drop foreign key: column \"${fkColumn}\" not found in table \"${op.tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(op.tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Rebuild column definition WITHOUT REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column);\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n // ===========================================================================\n // PRIMARY KEY OPERATIONS\n // LibSQL still requires table recreation for PK changes\n // ===========================================================================\n\n // generateAddPrimaryKey and generateDropPrimaryKey inherit from SQLite3\n // which uses table recreation. LibSQL does not support native PK modifications.\n}\n\n// Export singleton instance\nexport const libsqlMigrationDriver = new LibSQLMigrationDriver();\n"],"mappings":"umBAoFA,MAAM,EAA0B,2CAK1B,EAAoB,SACpB,EAAe,sBACf,EAAc,qBACd,EAAY,sBACZ,EACJ,8EACI,EAAiB,kDACjB,EAAa,uCAEb,EAAgB,SAQhB,EACJ,kYACI,EAAe,gBACf,EAAgB,iBAChB,EAAgB,iBA4BtB,SAAS,eACP,EACA,EACmE,CACnE,IAAM,EAAa,IAAI,IACrB,EAAQ,IAAK,GAAQ,CAAC,EAAI,KAAK,aAAa,CAAE,EAAI,CAAC,CACpD,CACK,EAAc,IAAI,IAClB,EAAwD,EAAE,CAChE,IAAK,IAAM,KAAa,EAAS,CAC/B,IAAI,EAAO,EAAU,MAAM,CAEvB,EAAU,EAA2B,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,MAAU,MACR,mCAAmC,EAAS,wBAAwB,EAAU,IAC/E,CAcH,MAAO,eAXO,KAAK,iBAAiB,EAAU,CAWlB,gBAVhB,KAAK,iBAAiB,EAAS,CAUK,MAPjC,KAAK,6BAA6B,EAAQ,CACvD,SAAU,EAAG,gBACb,OAAQ,EACR,SAAU,EAAG,SACb,SAAU,EAAG,SACd,CAAC,GASJ,uBACE,EACA,EAC4B,CAC5B,IAAM,EAAe,KAAK,gBAAgB,EAAG,UAAW,EAAQ,CAChE,GAAI,CAAC,EACH,MAAU,MACR,mCAAmC,EAAG,UAAU,yFAEjD,CAIH,IAAM,EAAK,EAAa,YAAY,KAAM,GAAM,EAAE,OAAS,EAAG,OAAO,CACrE,GAAI,CAAC,EACH,MAAU,MACR,wCAAwC,EAAG,OAAO,wBAAwB,EAAG,UAAU,IACxF,CAIH,GAAI,EAAG,QAAQ,OAAS,EACtB,OAAO,MAAM,uBAAuB,EAAI,EAAQ,CAGlD,IAAM,EAAW,EAAG,QAAQ,GAC5B,GAAI,CAAC,EACH,MAAU,MACR,+DAA+D,EAAG,OAAO,IAC1E,CAIH,IAAM,EAAS,EAAa,QAAQ,KAAM,GAAM,EAAE,OAAS,EAAS,CACpE,GAAI,CAAC,EACH,MAAU,MACR,oCAAoC,EAAS,wBAAwB,EAAG,UAAU,IACnF,CASH,MAAO,eANO,KAAK,iBAAiB,EAAG,UAAU,CAMrB,gBALhB,KAAK,iBAAiB,EAAS,CAKK,MAFjC,KAAK,6BAA6B,EAAO,KAe5D,MAAa,EAAwB,IAAI"}
@@ -1,2 +0,0 @@
1
- const e=new WeakSet;export{e as t};
2
- //# sourceMappingURL=light-BkJe3-yW.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{t as n}from"./migrations-BMiRjR-N.mjs";import{Sn as r}from"./serializer-rBq3v1xr.mjs";import{n as i}from"./canonical-json-Bl-fKFF_.mjs";import{a,c as o}from"./identity-CtW15WlB.mjs";const isCorruption=e=>e instanceof n&&e.code===t.MIGRATION_CORRUPTION;function createStorageConformanceSuite(e){return[{name:`identical content-addressed publish is idempotent`,run:async()=>{let t=e(),n=o(`hello`),i=r(n),a=await t.publishSql(i,n),s=await t.publishSql(i,n);if(a.outcome!==`created`||s.outcome!==`identical`)throw Error(`idempotent publish failed`)}},{name:`same hash with different bytes is corruption`,run:async()=>{let t=e(),n=o(`hello`),i=r(n);await t.publishSql(i,n);try{await t.publishSql(i,o(`other`))}catch(e){if(isCorruption(e))return}throw Error(`corrupt publish was accepted`)}},{name:`listStates returns only committed manifests`,run:async()=>{if((await e().listStates()).length!==0)throw Error(`fresh writer is not empty`)}},{name:`estate publish is idempotent for identical bytes`,run:async()=>{let t=e(),n=o(`{"format":"1"}`),r=await t.publishEstate(n),i=await t.publishEstate(n);if(r.outcome!==`created`||i.outcome!==`identical`)throw Error(`estate idempotent publish failed`)}},{name:`concurrent identical creates report created exactly once`,run:async()=>{let t=e(),n=o(`race-identical`),i=r(n),a=(await Promise.all(Array.from({length:8},()=>t.publishState(i,n)))).filter(e=>e.outcome===`created`).length;if(a!==1)throw Error(`${a} of 8 concurrent creates won`)}},{name:`concurrent conflicting creates keep one winner and refuse the rest`,run:async()=>{let t=e(),n=r(o(`race-conflicting`)),a=Array.from({length:8},(e,t)=>o(`{"racer":${t}}`)),s=await Promise.allSettled(a.map(e=>t.publishState(n,e))),c=a.filter((e,t)=>s[t]?.status===`fulfilled`),l=s.filter(e=>e.status===`rejected`&&isCorruption(e.reason)).length,u=await t.readState(n);if(c.length!==1||l!==7||!(u&&i(u,c[0])))throw Error(`${c.length} winners and ${l} refusals of 8 conflicting creates`)}},{name:`absent artifacts read as null`,run:async()=>{let t=e(),n=r(o(`absent`));if((await Promise.all([t.readState(n),t.readSnapshot(n),t.readSql(n)])).some(e=>e!==null))throw Error(`an absent artifact read as bytes`)}},{name:`published artifacts are listed as soon as publish returns`,run:async()=>{let t=e(),n=Array.from({length:5},(e,t)=>o(`listed-${t}`)),i=n.map(r);for(let[e,r]of i.entries())await t.publishState(r,n[e]),await t.publishSnapshot(r,n[e]),await t.publishSql(r,n[e]);if((await Promise.all([t.listStates(),t.listSnapshots(),t.listSql()])).some(e=>i.some(t=>!e.includes(t))))throw Error(`a published artifact is missing from its listing`)}},{name:`a listed state's snapshot and SQL are already readable (manifest last)`,run:async()=>{let t=e(),n=o(`manifest-last`),i=r(n),a=!1,s=(async()=>{await t.publishSnapshot(i,n),await t.publishSql(i,n),await t.publishState(i,n)})().finally(()=>{a=!0});try{for(;;){let e=a;if((await t.listStates()).includes(i))break;if(e)throw Error(`a published state is not listed`)}let[e,n]=await Promise.all([t.readSnapshot(i),t.readSql(i)]);if(!(e&&n))throw Error(`a listed state's artifacts are not readable yet`)}finally{await s}}}]}var MemoryEstateStorage=class{estate=null;states=new Map;snapshots=new Map;sql=new Map;async readEstate(){return this.estate?this.estate.slice():null}async listStates(){return[...this.states.keys()].sort()}async listSnapshots(){return[...this.snapshots.keys()].sort()}async listSql(){return[...this.sql.keys()].sort()}async readState(e){let t=this.states.get(e);return t?t.slice():null}async readSnapshot(e){let t=this.snapshots.get(e);return t?t.slice():null}async readSql(e){let t=this.sql.get(e);return t?t.slice():null}async publishEstate(e){if(this.estate&&!i(this.estate,e))throw new n(`estate.json already exists with different bytes`,t.MIGRATION_CORRUPTION);return this.estate?{outcome:`identical`}:(this.estate=e.slice(),{outcome:`created`})}async publishSnapshot(e,t){return publishMap(this.snapshots,e,t,`snapshot`)}async publishSql(e,t){return publishMap(this.sql,e,t,`sql`)}async publishState(e,r){if(!a(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return publishMap(this.states,e,r,`state`)}};function publishMap(e,r,a,o){let s=e.get(r);if(s){if(!i(s,a))throw new n(`${o} ${r} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}return e.set(r,a.slice()),{outcome:`created`}}export{createStorageConformanceSuite as n,MemoryEstateStorage as t};
2
- //# sourceMappingURL=memory-G4cSuc6A.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{t,y as n}from"./base-z-cH5ZBI.mjs";import{p as r,t as i}from"./validation--qS7OPmg.mjs";import{t as a}from"./routed-operations-wytpbYKv.mjs";import{i as o,o as s}from"./value-guards-CBuxSC66.mjs";import{r as c}from"./extension-CGepsF-p.mjs";import{et as l}from"./native-types-DgjMUikz.mjs";import{i as u}from"./schema-BYA-_bpk.mjs";import{t as d}from"./raw-Dyq6Y6UX.mjs";function bindArguments(e,t,n,r){let i={...r};for(let[r,a]of Object.entries(n)){let n=e.find(e=>e.name===r&&e.extension===t&&e.bound===!0);n===void 0&&notBound(t,r),i[r]=n.admit(n,a)}return i}function notBound(e,t){return c(`Extension "${e}" binds argument "${t}", which it does not declare with bound(schema).`,e)}function argsOwnedBy(e,t){let n={};for(let r of t)e&&Object.hasOwn(e,r)&&(n[r]=e[r]);return n}const closedValues=e=>(t,n,r,i)=>{if(e.some(e=>e===n))return n;throw invalidArgument(t,r,i,[`must be one of ${e.map(e=>JSON.stringify(e)).join(`, `)}`])},checkedBy=e=>(n,r,i,a)=>{let o;try{o=e[`~standard`].validate(r)}catch(e){throw e instanceof t?e:validatorFailure(n,i,a,`threw`,e)}if(`then`in o)throw l(o),validatorFailure(n,i,a,`returned a promise`,TypeError(`Argument validators must return synchronously`));if(o.issues)throw invalidArgument(n,i,a,o.issues.map(e=>e.message));return o.value};function invalidArgument(e,t,n,r){return new i(n===void 0?{kind:`schema-builder`,builder:`$bind`,path:e.name}:{kind:`operation`,operation:n,model:t},r.map(t=>({path:e.name,message:`Argument "${e.name}" ${t}`})),{meta:{model:t,extension:e.extension}})}function validatorFailure(e,t,i,a,o){return new r(`Extension "${e.extension}" argument "${e.name}" validator for ${i===void 0?`$bind`:`${t}.${i}`} ${a}.`,{cause:n(o),meta:{model:t,operation:i}})}function appendArguments(e,t){let n=[...e?.all??[],...t],r=n.find(e=>e.bind)?.bind,i=new Set;for(let{name:e,extension:t}of n)i.has(e)&&c(`Extension "${t}" declares argument "${e}", which extension "${n.find(t=>t.name===e)?.extension}" already declares.`,t),i.add(e);let a=new Map,placed=(e,t)=>u(a,`${e}\u0000${t}`,()=>n.filter(({on:n,models:r})=>(n===void 0||n.includes(t))&&(r===void 0||r.includes(e))));return{names:i,all:n,placed,owned:argsOwnedBy,admit:(e,t,n,r,i)=>{let a=placed(e,t);if(a.length===0)return;if(typeof r!=`object`||!r)return{args:r,values:void 0};let o,s;for(let t of a){let{name:a,required:c}=t,l;t.bound!==!0&&Object.hasOwn(r,a)&&(l=r[a],s??={...r},delete s[a]);let u=l===void 0?i?.[a]??t.default:t.admit(t,l,e,n);if(u!==void 0)(o??={})[a]=u;else if(c===!0||c?.includes(e))throw invalidArgument(t,e,n,[`is required`])}return{args:s??r,values:o}},bind:r&&((...e)=>r(n,...e))}}const f=Object.freeze(Object.create(null)),p=Object.freeze({client:()=>f,model:()=>f,force:()=>void 0}),m=new Set([`$driver`,`$schema`,`$transaction`,`$connect`,`$disconnect`,`$extends`]);function addMethods(e,t,n,r,i,a=``){let s=Object.assign(Object.create(null),e);for(let[e,c]of t){let t=`${i} method "${a}${e}"`;o(c)||n(`${t} must be a function`),(Object.hasOwn(s,e)||r(e))&&n(`${t} collides with the existing ${i} surface`),s[e]=c}return Object.freeze(s)}const clientLayer=({prior:t,answer:n,refuse:r})=>{let i,a=e(()=>i??=addMethods(t.client(),Object.entries(n()),r,e=>m.has(e)||Object.hasOwn(d,e),`client`),`methods`);return{client:a,model:t.model,force:()=>{t.force(),a()}}},modelLayer=({prior:t,answer:n,scope:r,refuse:i})=>{let c=new Map,l=e(e=>{let l=c.get(e);if(l===void 0){let u=n()[e],d=Reflect.get(r(),e),f=o(u)?Reflect.apply(u,void 0,[d,r()]):u;f!==void 0&&!s(f)&&i(`methods.${e} must be an object of methods`),l=addMethods(t.model(e),Object.entries(f??{}).map(([e,t])=>[e,o(t)?(...e)=>Reflect.apply(t,d,e):t]),i,e=>e===`then`||e===`$rows`||a.has(e),`model`,`${e}.`),c.set(e,l)}return l},`methods`);return{client:t.client,model:l,force:()=>{t.force();for(let e of Object.keys(n()))l(e)}}};function methodsPart(e,t,n){return{join({next:r,name:i,schema:a}){let o=r.methods;r.methods={bind:r=>{let l=o?.bind(r)??p,refuse=e=>c(`Extension "${i}" ${e}.`,i),u,scopeOf=()=>u??=r(l,i),d;return t({prior:l,answer:()=>{if(d!==void 0)return d;let t=Reflect.apply(e,void 0,[scopeOf()]);s(t)||refuse(`methods factory must return an object`);for(let e of Object.keys(t)){let t=n(e,a);t&&refuse(`methods returned "${e}", ${t}`)}return d=t,t},scope:scopeOf,refuse})},bindNone:(e,t,n)=>{for(let n of Object.keys(t))notBound(e,n);return{...n}}}}}}function methods(e){return methodsPart(e,clientLayer,e=>e.startsWith(`$`)?void 0:`which is not a $ client method (a model's are written with modelMethods)`)}function modelMethods(e){return methodsPart(e,modelLayer,(e,t)=>Object.hasOwn(t,e)?void 0:`which is not a model`)}export{checkedBy as a,bindArguments as i,modelMethods as n,closedValues as o,appendArguments as r,methods as t};
2
- //# sourceMappingURL=methods-part-ZY0f2AV_.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"methods-part-ZY0f2AV_.mjs","names":["methods"],"sources":["../src/extensions/arguments.ts","../src/extensions/methods.ts","../src/extensions/methods-part.ts"],"sourcesContent":["/**\n * Arguments: what `args` declares, placed on a chain and admitted once per\n * call. Brought by `args` alone: an extension that declares no argument\n * carries none of it.\n */\n\nimport { QueryError, ValidationError, VibORMError } from \"@errors\";\nimport { memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { Operation } from \"@query-engine/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { discardAsyncValidationResult } from \"@validation/parse-failure\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { extensionError } from \"./chain\";\nimport type { ResolvedArgs } from \"./chain-state\";\n\ntype ArgLiteral = string | number | boolean;\n\n/**\n * One argument an extension declares. Its values are a closed list or a\n * Standard Schema, and `admit` is the code that checks one, brought by the\n * word that declared it (`oneOf`, or `accepts` and `bound`), so a chain of\n * closed arguments carries no Standard Schema admission. `on` names the\n * operations that accept it (every operation when absent), `models` the\n * models (every model when absent). With `required`, a call on one of those\n * operations that does not pass it is refused: on every model that accepts\n * it, or on the models it lists. With `bound`, it is accepted only from a\n * binding (the client scope's `$bind`, which `bind` runs), never from a\n * call's arguments, so a call that passes it is refused as passing an\n * unknown key. With `volatile`, a call that holds a value of it has no key\n * (`key(run)`): a read that holds one is never served from a store nor kept\n * in one.\n */\nexport interface ArgDeclaration {\n /** A closed argument's values; absent for a Standard Schema's. */\n readonly oneOf?: readonly ArgLiteral[];\n readonly admit: AdmitValue;\n readonly on?: readonly string[];\n readonly models?: readonly string[];\n readonly required?: true | readonly string[];\n /** The value a call that passes none reads. */\n readonly default?: ArgLiteral;\n readonly bound?: boolean;\n readonly bind?: typeof bindArguments;\n readonly volatile?: boolean;\n}\n\n/** One value admitted for a call's (model, operation), or, without them, a binding. */\ntype AdmitValue = (\n argument: ResolvedArg,\n value: unknown,\n model?: string,\n operation?: Operation\n) => unknown;\n\n/**\n * One argument of a chain: its declaration as written, its name and the\n * extension that declares it. Its declaration alone places it: no other part\n * moves it.\n */\nexport type ResolvedArg = ArgDeclaration & {\n readonly name: string;\n readonly extension: string;\n};\n\n/** The arguments one call admitted, by name; one it did not pass is absent. */\nexport type AdmittedArgs = Readonly<Record<string, unknown>>;\n\nexport interface ArgAdmission {\n /** The call's arguments without the chain's; the input itself when it passed none. */\n readonly args: Record<string, unknown>;\n /** `undefined` when the call admitted no value. */\n readonly values: AdmittedArgs | undefined;\n}\n\n/**\n * The values a view binds after one extension binds its own arguments: each\n * admitted once, over the values the view already binds, a value replacing\n * an earlier one. Brought by `bound`: only a `bound` argument is bound.\n */\nexport function bindArguments(\n all: readonly ResolvedArg[],\n extension: string,\n values: Readonly<Record<string, unknown>>,\n previous: AdmittedArgs | undefined\n): AdmittedArgs {\n const next: Record<string, unknown> = { ...previous };\n for (const [name, raw] of Object.entries(values)) {\n const argument = all.find(\n (candidate) =>\n candidate.name === name &&\n candidate.extension === extension &&\n candidate.bound === true\n );\n if (argument === undefined) notBound(extension, name);\n next[name] = argument.admit(argument, raw);\n }\n return next;\n}\n\n/** The refusal of a `$bind` naming an argument its extension does not declare `bound`. */\nexport function notBound(extension: string, name: string): never {\n return extensionError(\n `Extension \"${extension}\" binds argument \"${name}\", which it does not declare with bound(schema).`,\n extension\n );\n}\n\n/** One extension's own admitted arguments, as its parts see them (`c.values`). */\nfunction argsOwnedBy(\n admitted: AdmittedArgs | undefined,\n names: readonly string[]\n): AdmittedArgs {\n const owned: Record<string, unknown> = {};\n for (const name of names)\n if (admitted && Object.hasOwn(admitted, name)) owned[name] = admitted[name];\n return owned;\n}\n\n/** What admits a value of one of `values`, brought by `oneOf`. */\nexport const closedValues =\n (values: readonly ArgLiteral[]): AdmitValue =>\n (argument, value, model, operation) => {\n if (values.some((allowed) => allowed === value)) return value;\n throw invalidArgument(argument, model, operation, [\n `must be one of ${values.map((allowed) => JSON.stringify(allowed)).join(\", \")}`,\n ]);\n };\n\n/** What admits a value `schema` checks, brought by `accepts` and `bound`. */\nexport const checkedBy =\n (schema: StandardSchemaV1): AdmitValue =>\n (argument, value, model, operation) => {\n let result: ReturnType<StandardSchemaV1[\"~standard\"][\"validate\"]>;\n try {\n result = schema[\"~standard\"].validate(value);\n } catch (cause) {\n // A validator may own its typed failure; anything else is a failure of\n // extension code, as a throwing first moment is.\n if (cause instanceof VibORMError) throw cause;\n throw validatorFailure(argument, model, operation, \"threw\", cause);\n }\n if (\"then\" in result) {\n // The refused promise is still live; without a handler its rejection\n // would surface as an unhandled rejection (D-37).\n discardAsyncValidationResult(result);\n throw validatorFailure(\n argument,\n model,\n operation,\n \"returned a promise\",\n new TypeError(\"Argument validators must return synchronously\")\n );\n }\n if (result.issues)\n throw invalidArgument(\n argument,\n model,\n operation,\n result.issues.map((issue) => issue.message)\n );\n return result.value;\n };\n\nfunction invalidArgument(\n argument: ResolvedArg,\n model: string | undefined,\n operation: Operation | undefined,\n messages: readonly string[]\n): ValidationError {\n return new ValidationError(\n operation === undefined\n ? { kind: \"schema-builder\", builder: \"$bind\", path: argument.name }\n : { kind: \"operation\", operation, model },\n messages.map((message) => ({\n path: argument.name,\n message: `Argument \"${argument.name}\" ${message}`,\n })),\n { meta: { model, extension: argument.extension } }\n );\n}\n\nfunction validatorFailure(\n argument: ResolvedArg,\n model: string | undefined,\n operation: Operation | undefined,\n failure: string,\n cause: unknown\n): QueryError {\n return new QueryError(\n `Extension \"${argument.extension}\" argument \"${argument.name}\" validator for ${operation === undefined ? \"$bind\" : `${model}.${operation}`} ${failure}.`,\n { cause: errorCause(cause), meta: { model, operation } }\n );\n}\n\n/**\n * The chain's arguments with one extension's added, each (model, operation)\n * listing the ones it accepts the first time a call asks. One name, one\n * argument: a call's value is read once and admitted against one\n * declaration, so a second declaration of a name would refuse every call\n * that passes either value, and a binding would answer for both.\n */\nexport function appendArguments(\n previous: ResolvedArgs | undefined,\n declared: readonly ResolvedArg[]\n): ResolvedArgs {\n const all = [...(previous?.all ?? []), ...declared];\n const binder = all.find((argument) => argument.bind)?.bind;\n const names = new Set<string>();\n for (const { name, extension } of all) {\n if (names.has(name))\n extensionError(\n `Extension \"${extension}\" declares argument \"${name}\", which extension \"${all.find((argument) => argument.name === name)?.extension}\" already declares.`,\n extension\n );\n names.add(name);\n }\n const lists = new Map<string, readonly ResolvedArg[]>();\n const placed = (model: string, operation: string): readonly ResolvedArg[] => {\n const key = `${model}\\u0000${operation}`;\n return memo(lists, key, () =>\n all.filter(\n ({ on, models }) =>\n (on === undefined || on.includes(operation)) &&\n (models === undefined || models.includes(model))\n )\n );\n };\n return {\n names,\n all,\n placed,\n owned: argsOwnedBy,\n /**\n * Take every argument placed on this operation out of the call's\n * arguments and admit each once, before any first moment runs. A key\n * naming an argument placed elsewhere, or a bound one, stays in the\n * arguments, where core validation refuses it as an unknown key. An\n * argument the call did not pass takes the value its view binds, else\n * its default; without either it is refused where it is required.\n */\n admit: (\n model: string,\n placement: string,\n operation: Operation,\n input: Record<string, unknown>,\n bound: AdmittedArgs | undefined\n ): ArgAdmission | undefined => {\n const list = placed(model, placement);\n if (list.length === 0) return undefined;\n // Arguments that are not an object hold no extension argument: core\n // validation refuses them as it does on a client without extensions.\n if (typeof input !== \"object\" || input === null) {\n return { args: input, values: undefined };\n }\n let values: Record<string, unknown> | undefined;\n let args: Record<string, unknown> | undefined;\n for (const argument of list) {\n const { name, required } = argument;\n let raw: unknown;\n if (argument.bound !== true && Object.hasOwn(input, name)) {\n raw = input[name];\n args ??= { ...input };\n delete args[name];\n }\n // A bound value was admitted once, when its view was bound.\n const value =\n raw === undefined\n ? (bound?.[name] ?? argument.default)\n : argument.admit(argument, raw, model, operation);\n if (value !== undefined) (values ??= {})[name] = value;\n else if (required === true || required?.includes(model)) {\n throw invalidArgument(argument, model, operation, [\"is required\"]);\n }\n }\n return { args: args ?? input, values };\n },\n // Brought by `bound`: a chain that declares no bound argument binds none.\n bind: binder && ((...binding) => binder(all, ...binding)),\n };\n}\n","import type { TransactionClient, VibORMConfig } from \"@client/client\";\nimport {\n RAW_METHOD_NAMES,\n type RawSurface,\n type RowsFragment,\n} from \"@client/raw\";\nimport type { ClientSchema } from \"@client/schema-links\";\nimport type {\n Client,\n ClientRowsContext,\n ComputedOperation,\n ComputedOperations,\n Schema,\n StampedOperation,\n StampedOperations,\n} from \"@client/types\";\nimport type { ModelSql } from \"@query-engine/raptor3/shared/insert-value\";\nimport { ROUTED_OPERATIONS } from \"@query-engine/routed-operations\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { type AdmittedArgs, notBound } from \"./arguments\";\nimport type { ExtensionPart } from \"./chain\";\nimport { extensionError } from \"./chain\";\nimport type { NoArguments } from \"./contract\";\nimport type { MergeResultFields } from \"./result-types\";\n\ntype NoMethods = Record<never, never>;\ntype RuntimeExtensionMethodFunction = (...args: never[]) => unknown;\n\ndeclare const extensionResultConsumerState: unique symbol;\nexport interface ExtensionResultConsumerState {\n readonly [extensionResultConsumerState]: true;\n}\n\n/** The only static facts accumulated while extensions are chained. */\nexport interface ClientExtensionState<\n ClientMethods extends object = NoMethods,\n ModelMethods extends object = NoMethods,\n ResultConsumerState extends\n | ExtensionResultConsumerState\n | undefined = undefined,\n Arguments extends object = NoArguments,\n Filtered extends string = never,\n Defaults = never,\n Fields extends object = Record<never, never>,\n> {\n readonly client: ClientMethods;\n readonly models: ModelMethods;\n readonly resultConsumer: ResultConsumerState;\n /** The arguments the chain declares: each one's values and placement. */\n readonly args: Arguments;\n /** The models whose rows the chain's rules filter: a relation read can find none. */\n readonly filtered: Filtered;\n /** The fields the chain's `defaults` write on a create, which a caller no longer writes. */\n readonly defaults: Defaults;\n /** The fields the chain's `fields` compute, per model key, and their types. */\n readonly fields: Fields;\n}\n\nexport type EmptyClientExtensionState = ClientExtensionState;\n\n/** What every extension state is: the widest of each fact. */\nexport type ExtensionStateConstraint = ClientExtensionState<\n object,\n object,\n ExtensionResultConsumerState | undefined,\n object,\n string,\n unknown,\n object\n>;\n\n/** Whether an earlier extension was typed against result-bearing delegates. */\ntype HasResultConsumingExtension<X extends ExtensionStateConstraint> = [\n X[\"resultConsumer\"],\n] extends [undefined]\n ? false\n : [X[\"resultConsumer\"]] extends [ExtensionResultConsumerState]\n ? true\n : false;\n\ndeclare const delegateState: unique symbol;\n/**\n * Declaration-only: what a result read on a delegate of a chain that adds\n * model methods depends on (its client's config, the models the chain's\n * rules filter, its computed fields, the model), so a method typed with a\n * `this` parameter reads its result from the client it is called on\n * (`DelegateOperationResult`), whatever the chain added after it. Nothing\n * else of the extension state: a later step that changes none of these (the\n * cache) keeps the client assignable to the one before it. No property is\n * installed at runtime.\n */\nexport interface DelegateState<C, Rows, Result, ModelName> {\n readonly [delegateState]?: readonly [C, Rows, Result, ModelName];\n}\n\ntype MethodsForModel<\n X extends ExtensionStateConstraint,\n ModelName extends PropertyKey,\n> = ModelName extends keyof X[\"models\"] ? X[\"models\"][ModelName] : NoMethods;\n\n/**\n * The link, on every delegate of a chain that adds model methods: decided by\n * the extension state alone, so a client generic over its schema without\n * them (the empty state) compares as before.\n */\ntype DelegateLink<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n ModelName extends PropertyKey,\n> = [keyof X[\"models\"]] extends [never]\n ? unknown\n : DelegateState<C, X[\"filtered\"], X[\"fields\"], ModelName>;\n\n/**\n * One model's delegate after the chain's methods and arguments. On a chain\n * that writes `defaults` on a create, its writes may leave out the fields the chain\n * writes on a create.\n */\nexport type ExtensionModelDelegate<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n ModelName extends keyof ClientSchema<C>,\n> = ([X[\"defaults\"]] extends [never]\n ? Client<C, ClientRowsContext<C, X[\"filtered\"]>, X[\"args\"]>[ModelName]\n : Omit<\n Client<C, ClientRowsContext<C, X[\"filtered\"]>, X[\"args\"]>[ModelName],\n StampedOperation\n > &\n StampedOperations<\n C,\n ClientRowsContext<C, X[\"filtered\"]>,\n X[\"args\"],\n X[\"defaults\"],\n ModelName\n >) &\n MethodsForModel<X, ModelName> &\n DelegateLink<C, X, ModelName> &\n ModelRows;\n\n/** The core member every model delegate has beside its operations. */\ninterface ModelRows {\n /**\n * The rows of this model this client may read, as a `FROM` item of a\n * tagged `$queryRaw` named `alias`: a derived table filtered by the row\n * domain a `findMany` of this model on this client takes (permissions,\n * soft delete, bound arguments). Refused anywhere else.\n *\n * @example\n * ```ts\n * await db.$as(actor).$queryRaw`\n * SELECT p.id FROM ${db.$as(actor).page.$rows(\"p\")} WHERE p.title LIKE ${q}\n * `;\n * ```\n */\n $rows(alias: string): RowsFragment;\n /**\n * This model's names and values as this client's statements spell them:\n * its table, its columns, a value bound as one of its fields, and the rows\n * a call may see as a condition. For a fragment you write by hand and hand\n * to a model operation (a `computed` value, a filter's expression).\n */\n readonly $sql: ModelSql;\n}\n\n/**\n * One model's delegate on a chain that declares `fields`: its projecting\n * operations rebuilt so `select` and `omit` name the computed fields and the\n * rows carry them. A chain without `fields` never reaches this type.\n */\ntype ComputedModelDelegate<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n ModelName extends keyof ClientSchema<C>,\n> = Omit<ExtensionModelDelegate<C, X, ModelName>, ComputedOperation> &\n ComputedOperations<\n C,\n ClientRowsContext<C, X[\"filtered\"]>,\n X[\"args\"],\n X[\"defaults\"],\n ModelName,\n X[\"fields\"]\n >;\n\n/**\n * Model delegates after the methods contributed by the current chain. The\n * always-true test is deliberate: for a client generic over its config it\n * stays deferred, so the model map adds no index signature to that client and\n * its `$` members stay reachable inside a body generic over `C`. A chain\n * that declares `fields` is told apart here, once per client.\n */\nexport type ExtensionModelClient<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = [keyof C[\"schema\"]] extends [PropertyKey]\n ? [keyof X[\"fields\"]] extends [never]\n ? {\n [ModelName in keyof ClientSchema<C>]: ExtensionModelDelegate<\n C,\n X,\n ModelName\n >;\n }\n : {\n [ModelName in keyof ClientSchema<C>]: ComputedModelDelegate<\n C,\n X,\n ModelName\n >;\n }\n : unknown;\n\n/** The surface given to one client-method factory. */\nexport type ExtensionClientScope<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = ExtensionModelClient<C, X> &\n RawSurface &\n X[\"client\"] & {\n readonly $schema: ClientSchema<C>;\n readonly $transaction: TransactionClient<C, X>[\"$transaction\"];\n /**\n * The client this scope's methods are called on, its calls admitting\n * these values of this extension's own arguments as if passed (a\n * `bound: true` argument only from here). Its type is that client's,\n * which only the method knows: declare it with a `this` parameter,\n * `$with<Self>(this: Self, value: Value): Self`, outside the returned\n * literal (inside it, the factory's contextual type makes `Self` void).\n */\n readonly $bind: (values: Readonly<Record<string, unknown>>) => unknown;\n };\n\nexport type MergeModelMethods<Left extends object, Right extends object> = {\n readonly [ModelName in\n | keyof Left\n | keyof Right]: (ModelName extends keyof Left\n ? Left[ModelName]\n : NoMethods) &\n (ModelName extends keyof Right ? Right[ModelName] : NoMethods);\n};\n\n/** Incoming facts keep their nominal bit derivation inside this named state. */\nexport interface AddedExtensionState<\n ClientMethods extends object,\n ModelMethods extends object,\n Arguments extends object,\n Filtered extends string,\n Defaults,\n ConsumerContext extends string,\n // Defaulted: 1.3.3 exported this state with six parameters.\n Fields extends object = Record<never, never>,\n> extends ExtensionStateConstraint {\n readonly client: ClientMethods;\n readonly models: ModelMethods;\n readonly resultConsumer: ConsumerContext extends \"result-consuming\"\n ? ExtensionResultConsumerState\n : undefined;\n readonly args: Arguments;\n readonly filtered: Filtered;\n readonly defaults: Defaults;\n readonly fields: Fields;\n}\n\n/** Accumulate the same seven facts lazily, without retaining callback definitions. */\nexport interface ChainedExtensionState<\n X extends ExtensionStateConstraint,\n Added extends ExtensionStateConstraint,\n> extends ExtensionStateConstraint {\n readonly client: X[\"client\"] & Added[\"client\"];\n readonly models: MergeModelMethods<X[\"models\"], Added[\"models\"]>;\n readonly resultConsumer: HasResultConsumingExtension<Added> extends true\n ? ExtensionResultConsumerState\n : X[\"resultConsumer\"];\n readonly args: X[\"args\"] & Added[\"args\"];\n readonly filtered: X[\"filtered\"] | Added[\"filtered\"];\n readonly defaults: X[\"defaults\"] | Added[\"defaults\"];\n readonly fields: MergeResultFields<X[\"fields\"], Added[\"fields\"]>;\n}\n\ntype MethodRecord = Readonly<Record<string, RuntimeExtensionMethodFunction>>;\n\n/**\n * The methods a view answers after some prefix of its chain: its client\n * methods, and one model's. Each is computed the first time it is read.\n */\nexport interface ExtensionMethods {\n readonly client: () => MethodRecord;\n readonly model: (model: string) => MethodRecord;\n}\n\n/** A view's methods, and what invokes every factory of its chain in order. */\ntype BoundExtensionMethods = ExtensionMethods & {\n readonly force: () => void;\n};\n\nconst NO_METHODS: MethodRecord = /* @__PURE__ */ Object.freeze(\n Object.create(null)\n);\nconst NO_LAYER: BoundExtensionMethods = /* @__PURE__ */ Object.freeze({\n client: () => NO_METHODS,\n model: () => NO_METHODS,\n force: () => undefined,\n});\n\nconst CORE_CLIENT_METHODS = new Set([\n \"$driver\",\n \"$schema\",\n \"$transaction\",\n \"$connect\",\n \"$disconnect\",\n \"$extends\",\n]);\n\n/**\n * The methods before one extension with its own added, each a function and\n * each name (`at` the model's, for a model method) checked against what the\n * view already answers.\n */\nfunction addMethods(\n previous: MethodRecord,\n added: readonly (readonly [string, unknown])[],\n refuse: (problem: string) => never,\n collides: (name: string) => boolean,\n surface: \"client\" | \"model\",\n at = \"\"\n): MethodRecord {\n const methods: Record<string, RuntimeExtensionMethodFunction> = Object.assign(\n Object.create(null),\n previous\n );\n for (const [name, method] of added) {\n const label = `${surface} method \"${at}${name}\"`;\n if (!isFunction(method)) refuse(`${label} must be a function`);\n if (Object.hasOwn(methods, name) || collides(name))\n refuse(`${label} collides with the existing ${surface} surface`);\n methods[name] = method;\n }\n return Object.freeze(methods);\n}\n\n/**\n * What one factory's methods add to a view, given the view's methods before\n * it: brought by the builder (`methods` its client methods, `modelMethods`\n * its model methods), so an extension carries only the half it writes. Its\n * `force` forces the view before it first.\n */\ntype MethodsLayer = (made: {\n readonly prior: BoundExtensionMethods;\n /** The factory's answer, once per view, each key checked by `owns`. */\n readonly answer: () => Readonly<Record<string, unknown>>;\n readonly scope: () => object;\n readonly refuse: (problem: string) => never;\n}) => BoundExtensionMethods;\n\n/** `methods`' half: the `$` client methods its factory returns. */\nexport const clientLayer: MethodsLayer = ({ prior, answer, refuse }) => {\n let client: MethodRecord | undefined;\n const methods = () =>\n (client ??= addMethods(\n prior.client(),\n Object.entries(answer()),\n refuse,\n (method) =>\n CORE_CLIENT_METHODS.has(method) ||\n Object.hasOwn(RAW_METHOD_NAMES, method),\n \"client\"\n ));\n return {\n client: methods,\n model: prior.model,\n force: () => {\n prior.force();\n methods();\n },\n };\n};\n\n/**\n * `modelMethods`' half: each model's methods, made the first time the model\n * is read on a view; a model's entry may be a function of its delegate and\n * the scope, and a model method is called with `this` equal to its delegate.\n */\nexport const modelLayer: MethodsLayer = ({ prior, answer, scope, refuse }) => {\n const models = new Map<string, MethodRecord>();\n const methods = (model: string) => {\n let made = models.get(model);\n if (made === undefined) {\n const given = answer()[model];\n const delegate: unknown = Reflect.get(scope(), model);\n const own: unknown = isFunction(given)\n ? Reflect.apply(given, undefined, [delegate, scope()])\n : given;\n if (own !== undefined && !isRecord(own))\n refuse(`methods.${model} must be an object of methods`);\n made = addMethods(\n prior.model(model),\n Object.entries(own ?? {}).map(([method, fn]) => [\n method,\n isFunction(fn)\n ? (...args: unknown[]) => Reflect.apply(fn, delegate, args)\n : fn,\n ]),\n refuse,\n (method) =>\n method === \"then\" ||\n method === \"$rows\" ||\n ROUTED_OPERATIONS.has(method),\n \"model\",\n `${model}.`\n );\n models.set(model, made);\n }\n return made;\n };\n return {\n client: prior.client,\n model: methods,\n force: () => {\n prior.force();\n for (const key of Object.keys(answer())) methods(key);\n },\n };\n};\n\n/** A `methods` factory as its part keeps it. */\ntype RuntimeMethodsFactory = (scope: never) => unknown;\n\n/** A chain's methods, and what binds one view's methods. */\nexport interface ExtensionMethodsState {\n readonly bind: (\n createScope: (prior: ExtensionMethods, extension: string) => object\n ) => BoundExtensionMethods;\n /**\n * A factory scope's `$bind` on a chain that declares no `bound` argument:\n * it binds nothing, and refuses any argument it is asked to.\n */\n readonly bindNone: (\n extension: string,\n values: Readonly<Record<string, unknown>>,\n previous: AdmittedArgs | undefined\n ) => AdmittedArgs;\n}\n\n/**\n * A methods part: what a view answers, in chain order. `owns` (which keys\n * the factory may return: why not, else `undefined`) and `layer` (what its\n * methods add to a view) are its builder's half (`methods-part.ts`).\n *\n * A view's methods are this part's layer over the view the chain's methods\n * before it bind. The factory is invoked against the scope `createScope`\n * builds over those, the first time a method it returns could be read: a\n * view costs the factories it uses. `force` invokes every factory in chain\n * order, where a root view surfaces an extension's faults.\n */\nexport function methodsPart(\n factory: RuntimeMethodsFactory,\n layer: MethodsLayer,\n owns: (key: string, schema: Schema) => string | undefined\n): ExtensionPart {\n return {\n join({ next, name, schema }) {\n const before = next.methods;\n next.methods = {\n bind: (createScope) => {\n const prior = before?.bind(createScope) ?? NO_LAYER;\n // Typed where it is declared, so a call to it ends the argument flow.\n const refuse: (problem: string) => never = (problem) =>\n extensionError(`Extension \"${name}\" ${problem}.`, name);\n let scope: object | undefined;\n const scopeOf = () => (scope ??= createScope(prior, name));\n let returned: Readonly<Record<string, unknown>> | undefined;\n return layer({\n prior,\n // The factory's answer, once per view: the methods come from it.\n answer: () => {\n if (returned !== undefined) return returned;\n const value: unknown = Reflect.apply(factory, undefined, [\n scopeOf(),\n ]);\n if (!isRecord(value))\n refuse(\"methods factory must return an object\");\n for (const key of Object.keys(value)) {\n const problem = owns(key, schema);\n if (problem) refuse(`methods returned \"${key}\", ${problem}`);\n }\n returned = value;\n return value;\n },\n scope: scopeOf,\n refuse,\n });\n },\n bindNone: (extension, values, previous) => {\n for (const key of Object.keys(values)) notBound(extension, key);\n return { ...previous };\n },\n };\n },\n };\n}\n","/**\n * `methods((scope) => ({ $name: fn }))`: functions added to the client, and\n * `modelMethods((scope) => ({ model: { name: fn } }))`: functions added to\n * the models. Each factory runs once per view it serves, the first time one\n * of its methods is read; a model method is called with `this` equal to the\n * delegate it is read from. Two builders, each bringing its own half of the\n * methods host (`methods.ts`): an extension that adds client methods only\n * carries no model-method code, and the reverse.\n */\nimport type {\n AnyTarget,\n ConsumesResults,\n MethodsCheck,\n MethodsFacts,\n MethodsScope,\n ModelName,\n Part,\n} from \"./contract\";\nimport { clientLayer, methodsPart, modelLayer } from \"./methods\";\n\n/** Functions added to the client of the extension's chain: `$` names. */\nexport function methods<\n T extends AnyTarget,\n F extends (\n scope: MethodsScope<T>\n ) => MethodsCheck<ReturnType<F>, T, \"client\"> = (\n scope: MethodsScope<T>\n ) => object,\n>(factory: F): Part<T, MethodsFacts<ReturnType<F>, ConsumesResults<F>, never>>;\nexport function methods(factory: (scope: never) => unknown): unknown {\n return methodsPart(factory, clientLayer, (key) =>\n key.startsWith(\"$\")\n ? undefined\n : \"which is not a $ client method (a model's are written with modelMethods)\"\n );\n}\n\n/** Functions added to the models of the extension's chain, by model. */\nexport function modelMethods<\n T extends AnyTarget,\n F extends (\n scope: MethodsScope<T>\n ) => MethodsCheck<ReturnType<F>, T, \"model\"> = (\n scope: MethodsScope<T>\n ) => object,\n>(\n factory: F\n): Part<T, MethodsFacts<ReturnType<F>, ConsumesResults<F>, ModelName<T>>>;\nexport function modelMethods(factory: (scope: never) => unknown): unknown {\n return methodsPart(factory, modelLayer, (key, schema) =>\n Object.hasOwn(schema, key) ? undefined : \"which is not a model\"\n );\n}\n"],"mappings":"maA+EA,SAAgB,cACd,EACA,EACA,EACA,EACc,CACd,IAAM,EAAgC,CAAE,GAAG,EAAU,CACrD,IAAK,GAAM,CAAC,EAAM,KAAQ,OAAO,QAAQ,EAAO,CAAE,CAChD,IAAM,EAAW,EAAI,KAClB,GACC,EAAU,OAAS,GACnB,EAAU,YAAc,GACxB,EAAU,QAAU,GACvB,CACG,IAAa,IAAA,IAAW,SAAS,EAAW,EAAK,CACrD,EAAK,GAAQ,EAAS,MAAM,EAAU,EAAI,CAE5C,OAAO,EAIT,SAAgB,SAAS,EAAmB,EAAqB,CAC/D,OAAO,EACL,cAAc,EAAU,oBAAoB,EAAK,kDACjD,EACD,CAIH,SAAS,YACP,EACA,EACc,CACd,IAAM,EAAiC,EAAE,CACzC,IAAK,IAAM,KAAQ,EACb,GAAY,OAAO,OAAO,EAAU,EAAK,GAAE,EAAM,GAAQ,EAAS,IACxE,OAAO,EAIT,MAAa,aACV,IACA,EAAU,EAAO,EAAO,IAAc,CACrC,GAAI,EAAO,KAAM,GAAY,IAAY,EAAM,CAAE,OAAO,EACxD,MAAM,gBAAgB,EAAU,EAAO,EAAW,CAChD,kBAAkB,EAAO,IAAK,GAAY,KAAK,UAAU,EAAQ,CAAC,CAAC,KAAK,KAAK,GAC9E,CAAC,EAIO,UACV,I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AAc,GACxC,EAAI,WAAW,IAAI,CACf,IAAA,GACA,2EACL,CAcH,SAAgB,aAAa,EAA6C,CACxE,OAAO,YAAY,EAAS,YAAa,EAAK,IAC5C,OAAO,OAAO,EAAQ,EAAI,CAAG,IAAA,GAAY,uBAC1C"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,t as n,u as r}from"./base-z-cH5ZBI.mjs";var MigrationError=class extends n{static diagnosticName=`MigrationError`;constructor(e,n=t.MIGRATION_FAILED,i){let a=i?.cause;super(e,n,{...i,diagnostics:a?r(a):void 0})}};function isMigrationError(e){return e instanceof MigrationError}export{isMigrationError as n,MigrationError as t};
2
- //# sourceMappingURL=migrations-BMiRjR-N.mjs.map
@@ -1,100 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{t as n}from"./migrations-BMiRjR-N.mjs";import{R as r,j as i,o as a}from"./native-types-DgjMUikz.mjs";import{a as o}from"./physical-CeE2nYmI.mjs";import{r as s}from"./datetime-physical-codec-Dj-APo9f.mjs";import{r as c}from"./identifiers-s00pGES8.mjs";import{$n as l,An as u,Gn as d,Gt as f,Mn as p,On as m,Qn as h,Wn as g,Xn as _,Zn as v,ar as y,c as b,er as x,ir as S,jn as C,kn as w,l as T,lr as E,nr as D,or as O,qn as k,rr as A,s as j,sr as M,tr as N}from"./serializer-rBq3v1xr.mjs";import{r as P}from"./identity-CtW15WlB.mjs";import{t as F}from"./sql-Dl6nykFV.mjs";const namespaceMeta=e=>({dialect:`mysql`,namespace:e});async function resolveCatalogNamespace(e,r){if(r===void 0)throw new n(`This MySQL client's adapter declares no database, so there is no catalog to read. MySQL migration artifacts are database-relative on purpose: supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});let{rows:i}=await e(`
2
- SELECT SCHEMA_NAME
3
- FROM information_schema.SCHEMATA
4
- WHERE LOWER(SCHEMA_NAME) = LOWER(?)
5
- ORDER BY SCHEMA_NAME
6
- `,[r]),a=i.map(e=>e.SCHEMA_NAME).filter(e=>typeof e==`string`);if(a.length===0)throw new n(`The MySQL database "${r}" does not exist or is not visible to this connection. VibORM never creates or drops a database: create it, or grant this user access to it, before running migration work against it.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`missing-database`}});let o=a.find(e=>e===r);if(o!==void 0)return o;let[s]=a;if(a.length===1&&s!==void 0)return s;throw new n(`The MySQL database "${r}" matches ${a.length} existing databases that differ only by case (${a.join(`, `)}). Configure the exact name this server reports so migration work cannot land in the wrong one.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`ambiguous-database`,candidates:a}})}const I=/^viborm_decimal_([sl])_(\d+)_(\d+)$/,L=/^_[a-zA-Z0-9]+(?=')/,R=/\s/;function refuseReservedConstraint(e,r,i){throw new n(`The MySQL CHECK constraint "${e}" on table "${r}" uses VibORM's reserved decimal-conversion namespace but ${i}. Migration work is refused before any cleanup or schema effect; rename the user-owned constraint, or restore the exact interrupted VibORM conversion proof and run the command again.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`decimal-conversion-constraint-collision`,table:r,constraint:e}})}function readString(e,t,n,r){if(typeof e==`string`)return e;refuseReservedConstraint(t,n,`its catalog ${r} is not a string`)}function normalizeCheckClause(e){let t=e.replaceAll(`\\'`,`'`),n=``,r=0;for(;r<t.length;){let i=t[r];if(i===`'`){let e=r;for(r++;r<t.length;){if(t[r]===`\\`&&r+1<t.length){r+=2;continue}if(t[r]===`'`&&t[r+1]===`'`){r+=2;continue}if(t[r]===`'`){r++;break}r++}n+=t.slice(e,r);continue}if(i==="`"){let i=t.indexOf("`",r+1);if(i<0)return e;n+=t.slice(r,i+1),r=i+1;continue}if(R.test(i??``)){r++;continue}if(i===`_`){let e=L.exec(t.slice(r));if(e!==null){r+=e[0].length;continue}}n+=i?.toLowerCase()??``,r++}return n}function expectedConstraint(e,t,n){let r=`\`${e.name}\``;return t===`s`?D(r,`DECIMAL(${n.precision},${n.scale})`):S(r,n)}function readDescriptor(e,t,n){let i=r(e[2],e[3],`mysql`);return i===void 0&&refuseReservedConstraint(t,n,`its name declares a decimal domain this provider does not admit`),l(e[1]===`s`?`scalar`:`list`,i)!==t&&refuseReservedConstraint(t,n,`its name is not the canonical spelling of its decimal proof`),i}function proveConstraint(e,t){let n=typeof e.CONSTRAINT_NAME==`string`?e.CONSTRAINT_NAME:`<unreported>`,r=typeof e.TABLE_NAME==`string`?e.TABLE_NAME:`<unreported>`,i=readString(e.CONSTRAINT_NAME,n,r,`CONSTRAINT_NAME`),a=readString(e.TABLE_NAME,i,r,`TABLE_NAME`),o=readString(e.CHECK_CLAUSE,i,a,`CHECK_CLAUSE`);readString(e.ENFORCED,i,a,`ENFORCED`)!==`YES`&&refuseReservedConstraint(i,a,`its CHECK is not enforced`);let s=I.exec(i);s===null&&refuseReservedConstraint(i,a,`its name does not match the complete reserved proof identity`);let c=s[1]===`s`?`s`:`l`,l=readDescriptor(s,i,a),u=t.get(a)??[],d=normalizeCheckClause(o);for(let e of u){if(normalizeCheckClause(expectedConstraint(e,c,l))!==d)continue;if(c===`s`){if(e.dataType===`decimal`||e.dataType===`int`||e.dataType===`bigint`)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its scalar proof is attached to impossible ${e.dataType} storage`)}e.dataType!==`json`&&refuseReservedConstraint(i,a,`its list proof is attached to impossible ${e.dataType} storage`);let t;try{t=E(e.comment)}catch{refuseReservedConstraint(i,a,`its JSON column carries an invalid decimal-list marker`)}if(t!==void 0&&t.scale===l.scale&&t.precision>=l.precision)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its JSON column does not carry a compatible source or target decimal-list marker`)}refuseReservedConstraint(i,a,`its concrete CHECK predicate does not match that proof identity`)}function groupColumns(e){let t=new Map;for(let n of e){let e=typeof n.TABLE_NAME==`string`?n.TABLE_NAME:``,r=typeof n.COLUMN_NAME==`string`?n.COLUMN_NAME:``,i=typeof n.DATA_TYPE==`string`?n.DATA_TYPE:``,a=typeof n.COLUMN_COMMENT==`string`?n.COLUMN_COMMENT:``;if(e===``||r===``||i===``)continue;let o=t.get(e)??[];o.push({name:r,dataType:i.toLowerCase(),comment:a}),t.set(e,o)}return t}async function planInterruptedMySQLDecimalRecovery(e,t,n){let{rows:r}=await e(`
7
- SELECT
8
- tc.TABLE_NAME,
9
- tc.CONSTRAINT_NAME,
10
- tc.ENFORCED,
11
- cc.CHECK_CLAUSE
12
- FROM information_schema.TABLE_CONSTRAINTS tc
13
- JOIN information_schema.CHECK_CONSTRAINTS cc
14
- ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
15
- AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
16
- WHERE tc.CONSTRAINT_SCHEMA = ?
17
- AND tc.CONSTRAINT_TYPE = 'CHECK'
18
- AND LEFT(tc.CONSTRAINT_NAME, 15) = ?
19
- ORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME
20
- `,[t,`viborm_decimal_`]);if(r.length===0)return[];if(r.length>1){let e=r[0];refuseReservedConstraint(typeof e?.CONSTRAINT_NAME==`string`?e.CONSTRAINT_NAME:`<unreported>`,typeof e?.TABLE_NAME==`string`?e.TABLE_NAME:`<unreported>`,`the catalog contains ${r.length} reserved proofs, although one locked conversion can leave at most one`)}let i=groupColumns((await e(`
21
- SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT
22
- FROM information_schema.COLUMNS
23
- WHERE TABLE_SCHEMA = ?
24
- ORDER BY TABLE_NAME, ORDINAL_POSITION
25
- `,[t])).rows);return r.map(e=>proveConstraint(e,i)).map(e=>`ALTER TABLE ${n(t)}.${n(e.tableName)} DROP CHECK ${n(e.constraintName)}`)}const z=new Set([`bigint`,`bit`,`decimal`,`double`,`float`,`int`,`integer`,`mediumint`,`numeric`,`real`,`smallint`,`tinyint`]);function formatColumnType(e){if(e.DATA_TYPE.toLowerCase()===`point`){let t=readSrid(e);return t===void 0?`POINT`:`POINT SRID ${t}`}if(e.DATA_TYPE===`enum`){let t=h(e.COLUMN_TYPE);return t?_(t):e.COLUMN_TYPE}let t=e.COLUMN_TYPE.toLowerCase();return t.includes(`unsigned`)||t.includes(`zerofill`)||t.includes(`(`)&&e.DATA_TYPE!==`enum`?e.COLUMN_TYPE:e.DATA_TYPE===`varchar`&&e.CHARACTER_MAXIMUM_LENGTH?`VARCHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`char`&&e.CHARACTER_MAXIMUM_LENGTH?`CHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION?e.NUMERIC_SCALE!==null&&e.NUMERIC_SCALE!==void 0?`DECIMAL(${e.NUMERIC_PRECISION},${e.NUMERIC_SCALE})`:`DECIMAL(${e.NUMERIC_PRECISION})`:e.DATA_TYPE.toUpperCase()}function readSrid(e){if(e.SRS_ID===null||e.SRS_ID===void 0)return;let r=Number(e.SRS_ID);if(Number.isSafeInteger(r)&&r>=0&&r<=4294967295)return r;throw new n(`MySQL reported an invalid SRID for column "${e.TABLE_NAME}"."${e.COLUMN_NAME}". Migration introspection is refused rather than publishing an unprovable spatial type.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-srid`}})}function isAutoIncrement(e){return e.toLowerCase().includes(`auto_increment`)}function readDecimalDomain(e){if(e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION!==null){let i=r(e.NUMERIC_PRECISION,e.NUMERIC_SCALE??0,`mysql`);if(i!==void 0)return i;throw new n(`MySQL reported column "${e.TABLE_NAME}"."${e.COLUMN_NAME}" as DECIMAL(${String(e.NUMERIC_PRECISION)},${String(e.NUMERIC_SCALE??0)}), outside VibORM's complete exact-decimal domain for this provider. Migration introspection is refused rather than publishing an invalid descriptor.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-decimal-domain`}})}if(e.DATA_TYPE===`json`)return E(e.COLUMN_COMMENT)}const B=/^_([A-Za-z0-9_]+)\\'([\s\S]*)\\'$/,V=/\\([\s\S]?)/g;function decodeSingleByte(e){return Array.from(e,e=>String.fromCharCode(e)).join(``)}const H=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376];function decodeLatin1(e){return Array.from(e,e=>String.fromCharCode(e>=128&&e<=159?H[e-128]??e:e)).join(``)}const U=new Map([[`utf8`,P],[`utf8mb3`,P],[`utf8mb4`,P],[`latin1`,decodeLatin1],[`ascii`,decodeSingleByte],[`binary`,decodeSingleByte]]);function decodeIntroducedLiteral(e,t){let n=U.get(e.toLowerCase());if(n===void 0)return;let r=[...t].map(e=>e.codePointAt(0)??0);if(!r.some(e=>e>255))try{return n(Uint8Array.from(r))}catch{return}}function unescapeOneLayer(e){let t=!0,n=e.replace(V,(e,n)=>{let r=g.get(n);return r===void 0?(t=!1,n):r});return t?n:void 0}function deparsedStringValue(e){let t=B.exec(e),n=t?.[1],r=t?.[2],i=n===void 0||r===void 0?void 0:decodeIntroducedLiteral(n,r),a=i===void 0?void 0:unescapeOneLayer(i);return a===void 0?void 0:unescapeOneLayer(a)}function cleanDefault(e){let t=e.COLUMN_DEFAULT;if(t!==null){if(e.EXTRA.toUpperCase().includes(`DEFAULT_GENERATED`)){let e=deparsedStringValue(t);return e===void 0?t:`(${v(e)})`}return z.has(e.DATA_TYPE.toLowerCase())?t:v(t)}}function admitContainedForeignKeys(e,r,i){for(let a of e)if(!(i!==void 0&&!(a.TABLE_SCHEMA===r&&i.includes(a.TABLE_NAME))&&!(a.REFERENCED_TABLE_SCHEMA===r&&i.includes(a.REFERENCED_TABLE_NAME)))&&!(a.TABLE_SCHEMA===r&&a.REFERENCED_TABLE_SCHEMA===r))throw new n(`Foreign key "${a.CONSTRAINT_NAME}" crosses a database boundary: \`${a.TABLE_SCHEMA}\`.\`${a.TABLE_NAME}\` references \`${a.REFERENCED_TABLE_SCHEMA}\`.\`${a.REFERENCED_TABLE_NAME}\`, and this client manages only "${r}". Migration work is refused before any snapshot, plan or DDL: VibORM cannot recreate or drop a constraint whose other half lives in a database it does not own.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`cross-database-foreign-key`,constraint:a.CONSTRAINT_NAME,namespace:r,table:`${a.TABLE_SCHEMA}.${a.TABLE_NAME}`,referencedTable:`${a.REFERENCED_TABLE_SCHEMA}.${a.REFERENCED_TABLE_NAME}`}})}async function introspect(e,r,i){let a=await resolveCatalogNamespace(e,r),o=[a],s=await e(`
26
- SELECT TABLE_NAME
27
- FROM information_schema.TABLES
28
- WHERE TABLE_SCHEMA = ?
29
- AND TABLE_TYPE = 'BASE TABLE'
30
- ORDER BY TABLE_NAME
31
- `,o),c=await e(`
32
- SELECT
33
- TABLE_NAME,
34
- COLUMN_NAME,
35
- DATA_TYPE,
36
- COLUMN_TYPE,
37
- IS_NULLABLE,
38
- COLUMN_DEFAULT,
39
- CHARACTER_MAXIMUM_LENGTH,
40
- NUMERIC_PRECISION,
41
- NUMERIC_SCALE,
42
- SRS_ID,
43
- EXTRA,
44
- COLUMN_COMMENT
45
- FROM information_schema.COLUMNS
46
- WHERE TABLE_SCHEMA = ?
47
- ORDER BY TABLE_NAME, ORDINAL_POSITION
48
- `,o),l=await e(`
49
- SELECT
50
- tc.TABLE_NAME,
51
- tc.CONSTRAINT_NAME,
52
- kcu.COLUMN_NAME,
53
- kcu.ORDINAL_POSITION
54
- FROM information_schema.TABLE_CONSTRAINTS tc
55
- JOIN information_schema.KEY_COLUMN_USAGE kcu
56
- ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
57
- AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA
58
- AND tc.TABLE_NAME = kcu.TABLE_NAME
59
- WHERE tc.TABLE_SCHEMA = ?
60
- AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
61
- ORDER BY tc.TABLE_NAME, kcu.ORDINAL_POSITION
62
- `,o),d=await e(`
63
- SELECT
64
- TABLE_NAME,
65
- INDEX_NAME,
66
- COLUMN_NAME,
67
- NON_UNIQUE,
68
- INDEX_TYPE,
69
- INDEX_COMMENT,
70
- SEQ_IN_INDEX
71
- FROM information_schema.STATISTICS
72
- WHERE TABLE_SCHEMA = ?
73
- AND INDEX_NAME != 'PRIMARY'
74
- ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX
75
- `,o),f=await e(`
76
- SELECT
77
- tc.TABLE_SCHEMA,
78
- tc.TABLE_NAME,
79
- tc.CONSTRAINT_NAME,
80
- kcu.COLUMN_NAME,
81
- kcu.REFERENCED_TABLE_SCHEMA,
82
- kcu.REFERENCED_TABLE_NAME,
83
- kcu.REFERENCED_COLUMN_NAME,
84
- rc.DELETE_RULE,
85
- rc.UPDATE_RULE,
86
- kcu.ORDINAL_POSITION
87
- FROM information_schema.TABLE_CONSTRAINTS tc
88
- JOIN information_schema.KEY_COLUMN_USAGE kcu
89
- ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
90
- AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA
91
- AND tc.TABLE_NAME = kcu.TABLE_NAME
92
- JOIN information_schema.REFERENTIAL_CONSTRAINTS rc
93
- ON rc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
94
- AND rc.CONSTRAINT_SCHEMA = tc.TABLE_SCHEMA
95
- WHERE tc.CONSTRAINT_TYPE = 'FOREIGN KEY'
96
- AND (tc.TABLE_SCHEMA = ? OR kcu.REFERENCED_TABLE_SCHEMA = ?)
97
- ORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION
98
- `,[a,a]);admitContainedForeignKeys(f.rows,a,i);let p=j(c.rows,e=>e.TABLE_NAME),g=j(l.rows,e=>e.TABLE_NAME),v=b(d.rows,e=>e.TABLE_NAME,e=>e.INDEX_NAME),y=b(f.rows.filter(e=>e.TABLE_SCHEMA===a),e=>e.TABLE_NAME,e=>e.CONSTRAINT_NAME),x=[],S=new Set,C=[];for(let e of s.rows){let r=e.TABLE_NAME,a=[];for(let e of p.get(r)||[]){if((i===void 0||i.includes(r))&&(e.EXTRA.toUpperCase().includes(`VIRTUAL GENERATED`)||e.EXTRA.toUpperCase().includes(`STORED GENERATED`)))throw new n(`MySQL column "${r}.${e.COLUMN_NAME}" is generated. Synchronization refuses before effects because its expression cannot be represented.`,t.MIGRATION_INVALID_STATE,{meta:{table:r,column:e.COLUMN_NAME,feature:`generated column`}});if(e.DATA_TYPE===`enum`){let t=h(e.COLUMN_TYPE),n=t&&_(t);t&&n&&!S.has(n)&&(x.push({name:n,values:t}),S.add(n))}let o=i===void 0||i.includes(r),s=o?readDecimalDomain(e):void 0;a.push({name:e.COLUMN_NAME,type:o?formatColumnType(e):e.COLUMN_TYPE,nullable:e.IS_NULLABLE===`YES`,default:o?cleanDefault(e):void 0,autoIncrement:isAutoIncrement(e.EXTRA),decimal:s})}let o,s=g.get(r);if(s&&s.length>0){s.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let e=s[0];e&&(o={columns:s.map(e=>e.COLUMN_NAME),name:e.CONSTRAINT_NAME})}let c=[],l=v.get(r),d=new Set(y.get(r)?.keys()??[]);if(l)for(let[e,t]of l){if(d.has(e))continue;t.sort((e,t)=>e.SEQ_IN_INDEX-t.SEQ_IN_INDEX);let n=t[0],r=n?.INDEX_COMMENT?.startsWith(m)?u(n.INDEX_COMMENT.slice(m.length),e):void 0;if(r){c.push(r);continue}if(n){let r=n.INDEX_TYPE.toLowerCase(),i=r===`rtree`?`spatial`:r;c.push({name:e,columns:t.map(e=>e.COLUMN_NAME),unique:n.NON_UNIQUE===0,type:i===`btree`||i===`hash`||i===`fulltext`||i===`spatial`?i:void 0})}}let f=[],b=y.get(r);if(b)for(let[e,t]of b){t.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let n=t[0];n&&f.push({name:e,columns:t.map(e=>e.COLUMN_NAME),referencedTable:n.REFERENCED_TABLE_NAME,referencedColumns:t.map(e=>e.REFERENCED_COLUMN_NAME),onDelete:T(n.DELETE_RULE),onUpdate:T(n.UPDATE_RULE)})}C.push({name:r,columns:a,primaryKey:o,indexes:c,foreignKeys:f,uniqueConstraints:[]})}return{tables:C,enums:x.length>0?x:void 0}}const W=/[^a-z0-9_]/g;function hashLockScope(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function mysqlMigrationLockName(e){let t=e.toLowerCase();return`viborm_migration_${t.replace(W,`_`).slice(0,38)}_${hashLockScope(t)}`}function mysqlAcquireLockStatement(e,t,n){return`SELECT GET_LOCK(${n(mysqlMigrationLockName(e))}, ${t}) AS acquired`}function mysqlReleaseLockStatement(e,t){return`SELECT RELEASE_LOCK(${t(mysqlMigrationLockName(e))}) AS released`}function mysqlLockAnswer(e,t){if(e.length!==1)return!1;let n=e[0];if(typeof n!=`object`||!n)return!1;let r=Reflect.get(n,t);return typeof r==`number`?r===1:typeof r==`string`?Number(r)===1:!1}function mysqlSelectTargetStatement(e,t){return`USE ${t(e)}`}const G=/^(\d+)\.(\d+)\.(\d+)/;async function proveMySQLExactValueSession(e,r){let{rows:i}=await e(`SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS server_version`),a=i[0],o=typeof a==`object`&&a?Reflect.get(a,`sql_mode`):void 0,s=typeof o==`string`?o:``,c=typeof a==`object`&&a?Reflect.get(a,`server_version`):void 0,l=typeof c==`string`?c:`<unreported>`;if(!supportsEnforcedMySQLChecks(l))throw new n(`This MySQL migration session reports version "${l}". Fixed-decimal conversions require MySQL 8.0.16 or later, where CHECK constraints are enforced; the command is refused before any migration effect.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`unenforced-check-constraints`,target:r}});if(!s.split(`,`).some(e=>{let t=e.trim();return t===`STRICT_TRANS_TABLES`||t===`STRICT_ALL_TABLES`}))throw new n(`This MySQL session runs in sql_mode "${s}", which has neither STRICT_TRANS_TABLES nor STRICT_ALL_TABLES. Effectful migration work is refused: without a strict mode MySQL answers an out-of-range DECIMAL with a warning and stores the clamped value, so an exact fixed-decimal column would silently stop holding what it was given. Enable a strict mode on the server or on this connection and run the command again.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`non-strict-sql-mode`,target:r}})}function supportsEnforcedMySQLChecks(e){if(e.toLowerCase().includes(`mariadb`))return!1;let t=G.exec(e);if(t===null)return!1;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]);return n>8||n===8&&(r>0||i>=16)}const K=[/^GEOMETRY\b/,/^POINT\b/,/^LINESTRING\b/,/^POLYGON\b/,/^MULTIPOINT\b/,/^MULTILINESTRING\b/,/^MULTIPOLYGON\b/,/^GEOMETRYCOLLECTION\b/],q=/^(?:(?:TINY|MEDIUM|LONG)?(?:TEXT|BLOB)|JSON|GEOMETRY|POINT|LINESTRING|POLYGON|MULTI(?:POINT|LINESTRING|POLYGON)|GEOMETRYCOLLECTION)\b/i,J=/[\s(]/;function classifyDecimalListDescriptorChange(e,t){return e.scale===t.scale?e.precision<t.precision?`widening`:e.precision>t.precision?`narrowing`:`same`:`rescaling`}const Y=`InnoDB`,X=`utf8mb4_0900_bin`,Z=d.point.indexOf(` `),Q=d.point.slice(0,Z),$=d.point.slice(Z+1);function mysqlRefusesLiteralDefault(e){let t=e.toUpperCase();return t.includes(`TEXT`)||t.includes(`BLOB`)||t.includes(`JSON`)||K.some(e=>e.test(t))}const ee=/^(?:DATETIME|TIMESTAMP)\s*(?:\((\d+)\))?$/i;function mysqlNowExpression(e){let t=ee.exec(e.trim());if(t!==null)return t[1]===void 0?`CURRENT_TIMESTAMP`:`CURRENT_TIMESTAMP(${t[1]})`}function finalizeMySQLColumn(e,t){let n=e.type.toUpperCase()===`TEXT`&&t?`VARCHAR(191)`:e.type,r=e.default!==void 0&&mysqlRefusesLiteralDefault(n)?`(${e.default})`:e.default;return n===e.type&&r===e.default?e:{...e,type:n,default:r}}function isMySQLExactIntegerType(e){let t=e.trim().toUpperCase().split(J,1)[0];return t===`INT`||t===`INTEGER`||t===`BIGINT`}const te=new class MySQLMigrationDriver extends F{dialect=`mysql`;driverName=`mysql`;capabilities={supportsNativeEnums:!0,supportsAddEnumValueInTransaction:!1,supportsIndexTypes:[`btree`,`fulltext`,`spatial`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!0,introspectionReadsConstraintNames:!0};getIrreversibleRollbackReason(e){if(e.type!==`alterColumn`)return;let t=e.from.decimal,n=e.to.decimal;if(!(t===void 0||n===void 0||M(e.from)!==`list`||M(e.to)!==`list`||classifyDecimalListDescriptorChange(t,n)!==`narrowing`))return`MySQL cannot automatically roll back the decimal-list widening of "${e.tableName}"."${e.columnName}": the inverse narrows ${i(t)} to ${i(n)}, and its implicit DDL commits cannot make the stricter proof, descriptor-marker change, and cleanup indivisible.`}async preflightSchemaRequirements(e,r){let i=new Set(e.flatMap(e=>e.tables.map(e=>e.name)));if(i.size===0)return!1;let a=await resolveCatalogNamespace(r,this.namespace),o=(await r(`SELECT TABLE_NAME FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ?`,[a])).rows.find(e=>i.has(e.TABLE_NAME));if(o)throw new n(`MySQL relation "${o.TABLE_NAME}" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,t.MIGRATION_INVALID_STATE,{meta:{table:o.TABLE_NAME,feature:`view`,namespace:a}});return!1}introspect(e){return introspect(e,this.namespace,this.target?.tables)}async adoptionHazards(e,t){if(e.length===0)return[];let n=await resolveCatalogNamespace(t,this.namespace),r=[];for(let i of e){let e=[n,i],[a]=(await t(`SELECT ENGINE, TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`,e)).rows,o=await t(`SELECT TRIGGER_NAME AS name FROM information_schema.TRIGGERS WHERE EVENT_OBJECT_SCHEMA = ? AND EVENT_OBJECT_TABLE = ? ORDER BY TRIGGER_NAME`,e),s=await t(`SELECT CONSTRAINT_NAME AS name FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'CHECK' ORDER BY CONSTRAINT_NAME`,e),c=await t(`SELECT COLUMN_NAME AS name FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLLATION_NAME IS NOT NULL AND COLLATION_NAME <> ? ORDER BY ORDINAL_POSITION`,[...e,X]),l=[...o.rows.map(({name:e})=>`trigger "${e}"`),...s.rows.map(({name:e})=>`CHECK constraint "${e}"`),...a?.ENGINE&&a.ENGINE!==Y?[`ENGINE=${a.ENGINE}`]:[],...a?.TABLE_COLLATION&&a.TABLE_COLLATION!==X?[`the table collation ${a.TABLE_COLLATION}`]:[],...c.rows.map(({name:e})=>`a collation on column "${e}"`)];r.push(...l.map(e=>({table:i,feature:e})))}return r}escapeValue(e){return e==null?`NULL`:v(String(e))}escapeIdentifier(e){if(e==null)throw new n(`Cannot escape null or undefined identifier`,t.INVALID_INPUT);return`\`${String(e).replace(/`/g,"``")}\``}tableRef(e,t){return c(e=>this.escapeIdentifier(e),t===`live`?this.namespace:void 0,e)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0||t.array===!0?void 0:o(n,r,`mysql`);if(i)return i.columnType;let s=a(r,`mysql`);return s&&!t.array?s.type:k({type:t.type,array:t.array,decimal:t.decimal})}getDefaultExpression(e,t){let n=t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate?this.literalDefaultValue(t):void 0;if(t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate&&typeof n==`string`)return this.escapeValue(s(n));if(!(t.hasDefault&&t.default===null))return t.autoGenerate?.kind===`now`?mysqlNowExpression(this.mapScalarType(e,t)):super.getDefaultExpression(e,t)}finalizeTable(e){let r=new Set([...e.primaryKey?.columns??[],...e.uniqueConstraints.flatMap(e=>e.columns),...e.indexes.flatMap(e=>e.raw?[]:e.columns),...e.foreignKeys.flatMap(e=>e.columns)]),i=new Set(e.indexes.map(e=>e.name)),a=e.uniqueConstraints.filter(e=>!i.has(e.name)).map(e=>({name:e.name,columns:e.columns,unique:!0})),o={...e,primaryKey:e.primaryKey?{...e.primaryKey,name:`PRIMARY`}:void 0,columns:e.columns.map(e=>finalizeMySQLColumn(e,r.has(e.name))),indexes:[...e.indexes,...a],uniqueConstraints:[]},s=o.indexes.filter(e=>!(e.raw||e.type&&e.type!==`btree`)),c=[{name:`PRIMARY`,columns:o.primaryKey?.columns??[]},...s.map(e=>({name:e.name,columns:e.columns})),...o.foreignKeys.map(e=>({name:e.name,columns:e.columns}))];for(let{name:r,columns:i}of c)for(let a of i){let i=o.columns.find(e=>e.name===a);if(i&&q.test(i.type))throw new n(`MySQL key "${e.name}.${r}" cannot directly index ${i.type} column "${i.name}". Use an indexable native type such as VARCHAR, or manage a reviewed prefix/expression index outside this declaration.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.name,column:i.name}})}let l=o.columns.filter(e=>e.autoIncrement);if(l.length>1||l.some(e=>o.primaryKey?.columns[0]!==e.name&&!s.some(t=>t.columns[0]===e.name&&!t.where)&&!o.foreignKeys.some(t=>t.columns[0]===e.name)))throw new n(`MySQL table "${e.name}" requires at most one AUTO_INCREMENT column, first in an ordinary key. Declare its primary key or leading index explicitly.`,t.INVALID_INPUT,{meta:{table:e.name}});return o}formatBooleanDefault(e){return e?`1`:`0`}getEnumColumnType(e,t,n){return _(n)}static AUTO_INCREMENT_TYPES=new Set([`tinyint`,`smallint`,`mediumint`,`int`,`integer`,`bigint`]);validateAutoIncrementType(e){let r=e.type.toLowerCase().split(J)[0];if(!MySQLMigrationDriver.AUTO_INCREMENT_TYPES.has(r))throw new n(`MySQL AUTO_INCREMENT requires an integer type (TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT). Column "${e.name}" has type "${e.type}" which is not compatible with AUTO_INCREMENT.`,t.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}})}generateColumnDef(e,t){let n=[this.escapeIdentifier(e.name)],r=e.type.toUpperCase()===d.point;return e.autoIncrement?(this.validateAutoIncrementType(e),n.push(e.type),n.push(`AUTO_INCREMENT`)):n.push(r?Q:e.type),e.nullable||n.push(`NOT NULL`),r&&n.push($),e.default!==void 0&&!e.autoIncrement&&n.push(`DEFAULT ${e.default}`),e.decimal&&M(e)===`list`&&n.push(`COMMENT ${this.escapeValue(O(e.decimal))}`),n.join(` `)}generateCreateTable(e,t){let{table:n}=e,r=n.columns.map(e=>this.generateColumnDef(e,t)),i=n.columns.find(e=>e.autoIncrement),a=i&&n.primaryKey?.columns[0]!==i.name?n.indexes.find(e=>(!e.type||e.type===`btree`)&&!e.where&&!e.raw&&e.columns[0]===i.name):void 0;if(a&&r.push(`${a.unique?`UNIQUE `:``}KEY ${this.escapeIdentifier(a.name)} (${a.columns.map(e=>this.escapeIdentifier(e)).join(`, `)})`),n.primaryKey){let e=n.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`PRIMARY KEY (${e})`)}for(let e of n.uniqueConstraints){let t=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`CONSTRAINT ${this.escapeIdentifier(e.name)} UNIQUE (${t})`)}for(let e of n.foreignKeys)r.push(this.foreignKeyClause(e,t));let o=[`CREATE TABLE ${this.tableRef(n.name,t.destination)} (\n ${r.join(`,
99
- `)}\n) ENGINE=${Y} DEFAULT CHARSET=utf8mb4 COLLATE=${X}`];for(let e of n.indexes)e!==a&&o.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));return o}generateDropTable(e,t){return`DROP TABLE IF EXISTS ${this.tableRef(e.tableName,t.destination)}`}generateRenameTable(e,t){return`RENAME TABLE ${this.tableRef(e.from,t.destination)} TO ${this.tableRef(e.to,t.destination)}`}renameDerivedNames(e,t,n,r){let i=[...t].map(([e,{to:t}])=>{let i=n.foreignKeys.find(t=>t.name===e);return i?`DROP FOREIGN KEY ${this.escapeIdentifier(e)}, ADD ${this.foreignKeyClause({...i,name:t},r)}`:`RENAME INDEX ${this.escapeIdentifier(e)} TO ${this.escapeIdentifier(t)}`});return[`ALTER TABLE ${this.tableRef(e,r.destination)} ${i.join(`, `)}`]}generateAddColumn(e,t){let n=this.generateColumnDef(e.column,t);return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD COLUMN ${n}`}generateDropColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,t){return[`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`,...this.rawIndexesRenamedBy(e,t).flatMap(n=>[this.generateDropIndex({type:`dropIndex`,tableName:e.tableName,indexName:n.name},t),this.generateCreateIndex({type:`createIndex`,tableName:e.tableName,index:n},t)])]}generateAlterColumn(e,t){let{tableName:n,columnName:r,to:i}=e,a=this.tableRef(n,t.destination),o=this.generateColumnDef(i,t),s=r===i.name?`ALTER TABLE ${a} MODIFY COLUMN ${o}`:`ALTER TABLE ${a} CHANGE COLUMN ${this.escapeIdentifier(r)} ${o}`,c=this.decimalConversionBracket(e,a,t);return c===null?[s]:[c.validate,s,c.release]}decimalConversionBracket(e,r,a){let{from:o,to:s}=e,c=o.decimal,l=s.decimal;if(l===void 0||!x(o,s))return null;if(e.columnName!==s.name)throw new n(`The MySQL decimal conversion for "${e.tableName}"."${e.columnName}" also renames the column to "${s.name}". Run the rename as a separate migration step before changing the decimal descriptor; an interrupted CHECK proof must keep one stable column identity across MySQL's implicit DDL commits.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.tableName,column:e.columnName,type:`decimal-conversion-with-rename`}});let u=M(s);if(c===void 0)return(u!==`scalar`||!isMySQLExactIntegerType(o.type))&&this.refuseDecimalAdoption(e,a,u),this.decimalScalarConversionBracket(e,r,s.type,l);let d=M(o);if((u===void 0||d!==u)&&this.refuseDecimalConversion(e,a,`moves it from ${N(d)} to ${N(u)} storage, which`),u===`list`){let t=classifyDecimalListDescriptorChange(c,l);return t===`rescaling`&&this.refuseDecimalConversion(e,a,`moves its JSON list from ${i(c)} to ${i(l)}, which rescales every member and so`),t===`narrowing`&&this.refuseDecimalConversion(e,a,`narrows its JSON list from ${i(c)} to ${i(l)}, which`),this.decimalListConversionBracket(e,r,c)}return this.decimalScalarConversionBracket(e,r,s.type,l)}decimalListConversionBracket(e,t,n){let r=this.escapeIdentifier(l(`list`,n));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${r} CHECK (${y(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${r}`}}decimalScalarConversionBracket(e,t,n,r){let i=this.escapeIdentifier(l(`scalar`,r));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${i} CHECK (${A(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${i}`}}refuseDecimalAdoption(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" would adopt unmarked ${e.from.type} storage as a fixed-decimal ${N(i)}. Only INT and BIGINT have one exact descriptor-free meaning that a transient target-domain CHECK can prove. Approximate, text, native-decimal-without-descriptor, and unmarked JSON storage could already contain rounded values or members at an unknown scale. The change is refused before any statement runs, so MySQL cannot implicitly round or reinterpret the stored data. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal storage adoption`,dialect:`mysql`,target:r.destination}})}refuseDecimalConversion(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" ${i} would rewrite every stored value, and MySQL commits each DDL statement implicitly. There is no boundary that could make the member rewrite and its descriptor-marker change indivisible. The change is refused before any statement runs, so the schema and its data are unchanged. Only same-scale precision widening is applied automatically; narrowing or a scale change needs an explicit migration that validates and moves the values itself.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal descriptor conversion`,dialect:`mysql`,target:r.destination}})}generateCreateIndex(e,r){let{tableName:i,index:a}=e;if(a.raw){let e=p(a,{name:this.escapeIdentifier(a.name),table:this.tableRef(i,r.destination),column:e=>this.escapeIdentifier(e)});C(a,e,e=>f(e,`mysql`),[`COMMENT`,`ALGORITHM`,`LOCK`]);let o=m+w(a);if(new TextEncoder().encode(o).length>1024)throw new n(`The raw index "${a.name}" names too many or too long columns for MySQL's 1024-byte index comment, which holds VibORM's marker.`,t.FEATURE_NOT_SUPPORTED,{meta:{indexName:a.name}});return`${e}\nCOMMENT ${this.escapeValue(o)}`}if(this.validateIndexType(a.type,a.name),a.where)throw new n(`Index "${a.name}" declares a partial index predicate (where: "${a.where}"). MySQL does not support partial indexes. Either remove 'where' from the index definition, or move the predicate into a generated column and index that.`,t.FEATURE_NOT_SUPPORTED,{meta:{indexName:a.name,indexWhere:a.where}});let o=a.columns.map(e=>this.escapeIdentifier(e)).join(`, `),s=``;if(a.type===`fulltext`?s=`FULLTEXT `:a.type===`spatial`&&(s=`SPATIAL `),a.unique&&s)throw new n(`Cannot combine UNIQUE with ${a.type?.toUpperCase()} index "${a.name}". MySQL does not support UNIQUE ${a.type?.toUpperCase()} indexes. Either remove 'unique: true' from the index definition, or create a separate unique index.`,t.MIGRATION_FAILED,{meta:{indexName:a.name,indexType:a.type}});return`CREATE ${a.unique?`UNIQUE `:``}${s}INDEX ${this.escapeIdentifier(a.name)} ON ${this.tableRef(i,r.destination)} (${o})`}generateDropIndex(e,t){return`DROP INDEX ${this.escapeIdentifier(e.indexName)} ON ${this.tableRef(e.tableName,t.destination)}`}generateAddForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD ${this.foreignKeyClause(e.fk,t)}`}foreignKeyClause(e,t){let n=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `),r=e.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),i=`CONSTRAINT ${this.escapeIdentifier(e.name)} `;return i+=`FOREIGN KEY (${n}) `,i+=`REFERENCES ${this.tableRef(e.referencedTable,t.destination)} (${r})`,e.onDelete&&e.onDelete!==`noAction`&&(i+=` ON DELETE ${this.formatReferentialAction(e.onDelete)}`),e.onUpdate&&e.onUpdate!==`noAction`&&(i+=` ON UPDATE ${this.formatReferentialAction(e.onUpdate)}`),i}generateDropForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP FOREIGN KEY ${this.escapeIdentifier(e.fkName)}`}generateAddUniqueConstraint(e,t){let{tableName:n,constraint:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} UNIQUE (${i})`}generateDropUniqueConstraint(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP INDEX ${this.escapeIdentifier(e.constraintName)}`}generateAddPrimaryKey(e,t){let{tableName:n,primaryKey:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD PRIMARY KEY (${i})`}generateDropPrimaryKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP PRIMARY KEY`}generateCreateEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateDropEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateAlterEnum(e,t){let{enumName:n,newValues:r,dependentColumns:i}=e;if(!r||r.length===0)return[`-- MySQL: no new values provided for enum "${n}"`];if(!i||i.length===0)return[`-- MySQL: no dependent columns found for enum "${n}"`];let a=[],o=this.getEnumColumnType(``,``,r);a.push(...this.buildEnumReplacementUpdates(e,t));for(let e of i){let n=(t.currentSchema?.tables.find(t=>t.name===e.tableName))?.columns.find(t=>t.name===e.columnName);if(!n){a.push(`-- MySQL: column "${e.columnName}" not found in table "${e.tableName}"`);continue}let r=this.tableRef(e.tableName,t.destination),i=this.escapeIdentifier(e.columnName),s=n.nullable?``:` NOT NULL`,c=n.default===void 0?``:` DEFAULT ${n.default}`;a.push(`ALTER TABLE ${r} MODIFY COLUMN ${i} ${o}${s}${c}`)}return a}async proveNamespaceExists(e){await this.resolveCommandNamespace(e)}async resolveCommandNamespace(e){return await resolveCatalogNamespace(e,this.namespace)}generateAcquireLock(e){return mysqlAcquireLockStatement(this.requireLockScope(),30,e=>this.escapeValue(e))}generateReleaseLock(e){return mysqlReleaseLockStatement(this.requireLockScope(),e=>this.escapeValue(e))}provesLockAcquired(e){return mysqlLockAnswer(e,`acquired`)}provesLockReleased(e){return mysqlLockAnswer(e,`released`)}generateSelectTarget(){return this.namespace===void 0?null:mysqlSelectTargetStatement(this.namespace,e=>this.escapeIdentifier(e))}async proveSession(e){await proveMySQLExactValueSession(e,`database "${this.namespace??`(unbound)`}"`);let t=this.requireLockScope(),n=!1,r,i=Object.create(this);return Object.defineProperty(i,`programPreamble`,{value:async e=>{if(n)return[];if(r!==void 0)return await r,[];r=planInterruptedMySQLDecimalRecovery((t,n)=>e._executeRaw(t,n),t,e=>this.escapeIdentifier(e));try{let e=await r;return n=!0,e}catch(e){throw r=void 0,e}}}),Object.freeze(i),i}programPreamble(){return Promise.reject(new n(`This MySQL sequential migration program is not bound to its locked command's decimal-recovery scope.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-migration-command`}}))}requireLockScope(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no lock scope to name. A MySQL named lock is server-wide, and VibORM will not take one that covers every database on the instance. Supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return this.namespace}generateInventoryTables(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no table inventory to read. VibORM will not fall back to the connection's ambient default database here: a reset inventory decides what gets DROPPED. Supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return{sql:`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME`,params:[this.namespace]}}generateInventoryEnums(){return null}};export{te as t};
100
- //# sourceMappingURL=mysql-BNXWfTOo.mjs.map