@prisma/orm-target-sqlite 8.0.0-rc.9-dev.12 → 8.0.1-dev.1

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 (309) hide show
  1. package/README.md +5 -1
  2. package/dist/adapter-CLQMz42P.d.mts +205 -0
  3. package/dist/adapter-CLQMz42P.d.mts.map +1 -0
  4. package/dist/{adapter-jwxys1MM-CmUELyBs.mjs → adapter-CxzIV2_z-DKbo2Ebu.mjs} +347 -137
  5. package/dist/adapter-CxzIV2_z-DKbo2Ebu.mjs.map +1 -0
  6. package/dist/{adapter-DEYUC-KO-DO_abhIq.d.mts → adapter-xFPDhkod-Bfb8AQQJ.d.mts} +12 -9
  7. package/dist/adapter-xFPDhkod-Bfb8AQQJ.d.mts.map +1 -0
  8. package/dist/adapter.d.mts +14 -15
  9. package/dist/adapter.mjs +7 -6
  10. package/dist/adapter__adapter.d.mts +4 -4
  11. package/dist/adapter__adapter.mjs +3 -2
  12. package/dist/adapter__codec-types.d.mts +3 -3
  13. package/dist/adapter__column-types.d.mts +2 -2
  14. package/dist/adapter__column-types.mjs +2 -2
  15. package/dist/adapter__control.d.mts +5 -5
  16. package/dist/adapter__control.mjs +12 -247
  17. package/dist/adapter__control.mjs.map +1 -1
  18. package/dist/adapter__runtime.d.mts +1 -1
  19. package/dist/adapter__runtime.mjs +30 -16
  20. package/dist/adapter__runtime.mjs.map +1 -1
  21. package/dist/adapter__sql-renderer.d.mts +2 -2
  22. package/dist/adapter__sql-renderer.mjs +1 -1
  23. package/dist/adapter__types.d.mts +3 -2
  24. package/dist/aggregates-CA7Idm1d.d.mts +164 -0
  25. package/dist/aggregates-CA7Idm1d.d.mts.map +1 -0
  26. package/dist/{aggregates-DWyPO7t6.mjs → aggregates-hLiHPHBG.mjs} +44 -26
  27. package/dist/aggregates-hLiHPHBG.mjs.map +1 -0
  28. package/dist/codec-descriptor-3oN7rtrW-Cc_u7U5-.d.mts +1 -0
  29. package/dist/codec-descriptor-C16gQAdS.d.mts +2 -0
  30. package/dist/{codec-descriptor-B9ru99aI-DTkdKFU5.mjs → codec-descriptor-DRmF-crq-BALI5Jtz.mjs} +11 -15
  31. package/dist/codec-descriptor-DRmF-crq-BALI5Jtz.mjs.map +1 -0
  32. package/dist/codec-descriptor-DuW-d9ef-BBRBN0Ri.d.mts +45 -0
  33. package/dist/codec-descriptor-DuW-d9ef-BBRBN0Ri.d.mts.map +1 -0
  34. package/dist/codec-ids-CH8Nqk89-LNT9hksu.d.mts +23 -0
  35. package/dist/codec-ids-CH8Nqk89-LNT9hksu.d.mts.map +1 -0
  36. package/dist/codec-ids-CTshXpbg-tcdbf_VC.mjs +23 -0
  37. package/dist/codec-ids-CTshXpbg-tcdbf_VC.mjs.map +1 -0
  38. package/dist/codec-ids-Do7Ml2pg.d.mts +1 -0
  39. package/dist/codec-types-CBLOfyrr.d.mts +2 -0
  40. package/dist/codec-types-CcuzuROC.d.mts +1 -0
  41. package/dist/codec-types-Ci-h2uxN-41PNpdNL.d.mts +35 -0
  42. package/dist/codec-types-Ci-h2uxN-41PNpdNL.d.mts.map +1 -0
  43. package/dist/codecs-BO3frExA.mjs +49 -0
  44. package/dist/codecs-BO3frExA.mjs.map +1 -0
  45. package/dist/codecs-DBQsDiM--Cy-r45H3.d.mts +378 -0
  46. package/dist/codecs-DBQsDiM--Cy-r45H3.d.mts.map +1 -0
  47. package/dist/codecs-Dou3fR1K.d.mts +1 -0
  48. package/dist/codecs-izq9l1NG-Bb2RnXsx.mjs +1081 -0
  49. package/dist/codecs-izq9l1NG-Bb2RnXsx.mjs.map +1 -0
  50. package/dist/column-types-D3MMpY3X.d.mts +42 -0
  51. package/dist/column-types-D3MMpY3X.d.mts.map +1 -0
  52. package/dist/column-types-D_PjRS6w.mjs +24 -0
  53. package/dist/column-types-D_PjRS6w.mjs.map +1 -0
  54. package/dist/contract-contributions-DEePsuJb-CXE-f6pP.mjs +28 -0
  55. package/dist/contract-contributions-DEePsuJb-CXE-f6pP.mjs.map +1 -0
  56. package/dist/{contract-free-D5cZrgNl.mjs → contract-free-B5S1OSEd.mjs} +8 -7
  57. package/dist/contract-free-B5S1OSEd.mjs.map +1 -0
  58. package/dist/{contract-free-CCLAXZV2.d.mts → contract-free-IqKgq8Pk.d.mts} +6 -6
  59. package/dist/contract-free-IqKgq8Pk.d.mts.map +1 -0
  60. package/dist/{control-D9vMRRgU.d.mts → control-C2TjacST.d.mts} +3 -3
  61. package/dist/control-C2TjacST.d.mts.map +1 -0
  62. package/dist/control-CtCvtwJx.d.mts +408 -0
  63. package/dist/control-CtCvtwJx.d.mts.map +1 -0
  64. package/dist/{control-CLirKz11.d.mts → control-DfWteXy-.d.mts} +31 -45
  65. package/dist/control-DfWteXy-.d.mts.map +1 -0
  66. package/dist/control-V3kPfMTR.mjs +61 -0
  67. package/dist/control-V3kPfMTR.mjs.map +1 -0
  68. package/dist/{control-tables-Dua-YcJL.d.mts → control-tables-DKXLHvMU.d.mts} +2 -2
  69. package/dist/control-tables-DKXLHvMU.d.mts.map +1 -0
  70. package/dist/{control-tables-D_o8dKRB-BXi43noL.mjs → control-tables-D_o8dKRB-n_QqsXcm.mjs} +2 -2
  71. package/dist/control-tables-D_o8dKRB-n_QqsXcm.mjs.map +1 -0
  72. package/dist/data-type-entries-DaT4D2GV-DE0V_N6k.mjs +120 -0
  73. package/dist/data-type-entries-DaT4D2GV-DE0V_N6k.mjs.map +1 -0
  74. package/dist/data-types-C1nzwKt7.d.mts +68 -0
  75. package/dist/data-types-C1nzwKt7.d.mts.map +1 -0
  76. package/dist/data-types-Djvapurb-BR-Y4NWN.mjs +239 -0
  77. package/dist/data-types-Djvapurb-BR-Y4NWN.mjs.map +1 -0
  78. package/dist/date-time-now-generators-DUb3x91B-D0keGG59.mjs +64 -0
  79. package/dist/date-time-now-generators-DUb3x91B-D0keGG59.mjs.map +1 -0
  80. package/dist/datetime-text-DPjoF6HJ-se0mLEbc.mjs +32 -0
  81. package/dist/datetime-text-DPjoF6HJ-se0mLEbc.mjs.map +1 -0
  82. package/dist/ddl-31OBcTco.d.mts +1 -0
  83. package/dist/{ddl-CXduXyOT-nlDP6DGx.mjs → ddl-CgkyurGo-B2o4mSIT.mjs} +45 -8
  84. package/dist/ddl-CgkyurGo-B2o4mSIT.mjs.map +1 -0
  85. package/dist/default-normalizer-BANdMVGr-BiUHyBX1.mjs +124 -0
  86. package/dist/default-normalizer-BANdMVGr-BiUHyBX1.mjs.map +1 -0
  87. package/dist/default-normalizer-CtNsZNRZ.d.mts +25 -0
  88. package/dist/default-normalizer-CtNsZNRZ.d.mts.map +1 -0
  89. package/dist/descriptor-meta-CafFMPhN-x3YQXDSX.mjs +26 -0
  90. package/dist/descriptor-meta-CafFMPhN-x3YQXDSX.mjs.map +1 -0
  91. package/dist/descriptor-meta-CkiPlqDS-n3hDP01X.mjs +137 -0
  92. package/dist/descriptor-meta-CkiPlqDS-n3hDP01X.mjs.map +1 -0
  93. package/dist/descriptor-meta-DEr1ALec-DvT6glGq.mjs +385 -0
  94. package/dist/descriptor-meta-DEr1ALec-DvT6glGq.mjs.map +1 -0
  95. package/dist/driver.d.mts +2 -2
  96. package/dist/driver.mjs +1 -1
  97. package/dist/driver__control.d.mts +1 -1
  98. package/dist/driver__control.mjs +1 -1
  99. package/dist/driver__runtime.d.mts +1 -1
  100. package/dist/driver__runtime.mjs +58 -20
  101. package/dist/driver__runtime.mjs.map +1 -1
  102. package/dist/errors-DxbvEzQp-CeTjoGtL.mjs +146 -0
  103. package/dist/errors-DxbvEzQp-CeTjoGtL.mjs.map +1 -0
  104. package/dist/{migration-DOKPHtxn.mjs → migration-BYRMZiPU.mjs} +6 -5
  105. package/dist/migration-BYRMZiPU.mjs.map +1 -0
  106. package/dist/{migration-uylRe5MP.d.mts → migration-Dekon_QC.d.mts} +6 -5
  107. package/dist/migration-Dekon_QC.d.mts.map +1 -0
  108. package/dist/{nodes-D8EC1yCx-rpfpuJ4T.d.mts → nodes-D8EC1yCx-BS-fKla6.d.mts} +2 -2
  109. package/dist/nodes-D8EC1yCx-BS-fKla6.d.mts.map +1 -0
  110. package/dist/{nodes-DUZSdX86-BBEEaxXY.mjs → nodes-DUZSdX86-DWyLY3OW.mjs} +2 -2
  111. package/dist/nodes-DUZSdX86-DWyLY3OW.mjs.map +1 -0
  112. package/dist/op-factory-call-DjbjegGT-DsQBI5Ll.mjs +2044 -0
  113. package/dist/op-factory-call-DjbjegGT-DsQBI5Ll.mjs.map +1 -0
  114. package/dist/op-factory-call-gQ5ddSys.d.mts +327 -0
  115. package/dist/op-factory-call-gQ5ddSys.d.mts.map +1 -0
  116. package/dist/pack-CHESErO8.d.mts +1477 -0
  117. package/dist/pack-CHESErO8.d.mts.map +1 -0
  118. package/dist/{planner-Bxdi7jZF.d.mts → planner-Bu5XBkHm.d.mts} +21 -10
  119. package/dist/planner-Bu5XBkHm.d.mts.map +1 -0
  120. package/dist/planner-C1OMkqV5-BAv-WPw6.mjs +497 -0
  121. package/dist/planner-C1OMkqV5-BAv-WPw6.mjs.map +1 -0
  122. package/dist/{planner-produced-sqlite-migration-BuJysRxx-CaDUbNVx.d.mts → planner-produced-sqlite-migration-CMjzJW5V-dVv0SjJm.d.mts} +5 -6
  123. package/dist/planner-produced-sqlite-migration-CMjzJW5V-dVv0SjJm.d.mts.map +1 -0
  124. package/dist/{planner-produced-sqlite-migration-C9uVDKrJ-CWbxSANn.mjs → planner-produced-sqlite-migration-CrbMD1ch-O7Mh_aKY.mjs} +13 -23
  125. package/dist/planner-produced-sqlite-migration-CrbMD1ch-O7Mh_aKY.mjs.map +1 -0
  126. package/dist/planner-produced-sqlite-migration-DtytlAAY.d.mts +1 -0
  127. package/dist/{planner-target-details-xR6UfIcz-CMahymzq.d.mts → planner-target-details-B-qtfkmj-DIGpv7YQ.d.mts} +2 -3
  128. package/dist/planner-target-details-B-qtfkmj-DIGpv7YQ.d.mts.map +1 -0
  129. package/dist/{planner-target-details-CIQ789Gc-C5U4yVY9.mjs → planner-target-details-Daaeo8s9-BGAN4JVc.mjs} +2 -4
  130. package/dist/planner-target-details-Daaeo8s9-BGAN4JVc.mjs.map +1 -0
  131. package/dist/render-ops-CQ-Kf4P0-DDUU4OFY.mjs +34 -0
  132. package/dist/render-ops-CQ-Kf4P0-DDUU4OFY.mjs.map +1 -0
  133. package/dist/{render-ops-B10yqmdG.d.mts → render-ops-Wlf_Pawh.d.mts} +3 -3
  134. package/dist/render-ops-Wlf_Pawh.d.mts.map +1 -0
  135. package/dist/require-temporal-CHWqSDF3-ElFTiAh6.mjs +16 -0
  136. package/dist/require-temporal-CHWqSDF3-ElFTiAh6.mjs.map +1 -0
  137. package/dist/{runtime-B1coahKC.d.mts → runtime-BvMPuBrJ.d.mts} +3 -3
  138. package/dist/runtime-BvMPuBrJ.d.mts.map +1 -0
  139. package/dist/runtime-C43fN_cJ.mjs +32 -0
  140. package/dist/runtime-C43fN_cJ.mjs.map +1 -0
  141. package/dist/{runtime-C5J9fusd.d.mts → runtime-CVBk_GlD.d.mts} +4 -4
  142. package/dist/runtime-CVBk_GlD.d.mts.map +1 -0
  143. package/dist/runtime-DqzT70C4.d.mts +67 -0
  144. package/dist/runtime-DqzT70C4.d.mts.map +1 -0
  145. package/dist/sql-renderer-DlZKtvVf.d.mts +1 -0
  146. package/dist/{sql-utils-0SJZOd7Q.d.mts → sql-utils-BqHka8P6.d.mts} +2 -2
  147. package/dist/sql-utils-BqHka8P6.d.mts.map +1 -0
  148. package/dist/{sql-utils-C2O4zVkP-Dz3Hb85I.mjs → sql-utils-CHBxMmv--Dl7wl7n3.mjs} +31 -4
  149. package/dist/sql-utils-CHBxMmv--Dl7wl7n3.mjs.map +1 -0
  150. package/dist/{sqlite-contract-view-BpNMaU2m-COMDaGaq.d.mts → sqlite-contract-view-BDw8T5Cp-BfFajhe4.d.mts} +5 -4
  151. package/dist/sqlite-contract-view-BDw8T5Cp-BfFajhe4.d.mts.map +1 -0
  152. package/dist/sqlite-contract-view-c-qO_pKt-DOCoqwrD.mjs +51 -0
  153. package/dist/sqlite-contract-view-c-qO_pKt-DOCoqwrD.mjs.map +1 -0
  154. package/dist/sqlite-migration-C_9TPlLD-DtKN8bi9.d.mts +227 -0
  155. package/dist/sqlite-migration-C_9TPlLD-DtKN8bi9.d.mts.map +1 -0
  156. package/dist/sqlite-migration-Cmzykasm--GxBXXny.mjs +1363 -0
  157. package/dist/sqlite-migration-Cmzykasm--GxBXXny.mjs.map +1 -0
  158. package/dist/{sqlite-contract-view-BYR10usg-BteDAUZr.mjs → sqlite-unbound-database-CfLXSiVo-Dy5VBXGz.mjs} +6 -47
  159. package/dist/sqlite-unbound-database-CfLXSiVo-Dy5VBXGz.mjs.map +1 -0
  160. package/dist/{shared-BYAX0FaQ--VvRXVRC.d.mts → tables-BY3u6rl_-Coqqy4JK.d.mts} +46 -10
  161. package/dist/tables-BY3u6rl_-Coqqy4JK.d.mts.map +1 -0
  162. package/dist/target.d.mts +30 -29
  163. package/dist/target.mjs +27 -20
  164. package/dist/target__aggregates.d.mts +1 -1
  165. package/dist/target__aggregates.mjs +1 -1
  166. package/dist/target__codec-descriptor.d.mts +2 -2
  167. package/dist/target__codec-descriptor.mjs +1 -1
  168. package/dist/target__codec-ids.d.mts +3 -3
  169. package/dist/target__codec-ids.mjs +2 -2
  170. package/dist/target__codec-types.d.mts +3 -3
  171. package/dist/target__codecs.d.mts +3 -3
  172. package/dist/target__codecs.mjs +4 -2
  173. package/dist/target__contract-free.d.mts +1 -1
  174. package/dist/target__contract-free.mjs +2 -2
  175. package/dist/target__control-tables.d.mts +1 -1
  176. package/dist/target__control-tables.mjs +1 -1
  177. package/dist/target__control.d.mts +3 -3
  178. package/dist/target__control.mjs +332 -114
  179. package/dist/target__control.mjs.map +1 -1
  180. package/dist/target__data-types.d.mts +2 -0
  181. package/dist/target__data-types.mjs +3 -0
  182. package/dist/target__ddl.d.mts +2 -2
  183. package/dist/target__ddl.mjs +1 -1
  184. package/dist/target__default-normalizer.d.mts +2 -2
  185. package/dist/target__default-normalizer.mjs +2 -2
  186. package/dist/target__migration.d.mts +3 -3
  187. package/dist/target__migration.mjs +3 -3
  188. package/dist/target__op-factory-call.d.mts +2 -2
  189. package/dist/target__op-factory-call.mjs +2 -2
  190. package/dist/target__pack.d.mts +1 -1
  191. package/dist/target__pack.mjs +1 -1
  192. package/dist/target__planner-produced-sqlite-migration.d.mts +2 -2
  193. package/dist/target__planner-produced-sqlite-migration.mjs +1 -1
  194. package/dist/target__planner-target-details.d.mts +1 -1
  195. package/dist/target__planner-target-details.mjs +1 -1
  196. package/dist/target__planner.d.mts +1 -1
  197. package/dist/target__planner.mjs +1 -1
  198. package/dist/target__render-ops.d.mts +1 -1
  199. package/dist/target__render-ops.mjs +1 -1
  200. package/dist/target__runtime.d.mts +3 -3
  201. package/dist/target__runtime.mjs +4 -17
  202. package/dist/target__sql-utils.d.mts +1 -1
  203. package/dist/target__sql-utils.mjs +1 -1
  204. package/dist/target__types.d.mts +2 -0
  205. package/dist/target__types.mjs +2 -0
  206. package/dist/{control--wMueaTg.d.mts → types-COqCbSev.d.mts} +3 -8
  207. package/dist/types-COqCbSev.d.mts.map +1 -0
  208. package/dist/types-CexPOm8x.d.mts +2 -0
  209. package/dist/{types-C5FSREvo-CwUlKK34.d.mts → types-RJMd2PlL-BTGAJrBQ.d.mts} +5 -7
  210. package/dist/types-RJMd2PlL-BTGAJrBQ.d.mts.map +1 -0
  211. package/package.json +23 -14
  212. package/dist/adapter-D7zw14p5.d.mts +0 -2
  213. package/dist/adapter-DEYUC-KO-DO_abhIq.d.mts.map +0 -1
  214. package/dist/adapter-jwxys1MM-CmUELyBs.mjs.map +0 -1
  215. package/dist/aggregates-BGuKJwfI.d.mts +0 -10
  216. package/dist/aggregates-BGuKJwfI.d.mts.map +0 -1
  217. package/dist/aggregates-DWyPO7t6.mjs.map +0 -1
  218. package/dist/codec-descriptor-B9ru99aI-DTkdKFU5.mjs.map +0 -1
  219. package/dist/codec-descriptor-BcgD9f3L-yDi5nh_k.d.mts +0 -31
  220. package/dist/codec-descriptor-BcgD9f3L-yDi5nh_k.d.mts.map +0 -1
  221. package/dist/codec-descriptor-rFuZ9DzY-CKRIRxah.d.mts +0 -1
  222. package/dist/codec-descriptor-vwfD3BMy.d.mts +0 -2
  223. package/dist/codec-ids-7WqtUuda.d.mts +0 -1
  224. package/dist/codec-ids-CzeDyMWW-BZAcI50I.d.mts +0 -14
  225. package/dist/codec-ids-CzeDyMWW-BZAcI50I.d.mts.map +0 -1
  226. package/dist/codec-ids-KMliSCRp-BhTbmbGr.mjs +0 -14
  227. package/dist/codec-ids-KMliSCRp-BhTbmbGr.mjs.map +0 -1
  228. package/dist/codec-types-B-TDcvQc.d.mts +0 -1
  229. package/dist/codec-types-CS0bD1kX.d.mts +0 -2
  230. package/dist/codec-types-D7uWRvQ1-DPnvquS8.d.mts +0 -25
  231. package/dist/codec-types-D7uWRvQ1-DPnvquS8.d.mts.map +0 -1
  232. package/dist/codecs-BDdR6FbY.mjs +0 -504
  233. package/dist/codecs-BDdR6FbY.mjs.map +0 -1
  234. package/dist/codecs-BQWqLgCl-CdB8t7HI.d.mts +0 -193
  235. package/dist/codecs-BQWqLgCl-CdB8t7HI.d.mts.map +0 -1
  236. package/dist/codecs-BTv6fRXv.d.mts +0 -1
  237. package/dist/column-types-NVxgsjFA.mjs +0 -34
  238. package/dist/column-types-NVxgsjFA.mjs.map +0 -1
  239. package/dist/column-types-iWGuW-0W.d.mts +0 -33
  240. package/dist/column-types-iWGuW-0W.d.mts.map +0 -1
  241. package/dist/contract-free-CCLAXZV2.d.mts.map +0 -1
  242. package/dist/contract-free-D5cZrgNl.mjs.map +0 -1
  243. package/dist/control--wMueaTg.d.mts.map +0 -1
  244. package/dist/control-B16T9OoX.mjs +0 -51
  245. package/dist/control-B16T9OoX.mjs.map +0 -1
  246. package/dist/control-CLirKz11.d.mts.map +0 -1
  247. package/dist/control-D9vMRRgU.d.mts.map +0 -1
  248. package/dist/control-tables-D_o8dKRB-BXi43noL.mjs.map +0 -1
  249. package/dist/control-tables-Dua-YcJL.d.mts.map +0 -1
  250. package/dist/ddl-CXduXyOT-nlDP6DGx.mjs.map +0 -1
  251. package/dist/ddl-CfSqNT0M.d.mts +0 -1
  252. package/dist/default-normalizer-B9V7TY5u.d.mts +0 -7
  253. package/dist/default-normalizer-B9V7TY5u.d.mts.map +0 -1
  254. package/dist/default-normalizer-DuoHj9-O-DsK7lJZn.mjs +0 -69
  255. package/dist/default-normalizer-DuoHj9-O-DsK7lJZn.mjs.map +0 -1
  256. package/dist/descriptor-meta-C0sCVHMY-1P-YUnEW.mjs +0 -34
  257. package/dist/descriptor-meta-C0sCVHMY-1P-YUnEW.mjs.map +0 -1
  258. package/dist/descriptor-meta-DjKgG4z5-D_0obUB8.mjs +0 -34
  259. package/dist/descriptor-meta-DjKgG4z5-D_0obUB8.mjs.map +0 -1
  260. package/dist/descriptor-meta-runtime-BkXK3OjD-CxZdKHCw.mjs +0 -13
  261. package/dist/descriptor-meta-runtime-BkXK3OjD-CxZdKHCw.mjs.map +0 -1
  262. package/dist/descriptor-meta-vjJkUDsn-Hz3rnAnk.mjs +0 -70
  263. package/dist/descriptor-meta-vjJkUDsn-Hz3rnAnk.mjs.map +0 -1
  264. package/dist/errors-DnR-sMHS-KkMLIP2U.mjs +0 -38
  265. package/dist/errors-DnR-sMHS-KkMLIP2U.mjs.map +0 -1
  266. package/dist/migration-DOKPHtxn.mjs.map +0 -1
  267. package/dist/migration-uylRe5MP.d.mts.map +0 -1
  268. package/dist/native-type-normalizer-CO2wKGL6.d.mts +0 -12
  269. package/dist/native-type-normalizer-CO2wKGL6.d.mts.map +0 -1
  270. package/dist/native-type-normalizer-GpQMEyN5.mjs +0 -14
  271. package/dist/native-type-normalizer-GpQMEyN5.mjs.map +0 -1
  272. package/dist/nodes-D8EC1yCx-rpfpuJ4T.d.mts.map +0 -1
  273. package/dist/nodes-DUZSdX86-BBEEaxXY.mjs.map +0 -1
  274. package/dist/op-factory-call-DoHN7Q7L.d.mts +0 -161
  275. package/dist/op-factory-call-DoHN7Q7L.d.mts.map +0 -1
  276. package/dist/op-factory-call-gc26GqyA-Db5Fasef.mjs +0 -829
  277. package/dist/op-factory-call-gc26GqyA-Db5Fasef.mjs.map +0 -1
  278. package/dist/pack-Cn0GAuEa.d.mts +0 -103
  279. package/dist/pack-Cn0GAuEa.d.mts.map +0 -1
  280. package/dist/planner-Bxdi7jZF.d.mts.map +0 -1
  281. package/dist/planner-Cqjr2usR-4wg3FB78.mjs +0 -824
  282. package/dist/planner-Cqjr2usR-4wg3FB78.mjs.map +0 -1
  283. package/dist/planner-produced-sqlite-migration-BuJysRxx-CaDUbNVx.d.mts.map +0 -1
  284. package/dist/planner-produced-sqlite-migration-C9uVDKrJ-CWbxSANn.mjs.map +0 -1
  285. package/dist/planner-produced-sqlite-migration-uySoqJO-.d.mts +0 -1
  286. package/dist/planner-target-details-CIQ789Gc-C5U4yVY9.mjs.map +0 -1
  287. package/dist/planner-target-details-xR6UfIcz-CMahymzq.d.mts.map +0 -1
  288. package/dist/render-ops-B10yqmdG.d.mts.map +0 -1
  289. package/dist/render-ops-KxAmAz6d-W2xyvA5y.mjs +0 -27
  290. package/dist/render-ops-KxAmAz6d-W2xyvA5y.mjs.map +0 -1
  291. package/dist/runtime-B1coahKC.d.mts.map +0 -1
  292. package/dist/runtime-B99c4n56.d.mts +0 -28
  293. package/dist/runtime-B99c4n56.d.mts.map +0 -1
  294. package/dist/runtime-C5J9fusd.d.mts.map +0 -1
  295. package/dist/shared-BYAX0FaQ--VvRXVRC.d.mts.map +0 -1
  296. package/dist/sql-renderer-KX6hn_tg.d.mts +0 -1
  297. package/dist/sql-utils-0SJZOd7Q.d.mts.map +0 -1
  298. package/dist/sql-utils-C2O4zVkP-Dz3Hb85I.mjs.map +0 -1
  299. package/dist/sqlite-contract-view-BYR10usg-BteDAUZr.mjs.map +0 -1
  300. package/dist/sqlite-contract-view-BpNMaU2m-COMDaGaq.d.mts.map +0 -1
  301. package/dist/sqlite-migration-CjMkH4Id-c6dM9w61.mjs +0 -94
  302. package/dist/sqlite-migration-CjMkH4Id-c6dM9w61.mjs.map +0 -1
  303. package/dist/sqlite-migration-o23JHwzY-CwNJcqwl.d.mts +0 -105
  304. package/dist/sqlite-migration-o23JHwzY-CwNJcqwl.d.mts.map +0 -1
  305. package/dist/target__native-type-normalizer.d.mts +0 -2
  306. package/dist/target__native-type-normalizer.mjs +0 -2
  307. package/dist/target__runtime.mjs.map +0 -1
  308. package/dist/types-B7e2QVEx.d.mts +0 -1
  309. package/dist/types-C5FSREvo-CwUlKK34.d.mts.map +0 -1
@@ -0,0 +1,2044 @@
1
+ import { l as sqliteError } from "./errors-DxbvEzQp-CeTjoGtL.mjs";
2
+ import { a as tableExistsAst, i as indexExistsAst, n as columnNameTakenAst, o as tableNameTakenAst, r as createTable, t as columnExistsAst } from "./ddl-CgkyurGo-B2o4mSIT.mjs";
3
+ import { n as escapeLiteral, r as quoteIdentifier, t as SQLITE_QUOTING } from "./sql-utils-CHBxMmv--Dl7wl7n3.mjs";
4
+ import { r as stripOuterParens } from "./default-normalizer-BANdMVGr-BiUHyBX1.mjs";
5
+ import { t as buildTargetDetails } from "./planner-target-details-Daaeo8s9-BGAN4JVc.mjs";
6
+ import { DdlColumn, FunctionColumnDefault, LiteralColumnDefault, opaqueSql } from "@prisma/orm-family-sql/relational-core/ast";
7
+ import { ifDefined } from "@prisma/orm-framework/utils/defined";
8
+ import "@prisma/orm-framework/components/codec";
9
+ import { blindCast } from "@prisma/orm-framework/utils/casts";
10
+ import { InternalError, assertNever } from "@prisma/orm-framework/utils/internal-error";
11
+ import "@prisma/orm-family-sql/contract/data-type";
12
+ import { type } from "arktype";
13
+ import { CliStructuredError } from "@prisma/orm-framework/errors/control";
14
+ import { expectAbsent, expectPresent, issueOutcome } from "@prisma/orm-framework/components/control";
15
+ import { UnfilledValue, checkSqlExpressionText, convertedColumnMeta, createSqlTextSources, encodeStoredValue, fillKeyProblem, fillValueProblem, isUnfilledSlot, keyPathOf, parseJsonPath, requiredColumnMeta, rowsHoldingValueMeta, slotSource, sqlOfSlot } from "@prisma/orm-family-sql/family/control";
16
+ import { RelationalSchemaNodeKind, sqlColumnTypesEqual } from "@prisma/orm-family-sql/schema-ir/types";
17
+ import { errorMigrationOperationOptionRemoved, errorUnfilledPlaceholder, unfilledPlaceholderOperation } from "@prisma/orm-framework/errors/migration";
18
+ import { REFERENTIAL_ACTION_SQL } from "@prisma/orm-family-sql/contract/referential-action-sql";
19
+ import { TsExpression, jsonToTsSource, tsArraySource, tsObjectSource, tsQuotedTextSource } from "@prisma/orm-framework/ts-render";
20
+ //#region ../../../3-targets/sqlite/1-target/dist/op-factory-call-DjbjegGT.mjs
21
+ function foldAsciiLetters(identifier) {
22
+ return identifier.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
23
+ }
24
+ /**
25
+ * Whether SQLite takes two identifiers for the same name. It compares table and index names without regard to the case of ASCII letters, and compares every other character exactly.
26
+ */
27
+ function sqliteIdentifiersCollide(left, right) {
28
+ return foldAsciiLetters(left) === foldAsciiLetters(right);
29
+ }
30
+ function step(description, sql, params, expectation) {
31
+ return {
32
+ description,
33
+ sql,
34
+ ...ifDefined("params", params),
35
+ ...ifDefined("expectation", expectation)
36
+ };
37
+ }
38
+ /** The text a `DdlColumn`'s type ends with when the column is SQLite's inline `INTEGER PRIMARY KEY AUTOINCREMENT`. */
39
+ const INLINE_AUTOINCREMENT_PRIMARY_KEY = " PRIMARY KEY AUTOINCREMENT";
40
+ /** The DDL default of a contract default: `autoincrement()` is written as part of the column's type instead. */
41
+ function sqliteDefaultToDdlColumnDefault(columnDefault) {
42
+ if (!columnDefault) return void 0;
43
+ switch (columnDefault.kind) {
44
+ case "literal": return new LiteralColumnDefault(columnDefault.value);
45
+ case "function":
46
+ if (columnDefault.expression === "autoincrement()") return void 0;
47
+ return new FunctionColumnDefault(opaqueSql(columnDefault.expression));
48
+ default: {
49
+ const exhaustive = columnDefault;
50
+ return assertNever(exhaustive, `sqliteDefaultToDdlColumnDefault: unhandled kind "${blindCast(exhaustive).kind}"`);
51
+ }
52
+ }
53
+ }
54
+ /**
55
+ * A column spec an earlier version wrote carries its default as SQL text in `defaultSql`, empty when it has none.
56
+ */
57
+ function refuseEarlierColumnSpecs(operation, tableName, columns) {
58
+ const earlier = columns.find((column) => Object.hasOwn(column, "defaultSql"));
59
+ if (earlier === void 0) return;
60
+ throw errorMigrationOperationOptionRemoved({
61
+ operation,
62
+ option: "defaultSql",
63
+ subject: `column ${JSON.stringify(earlier.name)} of table ${JSON.stringify(tableName)}`,
64
+ rewrite: "Write the column's default as `default: { kind: 'literal', value }` or `default: { kind: 'function', expression }`, with the column's `codecRef`, in place of `defaultSql`, and delete an empty `defaultSql`.",
65
+ upgradeEntry: "migration-ts-column-defaults"
66
+ });
67
+ }
68
+ /** The `DEFAULT …` clause the adapter writes for a column spec, `''` when it has none. */
69
+ function renderSpecDefault$1(column, tableName, lowerer) {
70
+ const ddlDefault = column.inlineAutoincrementPrimaryKey ? void 0 : sqliteDefaultToDdlColumnDefault(column.default);
71
+ return lowerer.renderColumnDefault(new DdlColumn({
72
+ name: column.name,
73
+ type: column.typeSql,
74
+ ...ifDefined("default", ddlDefault),
75
+ ...ifDefined("codecRef", column.codecRef)
76
+ }), tableName);
77
+ }
78
+ /**
79
+ * Renders a single column's inline DDL fragment within a `CREATE TABLE`
80
+ * statement. Honours the `inlineAutoincrementPrimaryKey` flag — SQLite
81
+ * treats `INTEGER PRIMARY KEY AUTOINCREMENT` as a special form that aliases
82
+ * `rowid`, and the column must not carry a `DEFAULT` or repeat `NOT NULL`.
83
+ */
84
+ function renderColumnDefinition(column, defaultClause) {
85
+ const parts = [quoteIdentifier(column.name), column.typeSql];
86
+ if (column.inlineAutoincrementPrimaryKey) parts.push("PRIMARY KEY AUTOINCREMENT");
87
+ else {
88
+ if (defaultClause) parts.push(defaultClause);
89
+ if (!column.nullable) parts.push("NOT NULL");
90
+ }
91
+ return parts.join(" ");
92
+ }
93
+ /**
94
+ * Renders an inline FOREIGN KEY constraint clause for a `CREATE TABLE`
95
+ * body. Every `SqliteForeignKeySpec` is constraint-bearing by construction
96
+ * (`tableSpecFromNode` only ever builds specs from schema-IR FK nodes, which
97
+ * are themselves constraint-only — a non-constraint FK contributes no node).
98
+ */
99
+ function renderForeignKeyClause(fk) {
100
+ let sql = `${fk.name ? `CONSTRAINT ${quoteIdentifier(fk.name)} ` : ""}FOREIGN KEY (${fk.columns.map(quoteIdentifier).join(", ")}) REFERENCES ${quoteIdentifier(fk.references.table)} (${fk.references.columns.map(quoteIdentifier).join(", ")})`;
101
+ if (fk.onDelete !== void 0) sql += ` ON DELETE ${REFERENTIAL_ACTION_SQL[fk.onDelete]}`;
102
+ if (fk.onUpdate !== void 0) sql += ` ON UPDATE ${REFERENTIAL_ACTION_SQL[fk.onUpdate]}`;
103
+ return sql;
104
+ }
105
+ function text(value) {
106
+ return `'${escapeLiteral(value)}'`;
107
+ }
108
+ function columnRow(column) {
109
+ return `(${text(column.name)}, ${text(column.typeSql.toLowerCase())}, ${column.notNull ? 1 : 0}, ${column.primaryKeyPosition})`;
110
+ }
111
+ /** Checks that the table has exactly these columns, each with its type, nullability and primary key position. */
112
+ function tableColumnsCheck(tableName, columns) {
113
+ const info = `pragma_table_info(${text(tableName)})`;
114
+ return {
115
+ description: `verify table "${tableName}" has exactly its columns`,
116
+ sql: `SELECT (SELECT COUNT(*) FROM ${info}) = ${columns.length} AND (SELECT COUNT(*) FROM ${info} WHERE (name, LOWER(type), "notnull", pk) IN (VALUES ${columns.map(columnRow).join(", ")})) = ${columns.length}`
117
+ };
118
+ }
119
+ /** Checks the column's type and nullability. */
120
+ function columnShapeCheck(tableName, column) {
121
+ return {
122
+ description: `verify column "${column.name}" on "${tableName}" has type ${column.typeSql} and ${column.notNull ? "is required" : "is optional"}`,
123
+ sql: `SELECT COUNT(*) > 0 FROM pragma_table_info(${text(tableName)}) WHERE name = ${text(column.name)} AND LOWER(type) = ${text(column.typeSql.toLowerCase())} AND "notnull" = ${column.notNull ? 1 : 0}`
124
+ };
125
+ }
126
+ /** Checks that the column takes NULL, or that no row holds `value` in it. */
127
+ function columnTakesNullOrValueAbsentCheck(tableName, columnName, value, description) {
128
+ return {
129
+ description,
130
+ sql: `SELECT (SELECT COUNT(*) > 0 FROM pragma_table_info(${text(tableName)}) WHERE name = ${text(columnName)} AND "notnull" = 0) OR NOT EXISTS (SELECT 1 FROM ${quoteIdentifier(tableName)} WHERE ${quoteIdentifier(columnName)} = ?1) AS result`,
131
+ params: [value]
132
+ };
133
+ }
134
+ /** Checks that the index is on the table, covers exactly these columns in this order, and is unique or not. */
135
+ function indexDefinitionCheck(tableName, indexName, columns, unique) {
136
+ const positions = columns.map((column, seqno) => `(${seqno}, ${text(column)})`).join(", ");
137
+ const info = `pragma_index_info(${text(indexName)})`;
138
+ return {
139
+ description: `verify index "${indexName}" on "${tableName}" covers (${columns.join(", ")})`,
140
+ sql: `SELECT EXISTS (SELECT 1 FROM pragma_index_list(${text(tableName)}) WHERE name = ${text(indexName)} AND "unique" = ${unique ? 1 : 0}) AND (SELECT COUNT(*) FROM ${info}) = ${columns.length} AND (SELECT COUNT(*) FROM ${info} WHERE (seqno, name) IN (VALUES ${positions})) = ${columns.length}`
141
+ };
142
+ }
143
+ function addColumnExecuteSql(tableName, column, defaultClause) {
144
+ return [
145
+ `ALTER TABLE ${quoteIdentifier(tableName)}`,
146
+ `ADD COLUMN ${quoteIdentifier(column.name)} ${column.typeSql}`,
147
+ defaultClause,
148
+ column.nullable ? "" : "NOT NULL"
149
+ ].filter(Boolean).join(" ");
150
+ }
151
+ function dropColumnExecuteSql(tableName, columnName) {
152
+ return `ALTER TABLE ${quoteIdentifier(tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`;
153
+ }
154
+ async function addColumn(tableName, column, lowerer) {
155
+ refuseEarlierColumnSpecs("addColumn", tableName, [column]);
156
+ const defaultClause = await renderSpecDefault$1(column, tableName, lowerer);
157
+ const checks = columnExistsAst(tableName, column.name);
158
+ const absent = await lowerer.lowerToExecuteRequest(checks.columnAbsent());
159
+ const present = await lowerer.lowerToExecuteRequest(checks.columnPresent());
160
+ return {
161
+ id: `column.${tableName}.${column.name}`,
162
+ label: `Add column ${column.name} on ${tableName}`,
163
+ summary: `Adds column ${column.name} on ${tableName}`,
164
+ operationClass: "additive",
165
+ target: {
166
+ id: "sqlite",
167
+ details: buildTargetDetails("column", column.name, tableName)
168
+ },
169
+ precheck: [step(`ensure column "${column.name}" is missing`, absent.sql, absent.params, expectAbsent(`column "${column.name}" on "${tableName}"`))],
170
+ execute: [step(`add column "${column.name}"`, addColumnExecuteSql(tableName, column, defaultClause))],
171
+ postcheck: [step(`verify column "${column.name}" exists`, present.sql, present.params, expectPresent(`column "${column.name}" on "${tableName}"`)), columnShapeCheck(tableName, {
172
+ name: column.name,
173
+ typeSql: column.typeSql,
174
+ notNull: !column.nullable
175
+ })]
176
+ };
177
+ }
178
+ function renameColumnExecuteSql(tableName, fromName, toName) {
179
+ return `ALTER TABLE ${quoteIdentifier(tableName)} RENAME COLUMN ${quoteIdentifier(fromName)} TO ${quoteIdentifier(toName)}`;
180
+ }
181
+ /**
182
+ * Renames a column. SQLite updates the indexes, foreign keys and triggers that name it, and keeps
183
+ * index names. SQLite takes names that differ only in case for the same name, so the new name
184
+ * must be free whatever its case, except in a rename that only changes case, which SQLite performs
185
+ * in one statement.
186
+ */
187
+ function renameColumnOperationId(tableName, fromName) {
188
+ return `renameColumn.${tableName}.${fromName}`;
189
+ }
190
+ async function renameColumn(tableName, fromName, toName, lowerer) {
191
+ const fromChecks = columnExistsAst(tableName, fromName);
192
+ const toChecks = columnExistsAst(tableName, toName);
193
+ const fromPresent = await lowerer.lowerToExecuteRequest(fromChecks.columnPresent());
194
+ const onlyCase = sqliteIdentifiersCollide(fromName, toName);
195
+ const toAbsent = await lowerer.lowerToExecuteRequest(onlyCase ? toChecks.columnAbsent() : columnNameTakenAst(tableName, toName).nameFree());
196
+ const toPresent = await lowerer.lowerToExecuteRequest(toChecks.columnPresent());
197
+ const fromAbsent = await lowerer.lowerToExecuteRequest(fromChecks.columnAbsent());
198
+ return {
199
+ id: renameColumnOperationId(tableName, fromName),
200
+ label: `Rename column ${fromName} on ${tableName} to ${toName}`,
201
+ summary: `Renames column ${fromName} on ${tableName} to ${toName}, keeping its values`,
202
+ operationClass: "widening",
203
+ target: {
204
+ id: "sqlite",
205
+ details: buildTargetDetails("column", toName, tableName)
206
+ },
207
+ precheck: [step(`ensure column "${fromName}" exists on "${tableName}"`, fromPresent.sql, fromPresent.params, expectPresent(`column "${fromName}" on "${tableName}"`)), step(`ensure column "${toName}" does not exist on "${tableName}"`, toAbsent.sql, toAbsent.params, expectAbsent(onlyCase ? `column "${toName}" on "${tableName}"` : `a column named "${toName}" on "${tableName}" in any case`))],
208
+ execute: [step(`rename column "${fromName}" on "${tableName}" to "${toName}"`, renameColumnExecuteSql(tableName, fromName, toName))],
209
+ postcheck: [step(`verify column "${toName}" exists on "${tableName}"`, toPresent.sql, toPresent.params, expectPresent(`column "${toName}" on "${tableName}"`)), step(`verify column "${fromName}" no longer exists on "${tableName}"`, fromAbsent.sql, fromAbsent.params, expectAbsent(`column "${fromName}" on "${tableName}"`))]
210
+ };
211
+ }
212
+ /** The SQLite JSON path of member `name`, as an SQL string literal. */
213
+ function memberPath(name) {
214
+ return `'${escapeLiteral(`$.${JSON.stringify(name)}`)}'`;
215
+ }
216
+ function child(value, depth) {
217
+ return `(${value} -> e${depth}.fullkey)`;
218
+ }
219
+ /**
220
+ * The children of a list or an object rewritten one by one, keeping their order; `kept` filters
221
+ * them. Any other value is left as it is.
222
+ */
223
+ function rewrittenChildren(value, depth, rewrite, kept) {
224
+ const e = `e${depth}`;
225
+ const each = `FROM json_each(${value}) AS ${e}${kept === void 0 ? "" : ` WHERE ${kept(child(value, depth))}`}`;
226
+ const rewritten = `json(${rewrite(child(value, depth))})`;
227
+ return `CASE json_type(${value}) WHEN 'array' THEN (SELECT json_group_array(${rewritten} ORDER BY ${e}.key) ${each}) WHEN 'object' THEN (SELECT json_group_object(${e}.key, ${rewritten} ORDER BY ${e}.id) ${each}) ELSE ${value} END`;
228
+ }
229
+ /** Whether `value` is a list or an object with a child that passes `test`. */
230
+ function someChild(value, depth, test) {
231
+ return `(json_type(${value}) IN ('array', 'object') AND EXISTS (SELECT 1 FROM json_each(${value}) AS e${depth} WHERE ${test(child(value, depth))}))`;
232
+ }
233
+ /**
234
+ * The JSON text that rewrites `value` along `steps` with `leaf`. A member step that meets no object
235
+ * with the member, or a wildcard step that meets neither a list nor an object, leaves the value as
236
+ * it is.
237
+ */
238
+ function jsonRewrite(value, steps, leaf, depth = 0) {
239
+ const [first, ...rest] = steps;
240
+ if (first === void 0) return leaf(value, depth);
241
+ if (first.kind === "member") {
242
+ const member = memberPath(first.name);
243
+ return `CASE WHEN json_type(${value}) = 'object' AND json_type(${value}, ${member}) IS NOT NULL THEN json_set(${value}, ${member}, json(${jsonRewrite(`(${value} -> ${member})`, rest, leaf, depth)})) ELSE ${value} END`;
244
+ }
245
+ return rewrittenChildren(value, depth, (c) => jsonRewrite(c, rest, leaf, depth + 1));
246
+ }
247
+ /**
248
+ * Whether the JSON text `value` holds, at the end of `steps`, a value that passes `test`. Each step
249
+ * tests the type of what it reads first, so a SQL `NULL`, a JSON `null`, a missing member, a value
250
+ * of another type, or a `null` element or member value never fails the match.
251
+ */
252
+ function jsonMatches(value, steps, test, depth = 0) {
253
+ const [first, ...rest] = steps;
254
+ if (first === void 0) return test(value, depth);
255
+ if (first.kind === "member") {
256
+ const member = memberPath(first.name);
257
+ return `(json_type(${value}) = 'object' AND json_type(${value}, ${member}) IS NOT NULL AND ${jsonMatches(`(${value} -> ${member})`, rest, test, depth)})`;
258
+ }
259
+ return someChild(value, depth, (c) => jsonMatches(c, rest, test, depth + 1));
260
+ }
261
+ /** Whether the JSON text `value` is an object that has member `name`. */
262
+ function hasMember(value, name) {
263
+ return `(json_type(${value}) = 'object' AND json_type(${value}, ${memberPath(name)}) IS NOT NULL)`;
264
+ }
265
+ function at(keyPath) {
266
+ return `at path ${JSON.stringify(keyPath.objectsText)}`;
267
+ }
268
+ /** Where in a column a key operation acts, as its label and step descriptions write it. */
269
+ function keyPlace(keyPath, tableName, columnName) {
270
+ return `${at(keyPath)} in column "${columnName}" of "${tableName}"`;
271
+ }
272
+ function noRowWhere(tableName, condition) {
273
+ return `SELECT NOT EXISTS (SELECT 1 FROM ${quoteIdentifier(tableName)} WHERE ${condition}) AS result`;
274
+ }
275
+ function objectsMatch(columnName, keyPath, test) {
276
+ return jsonMatches(quoteIdentifier(columnName), keyPath.objects, test);
277
+ }
278
+ function renameStoredKey(tableName, columnName, keyPath, to) {
279
+ const column = quoteIdentifier(columnName);
280
+ const from = memberPath(keyPath.key);
281
+ const renamed = jsonRewrite(column, keyPath.objects, (object) => `CASE WHEN ${hasMember(object, keyPath.key)} THEN json_set(json_remove(${object}, ${from}), ${memberPath(to)}, json(${object} -> ${from})) ELSE ${object} END`);
282
+ const holdsKey = objectsMatch(columnName, keyPath, (object) => hasMember(object, keyPath.key));
283
+ const place = keyPlace(keyPath, tableName, columnName);
284
+ return {
285
+ id: `renameStoredKey.${tableName}.${columnName}.${keyPath.path.text}`,
286
+ label: `Rename key "${keyPath.key}" to "${to}" ${place}`,
287
+ operationClass: "widening",
288
+ target: {
289
+ id: "sqlite",
290
+ details: buildTargetDetails("column", columnName, tableName)
291
+ },
292
+ precheck: [step(`ensure no object ${place} has both key "${keyPath.key}" and key "${to}"; remove one of the two keys from those objects`, noRowWhere(tableName, objectsMatch(columnName, keyPath, (object) => `(${hasMember(object, keyPath.key)} AND ${hasMember(object, to)})`)))],
293
+ execute: [step(`rename key "${keyPath.key}" to "${to}" ${place}`, `UPDATE ${quoteIdentifier(tableName)} SET ${column} = ${renamed} WHERE ${holdsKey}`)],
294
+ postcheck: [step(`verify no object ${place} has key "${keyPath.key}"`, noRowWhere(tableName, holdsKey))]
295
+ };
296
+ }
297
+ function removeStoredKey(tableName, columnName, keyPath) {
298
+ const column = quoteIdentifier(columnName);
299
+ const removed = jsonRewrite(column, keyPath.objects, (object) => `CASE WHEN ${hasMember(object, keyPath.key)} THEN json_remove(${object}, ${memberPath(keyPath.key)}) ELSE ${object} END`);
300
+ const holdsKey = objectsMatch(columnName, keyPath, (object) => hasMember(object, keyPath.key));
301
+ const place = keyPlace(keyPath, tableName, columnName);
302
+ return {
303
+ id: `removeStoredKey.${tableName}.${columnName}.${keyPath.path.text}`,
304
+ label: `Remove key "${keyPath.key}" ${place}`,
305
+ operationClass: "destructive",
306
+ target: {
307
+ id: "sqlite",
308
+ details: buildTargetDetails("column", columnName, tableName)
309
+ },
310
+ precheck: [],
311
+ execute: [step(`remove key "${keyPath.key}" ${place}`, `UPDATE ${quoteIdentifier(tableName)} SET ${column} = ${removed} WHERE ${holdsKey}`)],
312
+ postcheck: [step(`verify no object ${place} has key "${keyPath.key}"`, noRowWhere(tableName, holdsKey))]
313
+ };
314
+ }
315
+ /** `value` is the JSON text of the value the key takes, passed as a parameter. A key that holds JSON `null` is filled too, as a member that becomes required needs. */
316
+ function fillStoredKey(tableName, columnName, keyPath, value) {
317
+ const column = quoteIdentifier(columnName);
318
+ const member = memberPath(keyPath.key);
319
+ const lacks = (object) => `(json_type(${object}) = 'object' AND coalesce(json_type(${object}, ${member}), 'null') = 'null')`;
320
+ const filled = jsonRewrite(column, keyPath.objects, (object) => `CASE WHEN ${lacks(object)} THEN json_set(${object}, ${member}, json(?1)) ELSE ${object} END`);
321
+ const lacksKey = objectsMatch(columnName, keyPath, lacks);
322
+ const place = keyPlace(keyPath, tableName, columnName);
323
+ return {
324
+ id: `fillStoredKey.${tableName}.${columnName}.${keyPath.path.text}`,
325
+ label: `Fill key "${keyPath.key}" ${place}`,
326
+ operationClass: "widening",
327
+ target: {
328
+ id: "sqlite",
329
+ details: buildTargetDetails("column", columnName, tableName)
330
+ },
331
+ precheck: [],
332
+ execute: [step(`fill key "${keyPath.key}" ${place} in every object that lacks it or holds JSON null there`, `UPDATE ${quoteIdentifier(tableName)} SET ${column} = ${filled} WHERE ${lacksKey}`, [value])],
333
+ postcheck: [step(`verify every object ${place} has key "${keyPath.key}"`, noRowWhere(tableName, lacksKey))]
334
+ };
335
+ }
336
+ /** A stored value as operation ids, labels and step descriptions write it. */
337
+ function storedValueText(value) {
338
+ return JSON.stringify(value);
339
+ }
340
+ function idText(value) {
341
+ return String(value);
342
+ }
343
+ function valueAbsentCheck(tableName, columnName, value) {
344
+ return step(`verify no row of "${tableName}" holds value ${storedValueText(value)} in column "${columnName}"`, `SELECT NOT EXISTS (SELECT 1 FROM ${quoteIdentifier(tableName)} WHERE ${quoteIdentifier(columnName)} = ?1) AS result`, [value]);
345
+ }
346
+ function replaceStoredValue(tableName, columnName, from, to) {
347
+ const column = quoteIdentifier(columnName);
348
+ return {
349
+ id: `replaceStoredValue.${tableName}.${columnName}.${idText(from)}`,
350
+ label: `Replace value ${storedValueText(from)} with ${storedValueText(to)} in column "${columnName}" of "${tableName}"`,
351
+ operationClass: "widening",
352
+ target: {
353
+ id: "sqlite",
354
+ details: buildTargetDetails("column", columnName, tableName)
355
+ },
356
+ precheck: [],
357
+ execute: [step(`replace value ${storedValueText(from)} with ${storedValueText(to)} in column "${columnName}"`, `UPDATE ${quoteIdentifier(tableName)} SET ${column} = ?2 WHERE ${column} = ?1`, [from, to])],
358
+ postcheck: [valueAbsentCheck(tableName, columnName, from)]
359
+ };
360
+ }
361
+ function removeStoredValue(tableName, columnName, value, mark) {
362
+ const column = quoteIdentifier(columnName);
363
+ const takesNull = `ensure column "${columnName}" of "${tableName}" takes NULL, or no row holds ${storedValueText(value)} in it`;
364
+ return {
365
+ id: `removeStoredValue.${tableName}.${columnName}.${idText(value)}`,
366
+ label: `Remove value ${storedValueText(value)} from column "${columnName}" of "${tableName}"`,
367
+ operationClass: "destructive",
368
+ target: {
369
+ id: "sqlite",
370
+ details: buildTargetDetails("column", columnName, tableName)
371
+ },
372
+ precheck: [{
373
+ ...columnTakesNullOrValueAbsentCheck(tableName, columnName, value, takesNull),
374
+ ...mark === void 0 ? {} : { meta: rowsHoldingValueMeta({
375
+ ...mark,
376
+ table: tableName,
377
+ column: columnName,
378
+ storedValue: value
379
+ }) }
380
+ }],
381
+ execute: [step(`remove value ${storedValueText(value)} from column "${columnName}"`, `UPDATE ${quoteIdentifier(tableName)} SET ${column} = NULL WHERE ${column} = ?1`, [value])],
382
+ postcheck: [valueAbsentCheck(tableName, columnName, value)]
383
+ };
384
+ }
385
+ function cascadeStep(tableName, columnName, value, cascade) {
386
+ const referenced = cascade.columns.map((column, index) => {
387
+ const reference = cascade.references[index];
388
+ if (reference === void 0) throw new InternalError(`Cascade of table "${cascade.table}" has no reference for column "${column}"`);
389
+ return `${quoteIdentifier(tableName)}.${quoteIdentifier(reference)} = ${quoteIdentifier(cascade.table)}.${quoteIdentifier(column)}`;
390
+ }).join(" AND ");
391
+ return step(`delete the rows of "${cascade.table}" whose row of "${tableName}" holds value ${storedValueText(value)} in column "${columnName}", as their foreign key's cascade would`, `DELETE FROM ${quoteIdentifier(cascade.table)} WHERE EXISTS (SELECT 1 FROM ${quoteIdentifier(tableName)} WHERE ${quoteIdentifier(tableName)}.${quoteIdentifier(columnName)} = ?1 AND ${referenced})`, [value]);
392
+ }
393
+ /** The label of a `deleteRows` operation, which names each `cascade` table whose rows it deletes too. */
394
+ function deleteRowsLabel(tableName, columnName, value, cascade) {
395
+ const rows = `Delete the rows of "${tableName}" that hold value ${storedValueText(value)} in column "${columnName}"`;
396
+ if (cascade.length === 0) return rows;
397
+ return `${rows}, and the rows of ${cascade.map(({ table }) => `"${table}"`).join(", ")} that reference them`;
398
+ }
399
+ /** Deletes the rows that hold `value`, after the rows of each `cascade` table that reference them: the runner turns foreign keys off, so no declared cascade runs. */
400
+ function deleteRows(tableName, columnName, value, cascade) {
401
+ return {
402
+ id: `deleteRows.${tableName}.${columnName}.${idText(value)}`,
403
+ label: deleteRowsLabel(tableName, columnName, value, cascade),
404
+ operationClass: "destructive",
405
+ target: {
406
+ id: "sqlite",
407
+ details: buildTargetDetails("column", columnName, tableName)
408
+ },
409
+ precheck: [],
410
+ execute: [...cascade.map((foreignKey) => cascadeStep(tableName, columnName, value, foreignKey)), step(`delete the rows of "${tableName}" that hold value ${storedValueText(value)} in column "${columnName}"`, `DELETE FROM ${quoteIdentifier(tableName)} WHERE ${quoteIdentifier(columnName)} = ?1`, [value])],
411
+ postcheck: [valueAbsentCheck(tableName, columnName, value)]
412
+ };
413
+ }
414
+ function pathParts(path) {
415
+ const last = path.steps.at(-1);
416
+ if (last === void 0) throw new InternalError("A stored value path ends at a selector");
417
+ return {
418
+ reach: path.steps.slice(0, -1),
419
+ last
420
+ };
421
+ }
422
+ /** Whether the JSON text `value` is the JSON form of `stored`, bound as parameter `param`. */
423
+ function isStoredValue(value, stored, param) {
424
+ return `(json_type(${value}) ${typeof stored === "string" ? `= 'text'` : `IN ('integer', 'real')`} AND (${value} ->> '$') = ${param})`;
425
+ }
426
+ function memberHolds(object, name, stored, param) {
427
+ return `(json_type(${object}) = 'object' AND ${isStoredValue(`(${object} -> ${memberPath(name)})`, stored, param)})`;
428
+ }
429
+ /** Whether the JSON text of `column` holds `stored`, bound as parameter `param`, at the end of `path`. */
430
+ function holdsAtPath(column, path, stored, param) {
431
+ const { reach, last } = pathParts(path);
432
+ return jsonMatches(column, reach, (value, depth) => last.kind === "member" ? memberHolds(value, last.name, stored, param) : someChild(value, depth, (child) => isStoredValue(child, stored, param)));
433
+ }
434
+ /** The JSON text that sets the value at the end of `path` that equals `?1` to `replacement`, or, when `replacement` is undefined, removes it from a list or removes the member of an object that holds it. */
435
+ function rewriteAtPath(column, path, stored, replacement) {
436
+ const { reach, last } = pathParts(path);
437
+ if (last.kind === "member") return jsonRewrite(column, reach, (object) => `CASE WHEN ${memberHolds(object, last.name, stored, "?1")} THEN json_set(${object}, ${memberPath(last.name)}, ${replacement ?? "json('null')"}) ELSE ${object} END`);
438
+ return jsonRewrite(column, reach, (container, depth) => replacement === void 0 ? rewrittenChildren(container, depth, (child) => child, (child) => `NOT ${isStoredValue(child, stored, "?1")}`) : rewrittenChildren(container, depth, (child) => `CASE WHEN ${isStoredValue(child, stored, "?1")} THEN json_quote(${replacement}) ELSE ${child} END`));
439
+ }
440
+ function atPath(path, tableName, columnName) {
441
+ return `at path ${JSON.stringify(path.text)} in column "${columnName}" of "${tableName}"`;
442
+ }
443
+ function valueAbsentAtPathCheck(tableName, columnName, value, path) {
444
+ return step(`verify no row holds value ${storedValueText(value)} ${atPath(path, tableName, columnName)}`, `SELECT NOT EXISTS (SELECT 1 FROM ${quoteIdentifier(tableName)} WHERE ${holdsAtPath(quoteIdentifier(columnName), path, value, "?1")}) AS result`, [value]);
445
+ }
446
+ /** The condition and parameters that find the rows of a column that hold a stored value, at `path` inside its JSON when it is given. */
447
+ function holdingStoredValue(columnName, storedValue, path) {
448
+ const column = quoteIdentifier(columnName);
449
+ if (path === void 0) return {
450
+ condition: `${column} = ?1`,
451
+ params: [storedValue]
452
+ };
453
+ const parsed = parseJsonPath(path);
454
+ if (!parsed.ok) throw new InternalError(`A stored value path is a JSON path: ${parsed.failure}`);
455
+ return {
456
+ condition: holdsAtPath(column, parsed.value, storedValue, "?1"),
457
+ params: [storedValue]
458
+ };
459
+ }
460
+ function replaceStoredValueAtPath(tableName, columnName, from, to, path) {
461
+ const column = quoteIdentifier(columnName);
462
+ const place = atPath(path, tableName, columnName);
463
+ return {
464
+ id: `replaceStoredValue.${tableName}.${columnName}.${path.text}.${idText(from)}`,
465
+ label: `Replace value ${storedValueText(from)} with ${storedValueText(to)} ${place}`,
466
+ operationClass: "widening",
467
+ target: {
468
+ id: "sqlite",
469
+ details: buildTargetDetails("column", columnName, tableName)
470
+ },
471
+ precheck: [],
472
+ execute: [step(`replace value ${storedValueText(from)} with ${storedValueText(to)} ${place}`, `UPDATE ${quoteIdentifier(tableName)} SET ${column} = ${rewriteAtPath(column, path, from, "?2")} WHERE ${holdsAtPath(column, path, from, "?1")}`, [from, to])],
473
+ postcheck: [valueAbsentAtPathCheck(tableName, columnName, from, path)]
474
+ };
475
+ }
476
+ /**
477
+ * Removes a stored value inside JSON: takes it out of a list, or removes its member from an object,
478
+ * when `path` ends at a wildcard, else sets the member to JSON `null`. When the member takes no
479
+ * null, the check fails while a row holds the value.
480
+ */
481
+ function removeStoredValueAtPath(tableName, columnName, value, path, nullable, mark) {
482
+ const column = quoteIdentifier(columnName);
483
+ const place = atPath(path, tableName, columnName);
484
+ const holds = holdsAtPath(column, path, value, "?1");
485
+ const required = pathParts(path).last.kind === "member" && !nullable;
486
+ return {
487
+ id: `removeStoredValue.${tableName}.${columnName}.${path.text}.${idText(value)}`,
488
+ label: `Remove value ${storedValueText(value)} ${place}`,
489
+ operationClass: "destructive",
490
+ target: {
491
+ id: "sqlite",
492
+ details: buildTargetDetails("column", columnName, tableName)
493
+ },
494
+ precheck: required ? [{
495
+ ...step(`ensure no row holds ${storedValueText(value)} ${place}, a member that takes no null`, `SELECT NOT EXISTS (SELECT 1 FROM ${quoteIdentifier(tableName)} WHERE ${holds}) AS result`, [value]),
496
+ ...mark === void 0 ? {} : { meta: rowsHoldingValueMeta({
497
+ ...mark,
498
+ table: tableName,
499
+ column: columnName,
500
+ storedValue: value,
501
+ path: path.text
502
+ }) }
503
+ }] : [],
504
+ execute: [step(`remove value ${storedValueText(value)} ${place}`, `UPDATE ${quoteIdentifier(tableName)} SET ${column} = ${rewriteAtPath(column, path, value, void 0)} WHERE ${holds}`, [value])],
505
+ postcheck: [valueAbsentAtPathCheck(tableName, columnName, value, path)]
506
+ };
507
+ }
508
+ function buildCreateIndexSql(tableName, indexName, columns, unique = false) {
509
+ return `CREATE ${unique ? "UNIQUE " : ""}INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} (${columns.map(quoteIdentifier).join(", ")})`;
510
+ }
511
+ function buildDropIndexSql(indexName) {
512
+ return `DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`;
513
+ }
514
+ async function tableExistsSteps(lowerer, tableName) {
515
+ const checks = tableExistsAst(tableName);
516
+ return {
517
+ present: await lowerer.lowerToExecuteRequest(checks.tablePresent()),
518
+ absent: await lowerer.lowerToExecuteRequest(checks.tableAbsent())
519
+ };
520
+ }
521
+ /**
522
+ * Renders the body of a `CREATE TABLE <name> ( … )` statement from a flat
523
+ * `SqliteTableSpec`. SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT` form is
524
+ * inline on the column; the table-level PRIMARY KEY clause is emitted only
525
+ * when no column carries `inlineAutoincrementPrimaryKey`.
526
+ */
527
+ function renderCreateTableSql(tableName, spec, defaultClauses) {
528
+ const columnDefs = spec.columns.map((column, index) => renderColumnDefinition(column, defaultClauses[index] ?? ""));
529
+ const constraintDefs = [];
530
+ const hasInlinePk = spec.columns.some((c) => c.inlineAutoincrementPrimaryKey);
531
+ if (spec.primaryKey && !hasInlinePk) constraintDefs.push(`PRIMARY KEY (${spec.primaryKey.columns.map(quoteIdentifier).join(", ")})`);
532
+ for (const u of spec.uniques ?? []) {
533
+ const name = u.name ? `CONSTRAINT ${quoteIdentifier(u.name)} ` : "";
534
+ constraintDefs.push(`${name}UNIQUE (${u.columns.map(quoteIdentifier).join(", ")})`);
535
+ }
536
+ for (const fk of spec.foreignKeys ?? []) {
537
+ const clause = renderForeignKeyClause(fk);
538
+ if (clause) constraintDefs.push(clause);
539
+ }
540
+ const allDefs = [...columnDefs, ...constraintDefs];
541
+ return `CREATE TABLE ${quoteIdentifier(tableName)} (\n ${allDefs.join(",\n ")}\n)`;
542
+ }
543
+ function renameTableViaName(toName) {
544
+ return `_prisma_rename_${toName}`;
545
+ }
546
+ function renameChangesOnlyCase(fromName, toName) {
547
+ return sqliteIdentifiersCollide(fromName, toName);
548
+ }
549
+ /**
550
+ * SQLite takes names that differ only in the case of ASCII letters for the
551
+ * same name, so such a rename (`userProfile` to `UserProfile`) is refused as
552
+ * "already exists" when done in one statement. It goes through a temporary name.
553
+ */
554
+ function renameTableSteps(fromName, toName) {
555
+ const from = quoteIdentifier(fromName);
556
+ const to = quoteIdentifier(toName);
557
+ if (!renameChangesOnlyCase(fromName, toName)) return [step(`rename table "${fromName}" to "${toName}"`, `ALTER TABLE ${from} RENAME TO ${to}`)];
558
+ const viaName = renameTableViaName(toName);
559
+ const via = quoteIdentifier(viaName);
560
+ return [step(`rename table "${fromName}" to "${viaName}" (SQLite table names are case-insensitive)`, `ALTER TABLE ${from} RENAME TO ${via}`), step(`rename table "${viaName}" to "${toName}"`, `ALTER TABLE ${via} RENAME TO ${to}`)];
561
+ }
562
+ /** The table a rebuild of `tableName` creates, copies into, and renames to `tableName`. */
563
+ function rebuiltTableName(tableName) {
564
+ return `_prisma_new_${tableName}`;
565
+ }
566
+ async function recreateTable(args, lowerer) {
567
+ const { tableName, contractTable, schemaColumnNames, indexes, summary, postchecks, operationClass, copyExpressions = {}, temporaryValues = {}, retypedColumns = [] } = args;
568
+ refuseEarlierColumnSpecs("recreateTable", tableName, contractTable.columns);
569
+ const tempName = rebuiltTableName(tableName);
570
+ const liveSet = new Set(schemaColumnNames);
571
+ const convertedBy = (column) => Object.hasOwn(copyExpressions, column) ? copyExpressions[column] : void 0;
572
+ const copiedFrom = (column) => convertedBy(column) ?? (Object.hasOwn(temporaryValues, column) ? temporaryValues[column] : void 0);
573
+ const sharedColumns = contractTable.columns.filter((c) => liveSet.has(c.name) || copiedFrom(c.name) !== void 0).map((c) => c.name);
574
+ const columnList = sharedColumns.map(quoteIdentifier).join(", ");
575
+ const selectList = sharedColumns.map((column) => copiedFrom(column) ?? quoteIdentifier(column)).join(", ");
576
+ const indexStatements = indexes.map((idx) => ({
577
+ description: `recreate index "${idx.name}" on "${tableName}"`,
578
+ sql: buildCreateIndexSql(tableName, idx.name, idx.columns)
579
+ }));
580
+ const conversions = Object.fromEntries(sharedColumns.flatMap((column) => {
581
+ const expression = convertedBy(column);
582
+ return expression === void 0 ? [] : [[column, expression]];
583
+ }));
584
+ const copyStep = sharedColumns.length > 0 ? [{
585
+ ...step(`copy data from "${tableName}" to "${tempName}"`, `INSERT INTO ${quoteIdentifier(tempName)} (${columnList}) SELECT ${selectList} FROM ${quoteIdentifier(tableName)}`),
586
+ ...Object.keys(conversions).length === 0 ? {} : { meta: { conversionCopy: {
587
+ table: tableName,
588
+ expressions: conversions
589
+ } } }
590
+ }] : [];
591
+ const defaultClauses = await renderSpecDefaults(contractTable, tableName, lowerer);
592
+ const clauseByColumn = new Map(contractTable.columns.map((column, index) => [column.name, defaultClauses[index] ?? ""]));
593
+ const tableSteps = await tableExistsSteps(lowerer, tableName);
594
+ const tempSteps = await tableExistsSteps(lowerer, tempName);
595
+ return {
596
+ id: `recreateTable.${tableName}`,
597
+ label: `Recreate table ${tableName}`,
598
+ summary,
599
+ operationClass,
600
+ target: {
601
+ id: "sqlite",
602
+ details: buildTargetDetails("table", tableName)
603
+ },
604
+ precheck: [
605
+ step(`ensure table "${tableName}" exists`, tableSteps.present.sql, tableSteps.present.params, expectPresent(`table "${tableName}"`)),
606
+ step(`ensure temp table "${tempName}" does not exist`, tempSteps.absent.sql, tempSteps.absent.params, expectAbsent(`temp table "${tempName}"`)),
607
+ sourceColumnsCheck(tableName, schemaColumnNames)
608
+ ],
609
+ execute: [
610
+ step(`create new table "${tempName}" with desired schema`, renderCreateTableSql(tempName, contractTable, defaultClauses)),
611
+ ...copyStep,
612
+ step(`drop old table "${tableName}"`, `DROP TABLE ${quoteIdentifier(tableName)}`),
613
+ step(`rename "${tempName}" to "${tableName}"`, `ALTER TABLE ${quoteIdentifier(tempName)} RENAME TO ${quoteIdentifier(tableName)}`),
614
+ ...indexStatements
615
+ ],
616
+ postcheck: [
617
+ step(`verify table "${tableName}" exists`, tableSteps.present.sql, tableSteps.present.params, expectPresent(`table "${tableName}"`)),
618
+ step(`verify temp table "${tempName}" is gone`, tempSteps.absent.sql, tempSteps.absent.params, expectAbsent(`temp table "${tempName}"`)),
619
+ rebuiltTableCheck(tableName, renderCreateTableSql(tableName, contractTable, defaultClauses)),
620
+ ...postchecks.flatMap((check) => "sql" in check ? [markedStep(tableName, check)] : defaultPostcheck(tableName, check, clauseByColumn.get(check.columnDefault))),
621
+ ...contractTable.columns.flatMap((column) => {
622
+ const by = Object.hasOwn(conversions, column.name) ? "conversion" : retypedColumns.includes(column.name) ? "cast" : void 0;
623
+ return by === void 0 ? [] : [{
624
+ ...storageClassCheck(tableName, column),
625
+ meta: convertedColumnMeta(tableName, column.name, by)
626
+ }];
627
+ })
628
+ ]
629
+ };
630
+ }
631
+ /**
632
+ * Checks that the table has exactly the columns the rebuild reads, the ones it copies and the ones it
633
+ * leaves out. The rebuild copies only the columns it knows, so on a table with another column, such
634
+ * as one a later migration added, it would drop that column and its values.
635
+ */
636
+ function sourceColumnsCheck(tableName, columns) {
637
+ const info = `pragma_table_info('${escapeLiteral(tableName)}')`;
638
+ const named = columns.length === 0 ? "" : ` AND (SELECT COUNT(*) FROM ${info} WHERE name IN (${quoteSqlList(columns)})) = ${columns.length}`;
639
+ return {
640
+ description: `ensure table "${tableName}" has exactly the columns the rebuild copies or leaves out (${columns.join(", ")})`,
641
+ sql: `SELECT (SELECT COUNT(*) FROM ${info}) = ${columns.length}${named}`
642
+ };
643
+ }
644
+ /**
645
+ * Checks that the table is stored as the statement the rebuild writes. SQLite keeps a table's
646
+ * `CREATE TABLE` text as written, and renaming the rebuilt table only replaces its name, so this holds
647
+ * once the rebuild ran and not before, whatever text an earlier table had. It is the only check of
648
+ * what SQLite keeps in that text alone, such as `AUTOINCREMENT`.
649
+ */
650
+ function rebuiltTableCheck(tableName, statement) {
651
+ return {
652
+ description: `verify "${tableName}" is stored as the rebuilt table`,
653
+ sql: `SELECT (SELECT sql FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}') = '${escapeLiteral(statement)}'`
654
+ };
655
+ }
656
+ function markedStep(tableName, check) {
657
+ const { requiredColumn, ...step } = check;
658
+ const meta = { ...requiredColumn === void 0 ? {} : requiredColumnMeta(tableName, requiredColumn.column, requiredColumn.reason) };
659
+ return Object.keys(meta).length === 0 ? step : {
660
+ ...step,
661
+ meta
662
+ };
663
+ }
664
+ /**
665
+ * The storage classes SQLite keeps a value in once a column of `typeSql` has taken it: the column's
666
+ * type affinity converts what it can, so a value of another class is one it could not convert.
667
+ * See https://www.sqlite.org/datatype3.html#determination_of_column_affinity.
668
+ */
669
+ function affinityStorageClasses(typeSql) {
670
+ const declared = typeSql.toUpperCase();
671
+ if (declared.includes("INT")) return ["integer"];
672
+ if ([
673
+ "CHAR",
674
+ "CLOB",
675
+ "TEXT"
676
+ ].some((part) => declared.includes(part))) return ["text"];
677
+ if (declared === "" || declared.includes("BLOB")) return ["blob"];
678
+ if ([
679
+ "REAL",
680
+ "FLOA",
681
+ "DOUB"
682
+ ].some((part) => declared.includes(part))) return ["real"];
683
+ return ["integer", "real"];
684
+ }
685
+ /**
686
+ * The check that the copy into a rebuilt table converted every value of a retyped column to the
687
+ * column's new type. SQLite keeps a value it cannot convert in its old storage class, so a value of
688
+ * any other class than the column's affinity keeps fails the check.
689
+ */
690
+ function storageClassCheck(tableName, column) {
691
+ const classes = ["null", ...affinityStorageClasses(column.typeSql)].map((storageClass) => `'${storageClass}'`).join(", ");
692
+ return {
693
+ description: `verify every value of "${column.name}" on "${tableName}" is stored as ${column.typeSql}`,
694
+ sql: `SELECT NOT EXISTS (SELECT 1 FROM ${quoteIdentifier(tableName)} WHERE typeof(${quoteIdentifier(column.name)}) NOT IN (${classes}))`
695
+ };
696
+ }
697
+ /** What a step's `meta.conversionCopy` holds in an `ops.json`. */
698
+ const ConversionCopyJson = type({
699
+ "+": "reject",
700
+ table: "string",
701
+ expressions: "Record<string, string>"
702
+ });
703
+ const ConversionCopyMeta = type({ conversionCopy: ConversionCopyJson });
704
+ /**
705
+ * The table a rebuild's copy step reads and the copy expression of each column its conversions
706
+ * convert, when the step converts any: an error of the step may be an error of one of them.
707
+ */
708
+ function conversionCopyOf(step) {
709
+ const meta = ConversionCopyMeta(step.meta ?? {});
710
+ return meta instanceof type.errors ? void 0 : meta.conversionCopy;
711
+ }
712
+ function renderSpecDefaults(spec, tableName, lowerer) {
713
+ return Promise.all(spec.columns.map((column) => renderSpecDefault$1(column, tableName, lowerer)));
714
+ }
715
+ /**
716
+ * Checks the column's default is the text of its `DEFAULT …` clause. SQLite's
717
+ * `pragma_table_info.dflt_value` strips the outer parentheses of an expression
718
+ * default, so `(strftime('%Y-%m-%dT%H:%M:%fZ','now'))` is stored as `strftime('%Y-%m-%dT%H:%M:%fZ','now')`; they are
719
+ * stripped here too.
720
+ */
721
+ function defaultPostcheck(tableName, check, clause) {
722
+ if (clause === void 0 || !clause.startsWith("DEFAULT ")) return [];
723
+ const expectedRaw = stripOuterParens(clause.slice(8));
724
+ return [{
725
+ description: check.description,
726
+ sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(check.columnDefault)}' AND dflt_value = '${escapeLiteral(expectedRaw)}'`
727
+ }];
728
+ }
729
+ /**
730
+ * Build a one-line summary of a recreate-table operation from the schema-diff
731
+ * issues that triggered it. Lives next to `recreateTable` so the planner
732
+ * (which has the issues) can produce the same description the factory
733
+ * used to build inline. Keeping the formatting target-side keeps
734
+ * `RecreateTableCall` issue-free at the IR layer. `SchemaDiffIssue` carries
735
+ * no rendered message, so this renders one from each issue's path.
736
+ */
737
+ function buildRecreateSummary(tableName, issues) {
738
+ return `Recreates table ${tableName} to apply schema changes: ${issues.map((i) => i.path.join("/")).join("; ")}`;
739
+ }
740
+ function nodeKindOf(issue) {
741
+ const node = issue.expected ?? issue.actual;
742
+ if (node === void 0) return void 0;
743
+ return blindCast(node).nodeKind;
744
+ }
745
+ /**
746
+ * Returns the columns the contract expects as the table's primary key. Picks
747
+ * up SQLite's inline `INTEGER PRIMARY KEY AUTOINCREMENT` form when no
748
+ * explicit `primaryKey` clause is set on the spec.
749
+ */
750
+ function expectedPrimaryKeyColumns(spec) {
751
+ if (spec.primaryKey) return spec.primaryKey.columns;
752
+ const inlinePk = spec.columns.find((c) => c.inlineAutoincrementPrimaryKey);
753
+ return inlinePk ? [inlinePk.name] : [];
754
+ }
755
+ /** The text `pragma_foreign_key_list` reports for a referential action; SQLite reads an absent action as `NO ACTION`. */
756
+ function referentialActionText(action) {
757
+ return REFERENTIAL_ACTION_SQL[action ?? "noAction"];
758
+ }
759
+ function quoteSqlList(values) {
760
+ return values.map((v) => `'${escapeLiteral(v)}'`).join(", ");
761
+ }
762
+ /**
763
+ * A condition on the index aliased `l`: it covers exactly these columns. Order is not checked, because SQLite identifies a unique index by its column set.
764
+ */
765
+ function indexCoversExactly(columns) {
766
+ return `(SELECT COUNT(*) FROM pragma_index_info(l.name)) = ${columns.length} AND (SELECT COUNT(*) FROM pragma_index_info(l.name) WHERE name IN (${quoteSqlList(columns)})) = ${columns.length}`;
767
+ }
768
+ function columnNameFromNode(issue) {
769
+ const node = issue.expected ?? issue.actual;
770
+ if (node === void 0) return void 0;
771
+ return blindCast(node).name;
772
+ }
773
+ /**
774
+ * A column-default issue's own node has no back-reference to its owning
775
+ * column — it's a transient child built by `SqlColumnIR.children()`. The
776
+ * column's id (`column:<name>`) is always the diff path's second-to-last
777
+ * segment for a default issue (`[..., tableId, columnId, 'default']`), so
778
+ * the name is recovered from the path rather than the node.
779
+ */
780
+ function columnNameFromDefaultIssuePath(issue) {
781
+ const columnId = issue.path[issue.path.length - 2];
782
+ if (columnId === void 0) return void 0;
783
+ return columnId.startsWith("column:") ? columnId.slice(7) : columnId;
784
+ }
785
+ /**
786
+ * Compares the declared type with `typeSql`: exactly for a data type named by its catalog text, as
787
+ * verify compares it (ADR 273), and without case otherwise.
788
+ */
789
+ function declaredTypeMatches(expected, typeSql) {
790
+ return expected.catalogText !== void 0 ? `type = '${escapeLiteral(typeSql)}'` : `LOWER(type) = '${escapeLiteral(typeSql.toLowerCase())}'`;
791
+ }
792
+ /**
793
+ * Per-issue postchecks verifying the recreated table's shape against the
794
+ * expected spec. Column-level issues (`sql-column` `not-equal`,
795
+ * `sql-column-default` any reason) emit one targeted check each;
796
+ * constraint-level issues (`sql-primary-key`, `sql-unique`, `sql-foreign-key`,
797
+ * any reason) emit one `pragma_*`-driven check per declared constraint in the
798
+ * expected spec, so a recreated table with the right columns but the wrong
799
+ * PK / unique / FK shape fails the postcheck instead of passing silently.
800
+ * Exported so the planner can pre-build the list at construction time and
801
+ * `RecreateTableCall` doesn't have to carry `SchemaDiffIssue` objects through
802
+ * to render time.
803
+ */
804
+ function buildRecreatePostchecks(tableName, issues, spec, copiedColumns = /* @__PURE__ */ new Set(), backfilledColumns = /* @__PURE__ */ new Set()) {
805
+ const checks = [];
806
+ const t = escapeLiteral(tableName);
807
+ const byName = new Map(spec.columns.map((c) => [c.name, c]));
808
+ let hasPkIssue = false;
809
+ let hasUniqueIssue = false;
810
+ let hasFkIssue = false;
811
+ for (const issue of issues) {
812
+ const nodeKind = nodeKindOf(issue);
813
+ if (nodeKind === RelationalSchemaNodeKind.column && issueOutcome(issue) === "not-found") {
814
+ const columnName = columnNameFromNode(issue);
815
+ const column = columnName === void 0 ? void 0 : byName.get(columnName);
816
+ if (columnName === void 0 || column === void 0) continue;
817
+ const takesNoValue = !column.nullable && column.default === void 0 && !copiedColumns.has(columnName);
818
+ checks.push({
819
+ description: `verify "${columnName}" nullability on "${tableName}"`,
820
+ sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${escapeLiteral(columnName)}' AND "notnull" = ${column.nullable ? 0 : 1}`,
821
+ ...backfilledColumns.has(columnName) ? { requiredColumn: {
822
+ column: columnName,
823
+ reason: "backfillMissedRows"
824
+ } } : takesNoValue ? { requiredColumn: {
825
+ column: columnName,
826
+ reason: "newField"
827
+ } } : {}
828
+ });
829
+ continue;
830
+ }
831
+ if (nodeKind === RelationalSchemaNodeKind.column && issueOutcome(issue) === "not-equal") {
832
+ const columnName = columnNameFromNode(issue);
833
+ if (columnName === void 0) continue;
834
+ const c = escapeLiteral(columnName);
835
+ const expected = blindCast(issue.expected);
836
+ const actual = blindCast(issue.actual);
837
+ if (expected.nullable !== actual.nullable) checks.push({
838
+ description: `verify "${columnName}" nullability on "${tableName}"`,
839
+ sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND "notnull" = ${expected.nullable ? 0 : 1}`,
840
+ ...expected.nullable ? {} : { requiredColumn: {
841
+ column: columnName,
842
+ reason: backfilledColumns.has(columnName) ? "backfillMissedRows" : "nullValues"
843
+ } }
844
+ });
845
+ if (!sqlColumnTypesEqual(expected, actual)) {
846
+ const colSpec = byName.get(columnName);
847
+ if (colSpec) checks.push({
848
+ description: `verify "${columnName}" type on "${tableName}"`,
849
+ sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND ${declaredTypeMatches(expected, colSpec.typeSql)}`
850
+ });
851
+ }
852
+ continue;
853
+ }
854
+ if (nodeKind === RelationalSchemaNodeKind.columnDefault) {
855
+ const columnName = columnNameFromDefaultIssuePath(issue);
856
+ if (columnName === void 0) continue;
857
+ const c = escapeLiteral(columnName);
858
+ if (issueOutcome(issue) === "not-expected") {
859
+ checks.push({
860
+ description: `verify "${columnName}" has no default on "${tableName}"`,
861
+ sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value IS NULL`
862
+ });
863
+ continue;
864
+ }
865
+ if (byName.get(columnName)?.default !== void 0) checks.push({
866
+ description: `verify "${columnName}" default on "${tableName}"`,
867
+ columnDefault: columnName
868
+ });
869
+ continue;
870
+ }
871
+ if (nodeKind === RelationalSchemaNodeKind.primaryKey) hasPkIssue = true;
872
+ if (nodeKind === RelationalSchemaNodeKind.unique) hasUniqueIssue = true;
873
+ if (nodeKind === RelationalSchemaNodeKind.foreignKey) hasFkIssue = true;
874
+ }
875
+ if (hasPkIssue) {
876
+ const pkColumns = expectedPrimaryKeyColumns(spec);
877
+ const colCount = pkColumns.length;
878
+ if (colCount === 0) checks.push({
879
+ description: `verify "${tableName}" has no primary key`,
880
+ sql: `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = 0`
881
+ });
882
+ else checks.push({
883
+ description: `verify primary key on "${tableName}"`,
884
+ sql: `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = ${colCount} AND (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0 AND name IN (${quoteSqlList(pkColumns)})) = ${colCount}`
885
+ });
886
+ }
887
+ if (hasUniqueIssue) for (const u of spec.uniques ?? []) {
888
+ const description = u.name ? `verify unique constraint "${u.name}" on "${tableName}"` : `verify unique constraint (${u.columns.join(", ")}) on "${tableName}"`;
889
+ checks.push({
890
+ description,
891
+ sql: `SELECT EXISTS (SELECT 1 FROM pragma_index_list('${t}') l WHERE l."unique" = 1 AND ${indexCoversExactly(u.columns)})`
892
+ });
893
+ }
894
+ if (hasUniqueIssue) {
895
+ const expected = (spec.uniques ?? []).map((u) => `(${indexCoversExactly(u.columns)})`);
896
+ checks.push({
897
+ description: `verify "${tableName}" has no unique constraint besides the expected ones`,
898
+ sql: `SELECT NOT EXISTS (SELECT 1 FROM pragma_index_list('${t}') l WHERE l.origin = 'u' AND NOT (${expected.length === 0 ? "0" : expected.join(" OR ")}))`
899
+ });
900
+ }
901
+ if (hasFkIssue) {
902
+ for (const fk of spec.foreignKeys ?? []) {
903
+ const refTable = escapeLiteral(fk.references.table);
904
+ const colCount = fk.columns.length;
905
+ const tuples = fk.columns.map((from, i) => {
906
+ const to = fk.references.columns[i] ?? from;
907
+ return `('${escapeLiteral(from)}', '${escapeLiteral(to)}')`;
908
+ }).join(", ");
909
+ const description = `verify foreign key (${fk.columns.join(", ")}) → ${fk.references.table}(${fk.references.columns.join(", ")}) on "${tableName}"`;
910
+ checks.push({
911
+ description,
912
+ sql: `SELECT EXISTS (SELECT 1 FROM pragma_foreign_key_list('${t}') f WHERE f."table" = '${refTable}' AND f.on_delete = '${referentialActionText(fk.onDelete)}' AND f.on_update = '${referentialActionText(fk.onUpdate)}' GROUP BY f.id HAVING COUNT(*) = ${colCount} AND SUM(CASE WHEN (f."from", f."to") IN (${tuples}) THEN 1 ELSE 0 END) = ${colCount})`
913
+ });
914
+ }
915
+ const expected = spec.foreignKeys?.length ?? 0;
916
+ checks.push({
917
+ description: `verify "${tableName}" has exactly ${expected} foreign keys`,
918
+ sql: `SELECT (SELECT COUNT(DISTINCT id) FROM pragma_foreign_key_list('${t}')) = ${expected}`
919
+ });
920
+ }
921
+ return checks;
922
+ }
923
+ const MIGRATION_MODULE = "<migrations.module>";
924
+ var SqliteOpFactoryCallNode = class extends TsExpression {
925
+ /** The operations this call lowers to, in order: one, unless the call carries companions. */
926
+ toOps(lowerer) {
927
+ return [this.toOp(lowerer)];
928
+ }
929
+ importRequirements() {
930
+ return [{
931
+ moduleSpecifier: MIGRATION_MODULE,
932
+ symbol: this.factoryName
933
+ }];
934
+ }
935
+ freeze() {
936
+ Object.freeze(this);
937
+ }
938
+ };
939
+ /** Whether `call` is one of this target's calls, which lower through {@link SqliteOpFactoryCallNode.toOps}. */
940
+ function isSqliteOpFactoryCall(call) {
941
+ return call instanceof SqliteOpFactoryCallNode;
942
+ }
943
+ function renderDdlColumnDefault(def, sql) {
944
+ if (!def) return "";
945
+ if (def.kind === "literal") return `lit(${jsonToTsSource(def.value)})`;
946
+ return `fn(${sql.source(def.expression.text)})`;
947
+ }
948
+ function renderDdlColumnAsTsCall(column, sql) {
949
+ const opts = [];
950
+ if (column.notNull) opts.push("notNull: true");
951
+ if (column.primaryKey) opts.push("primaryKey: true");
952
+ if (column.default) opts.push(`default: ${renderDdlColumnDefault(column.default, sql)}`);
953
+ if (column.codecRef) opts.push(`codecRef: ${jsonToTsSource(column.codecRef)}`);
954
+ const optsStr = opts.length > 0 ? `, { ${opts.join(", ")} }` : "";
955
+ return `col(${jsonToTsSource(column.name)}, ${jsonToTsSource(column.type)}${optsStr})`;
956
+ }
957
+ function renderDdlConstraintAsTsCall(constraint) {
958
+ switch (constraint.kind) {
959
+ case "primary-key": {
960
+ const nameOpt = constraint.name ? `, { name: ${jsonToTsSource(constraint.name)} }` : "";
961
+ return `primaryKey(${jsonToTsSource(constraint.columns)}${nameOpt})`;
962
+ }
963
+ case "foreign-key": {
964
+ const opts = [];
965
+ if (constraint.name) opts.push(`name: ${jsonToTsSource(constraint.name)}`);
966
+ if (constraint.onDelete) opts.push(`onDelete: ${jsonToTsSource(constraint.onDelete)}`);
967
+ if (constraint.onUpdate) opts.push(`onUpdate: ${jsonToTsSource(constraint.onUpdate)}`);
968
+ const optsStr = opts.length > 0 ? `, { ${opts.join(", ")} }` : "";
969
+ return `foreignKey(${jsonToTsSource(constraint.columns)}, ${jsonToTsSource(constraint.refTable)}, ${jsonToTsSource(constraint.refColumns)}${optsStr})`;
970
+ }
971
+ case "unique": {
972
+ const nameOpt = constraint.name ? `, { name: ${jsonToTsSource(constraint.name)} }` : "";
973
+ return `unique(${jsonToTsSource(constraint.columns)}${nameOpt})`;
974
+ }
975
+ case "check-expression": throw sqliteError("CONTRACT.CONSTRAINT_INVALID", `The SQLite target does not support CHECK constraints (constraint "${constraint.name}"). The "checkConstraint" capability is Postgres-only — remove the "@@check" / "check()" declaration, or target Postgres.`, { meta: { constraintName: constraint.name } });
976
+ }
977
+ }
978
+ function constraintImportSymbols(constraints) {
979
+ if (!constraints || constraints.length === 0) return [];
980
+ const symbols = /* @__PURE__ */ new Set();
981
+ for (const c of constraints) if (c.kind === "primary-key") symbols.add("primaryKey");
982
+ else if (c.kind === "foreign-key") symbols.add("foreignKey");
983
+ else if (c.kind === "unique") symbols.add("unique");
984
+ return [...symbols];
985
+ }
986
+ function defaultImportSymbols(columns) {
987
+ const symbols = /* @__PURE__ */ new Set();
988
+ for (const col of columns) if (col.default?.kind === "literal") symbols.add("lit");
989
+ else if (col.default?.kind === "function") symbols.add("fn");
990
+ return [...symbols];
991
+ }
992
+ function columnShapesOf(columns, constraints) {
993
+ const primaryKey = constraints?.find((constraint) => constraint.kind === "primary-key");
994
+ return columns.map((column) => {
995
+ if (column.type.endsWith(" PRIMARY KEY AUTOINCREMENT")) return {
996
+ name: column.name,
997
+ typeSql: column.type.slice(0, -26),
998
+ notNull: false,
999
+ primaryKeyPosition: 1
1000
+ };
1001
+ return {
1002
+ name: column.name,
1003
+ typeSql: column.type,
1004
+ notNull: column.notNull === true,
1005
+ primaryKeyPosition: column.primaryKey ? 1 : (primaryKey?.columns.indexOf(column.name) ?? -1) + 1
1006
+ };
1007
+ });
1008
+ }
1009
+ var CreateTableCall = class extends SqliteOpFactoryCallNode {
1010
+ factoryName = "createTable";
1011
+ operationClass = "additive";
1012
+ tableName;
1013
+ columns;
1014
+ constraints;
1015
+ label;
1016
+ constructor(tableName, columns, constraints) {
1017
+ super();
1018
+ this.tableName = tableName;
1019
+ this.columns = Object.freeze([...columns]);
1020
+ this.constraints = constraints ? Object.freeze([...constraints]) : void 0;
1021
+ this.label = `Create table ${tableName}`;
1022
+ this.freeze();
1023
+ }
1024
+ async toOp(lowerer) {
1025
+ if (lowerer === void 0) throw sqliteError("MIGRATION.SQLITE_CONTROL_STACK_MISSING", `CreateTableCall.toOp: a DDL lowerer is required on the SQLite planner path (table "${this.tableName}"). Pass the control adapter to createSqliteMigrationPlanner.`, { meta: {
1026
+ factory: this.factoryName,
1027
+ tableName: this.tableName
1028
+ } });
1029
+ const ddlNode = createTable({
1030
+ table: this.tableName,
1031
+ columns: this.columns,
1032
+ ...ifDefined("constraints", this.constraints)
1033
+ });
1034
+ const statement = await lowerer.lowerToExecuteRequest(ddlNode);
1035
+ const tableName = this.tableName;
1036
+ const tableChecks = tableExistsAst(tableName);
1037
+ const absent = await lowerer.lowerToExecuteRequest(tableChecks.tableAbsent());
1038
+ const present = await lowerer.lowerToExecuteRequest(tableChecks.tablePresent());
1039
+ return {
1040
+ id: `table.${tableName}`,
1041
+ label: `Create table ${tableName}`,
1042
+ summary: `Creates table ${tableName} with required columns`,
1043
+ operationClass: "additive",
1044
+ target: {
1045
+ id: "sqlite",
1046
+ details: buildTargetDetails("table", tableName)
1047
+ },
1048
+ precheck: [step(`ensure table "${tableName}" does not exist`, absent.sql, absent.params, expectAbsent(`table "${tableName}"`))],
1049
+ execute: [{
1050
+ description: `create table "${tableName}"`,
1051
+ sql: statement.sql,
1052
+ params: statement.params ?? []
1053
+ }],
1054
+ postcheck: [step(`verify table "${tableName}" exists`, present.sql, present.params, expectPresent(`table "${tableName}"`)), tableColumnsCheck(tableName, columnShapesOf(this.columns, this.constraints))]
1055
+ };
1056
+ }
1057
+ renderTypeScript() {
1058
+ return this.#written().source;
1059
+ }
1060
+ #written() {
1061
+ const sql = createSqlTextSources(MIGRATION_MODULE);
1062
+ const columnsList = this.columns.map((column) => renderDdlColumnAsTsCall(column, sql)).join(", ");
1063
+ const constraintsList = this.constraints ? this.constraints.map(renderDdlConstraintAsTsCall).join(", ") : void 0;
1064
+ const opts = [];
1065
+ opts.push(`table: ${jsonToTsSource(this.tableName)}`);
1066
+ opts.push(`columns: [${columnsList}]`);
1067
+ if (constraintsList) opts.push(`constraints: [${constraintsList}]`);
1068
+ return {
1069
+ source: `this.createTable({ ${opts.join(", ")} })`,
1070
+ imports: sql.imports()
1071
+ };
1072
+ }
1073
+ importRequirements() {
1074
+ const req = [];
1075
+ if (this.columns.length > 0) {
1076
+ req.push({
1077
+ moduleSpecifier: MIGRATION_MODULE,
1078
+ symbol: "col"
1079
+ });
1080
+ for (const sym of defaultImportSymbols(this.columns)) req.push({
1081
+ moduleSpecifier: MIGRATION_MODULE,
1082
+ symbol: sym
1083
+ });
1084
+ }
1085
+ for (const sym of constraintImportSymbols(this.constraints)) req.push({
1086
+ moduleSpecifier: MIGRATION_MODULE,
1087
+ symbol: sym
1088
+ });
1089
+ req.push(...this.#written().imports);
1090
+ return req;
1091
+ }
1092
+ };
1093
+ var DropTableCall = class extends SqliteOpFactoryCallNode {
1094
+ factoryName = "dropTable";
1095
+ operationClass = "destructive";
1096
+ tableName;
1097
+ label;
1098
+ constructor(tableName) {
1099
+ super();
1100
+ this.tableName = tableName;
1101
+ this.label = `Drop table "${tableName}"`;
1102
+ this.freeze();
1103
+ }
1104
+ async toOp(lowerer) {
1105
+ if (lowerer === void 0) throw sqliteError("MIGRATION.SQLITE_CONTROL_STACK_MISSING", `DropTableCall.toOp: a lowerer is required on the SQLite planner path (table "${this.tableName}"). Pass the control adapter to createSqliteMigrationPlanner.`, { meta: {
1106
+ factory: this.factoryName,
1107
+ tableName: this.tableName
1108
+ } });
1109
+ const checks = tableExistsAst(this.tableName);
1110
+ const present = await lowerer.lowerToExecuteRequest(checks.tablePresent());
1111
+ const absent = await lowerer.lowerToExecuteRequest(checks.tableAbsent());
1112
+ return {
1113
+ id: `dropTable.${this.tableName}`,
1114
+ label: `Drop table "${this.tableName}"`,
1115
+ summary: `Drops table ${this.tableName} which is not in the contract`,
1116
+ operationClass: "destructive",
1117
+ target: {
1118
+ id: "sqlite",
1119
+ details: buildTargetDetails("table", this.tableName)
1120
+ },
1121
+ precheck: [step(`ensure table "${this.tableName}" exists`, present.sql, present.params, expectPresent(`table "${this.tableName}"`))],
1122
+ execute: [step(`drop table "${this.tableName}"`, `DROP TABLE ${quoteIdentifier(this.tableName)}`)],
1123
+ postcheck: [step(`verify table "${this.tableName}" is gone`, absent.sql, absent.params, expectAbsent(`table "${this.tableName}"`))]
1124
+ };
1125
+ }
1126
+ renderTypeScript() {
1127
+ return `this.dropTable({ table: ${jsonToTsSource(this.tableName)} })`;
1128
+ }
1129
+ importRequirements() {
1130
+ return [];
1131
+ }
1132
+ };
1133
+ /** The replaced indexes' drops, then their creates, since a create may take a dropped name. */
1134
+ function indexReplacementCalls(replacements) {
1135
+ return [...replacements.map(({ drop }) => drop), ...replacements.map(({ create }) => create)];
1136
+ }
1137
+ var RenameTableCall = class extends SqliteOpFactoryCallNode {
1138
+ factoryName = "renameTable";
1139
+ operationClass = "widening";
1140
+ oldTableName;
1141
+ /** The new name: the table's contract-side identity after the rename. */
1142
+ tableName;
1143
+ label;
1144
+ /** The indexes named after the old table, which SQLite cannot rename, so it replaces them. */
1145
+ indexReplacements;
1146
+ /**
1147
+ * The replacements' drops, then their creates. They run after the table rename and are never
1148
+ * rendered on their own.
1149
+ */
1150
+ companions;
1151
+ constructor(oldTableName, tableName, indexReplacements) {
1152
+ super();
1153
+ this.oldTableName = oldTableName;
1154
+ this.tableName = tableName;
1155
+ this.label = `Rename table ${oldTableName} to ${tableName}`;
1156
+ this.indexReplacements = Object.freeze([...indexReplacements]);
1157
+ this.companions = Object.freeze(indexReplacementCalls(indexReplacements));
1158
+ this.freeze();
1159
+ }
1160
+ /** The id of the operation this call lowers to. */
1161
+ get operationId() {
1162
+ return `renameTable.${this.oldTableName}`;
1163
+ }
1164
+ toOps(lowerer) {
1165
+ return [this.toOp(lowerer), ...this.companions.map((companion) => companion.toOp(lowerer))];
1166
+ }
1167
+ async toOp(lowerer) {
1168
+ if (lowerer === void 0) throw sqliteError("MIGRATION.SQLITE_CONTROL_STACK_MISSING", `RenameTableCall.toOp: a lowerer is required on the SQLite planner path (table "${this.oldTableName}"). Pass the control adapter to createSqliteMigrationPlanner.`, { meta: {
1169
+ factory: this.factoryName,
1170
+ tableName: this.oldTableName
1171
+ } });
1172
+ const fromChecks = tableExistsAst(this.oldTableName);
1173
+ const toChecks = tableExistsAst(this.tableName);
1174
+ const fromPresent = await lowerer.lowerToExecuteRequest(fromChecks.tablePresent());
1175
+ const onlyCase = renameChangesOnlyCase(this.oldTableName, this.tableName);
1176
+ const toAbsent = await lowerer.lowerToExecuteRequest(onlyCase ? toChecks.tableAbsent() : tableNameTakenAst(this.tableName).nameFree());
1177
+ const viaName = renameTableViaName(this.tableName);
1178
+ const viaAbsent = onlyCase ? await lowerer.lowerToExecuteRequest(tableExistsAst(viaName).tableAbsent()) : void 0;
1179
+ const toPresent = await lowerer.lowerToExecuteRequest(toChecks.tablePresent());
1180
+ const fromAbsent = await lowerer.lowerToExecuteRequest(fromChecks.tableAbsent());
1181
+ return {
1182
+ id: this.operationId,
1183
+ label: this.label,
1184
+ summary: `Renames table ${this.oldTableName} to ${this.tableName}, keeping its rows`,
1185
+ operationClass: "widening",
1186
+ target: {
1187
+ id: "sqlite",
1188
+ details: buildTargetDetails("table", this.tableName)
1189
+ },
1190
+ precheck: [
1191
+ step(`ensure table "${this.oldTableName}" exists`, fromPresent.sql, fromPresent.params, expectPresent(`table "${this.oldTableName}"`)),
1192
+ step(onlyCase ? `ensure table "${this.tableName}" does not exist` : `ensure no table or index is named "${this.tableName}" in any case`, toAbsent.sql, toAbsent.params, expectAbsent(onlyCase ? `table "${this.tableName}"` : `a table or index named "${this.tableName}" in any case`)),
1193
+ ...viaAbsent === void 0 ? [] : [step(`ensure table "${viaName}" does not exist (a rename that only changes case passes through this temporary name, because SQLite compares table names without case)`, viaAbsent.sql, viaAbsent.params, expectAbsent(`table "${viaName}"`))]
1194
+ ],
1195
+ execute: renameTableSteps(this.oldTableName, this.tableName),
1196
+ postcheck: [step(`verify table "${this.tableName}" exists`, toPresent.sql, toPresent.params, expectPresent(`table "${this.tableName}"`)), step(`verify table "${this.oldTableName}" no longer exists`, fromAbsent.sql, fromAbsent.params, expectAbsent(`table "${this.oldTableName}"`))]
1197
+ };
1198
+ }
1199
+ renderTypeScript() {
1200
+ return `...this.renameTable({ table: ${jsonToTsSource(this.oldTableName)}, to: ${jsonToTsSource(this.tableName)} })`;
1201
+ }
1202
+ importRequirements() {
1203
+ return [];
1204
+ }
1205
+ };
1206
+ var RenameColumnCall = class extends SqliteOpFactoryCallNode {
1207
+ factoryName = "renameColumn";
1208
+ operationClass = "widening";
1209
+ tableName;
1210
+ oldColumnName;
1211
+ /** The new name: the column's contract-side identity after the rename. */
1212
+ columnName;
1213
+ label;
1214
+ /** The indexes on the column whose wire names change, which SQLite cannot rename. */
1215
+ indexReplacements;
1216
+ /**
1217
+ * The replacements' drops, then their creates. They run after the column rename and are never
1218
+ * rendered on their own.
1219
+ */
1220
+ companions;
1221
+ constructor(tableName, oldColumnName, columnName, indexReplacements) {
1222
+ super();
1223
+ this.tableName = tableName;
1224
+ this.oldColumnName = oldColumnName;
1225
+ this.columnName = columnName;
1226
+ this.label = `Rename column ${oldColumnName} on ${tableName} to ${columnName}`;
1227
+ this.indexReplacements = Object.freeze([...indexReplacements]);
1228
+ this.companions = Object.freeze(indexReplacementCalls(indexReplacements));
1229
+ this.freeze();
1230
+ }
1231
+ toOps(lowerer) {
1232
+ return [this.toOp(lowerer), ...this.companions.map((companion) => companion.toOp(lowerer))];
1233
+ }
1234
+ async toOp(lowerer) {
1235
+ if (lowerer === void 0) throw sqliteError("MIGRATION.SQLITE_CONTROL_STACK_MISSING", `RenameColumnCall.toOp: a lowerer is required on the SQLite planner path (column "${this.oldColumnName}" on table "${this.tableName}"). Pass the control adapter to createSqliteMigrationPlanner.`, { meta: {
1236
+ factory: this.factoryName,
1237
+ tableName: this.tableName
1238
+ } });
1239
+ return renameColumn(this.tableName, this.oldColumnName, this.columnName, lowerer);
1240
+ }
1241
+ renderTypeScript() {
1242
+ return `...this.renameColumn({ table: ${jsonToTsSource(this.tableName)}, column: ${jsonToTsSource(this.oldColumnName)}, to: ${jsonToTsSource(this.columnName)} })`;
1243
+ }
1244
+ importRequirements() {
1245
+ return [];
1246
+ }
1247
+ };
1248
+ function refuseUnsafeCopyExpressions(tableName, option, expressions) {
1249
+ for (const [column, expression] of Object.entries(expressions)) {
1250
+ if (expression.kind !== "sql") continue;
1251
+ const refused = checkSqlExpressionText(expression.sql, SQLITE_QUOTING);
1252
+ if (refused === void 0) continue;
1253
+ const call = `recreateTable({ tableName: ${jsonToTsSource(tableName)} })`;
1254
+ throw sqliteError("MIGRATION.SQL_EXPRESSION_INVALID", `${call}: ${option}.${column} ${JSON.stringify(expression.sql)} holds ${refused}, which could end or extend the INSERT … SELECT statement it is written into`, {
1255
+ why: "A copy expression or a temporary value is written into the SELECT that copies the rows into the rebuilt table. The check refuses a semicolon, a SQL comment, dollar quoting, and a comma or a statement keyword outside parentheses, since each could end or extend that statement; it does not check that the text is valid SQL.",
1256
+ fix: `Write ${option}.${column} as one SQL expression over the old table's columns, such as CAST("${column}" AS INTEGER). If it holds a comma or a keyword such as FROM outside parentheses, wrap it in parentheses.`,
1257
+ meta: {
1258
+ call,
1259
+ field: `${option}.${column}`,
1260
+ expression: expression.sql,
1261
+ refused
1262
+ }
1263
+ });
1264
+ }
1265
+ }
1266
+ function refuseUnknownCopyExpressionColumns(tableName, contractTable, named) {
1267
+ const columns = contractTable.columns.map((column) => column.name);
1268
+ const unknown = [
1269
+ ...Object.keys(named.copyExpressions).map((key) => ({
1270
+ option: `copyExpressions.${key}`,
1271
+ key
1272
+ })),
1273
+ ...Object.keys(named.temporaryValues).map((key) => ({
1274
+ option: `temporaryValues.${key}`,
1275
+ key
1276
+ })),
1277
+ ...named.retypedColumns.map((key) => ({
1278
+ option: `retypedColumns entry ${JSON.stringify(key)}`,
1279
+ key
1280
+ }))
1281
+ ].find(({ key }) => !columns.includes(key));
1282
+ if (unknown === void 0) return;
1283
+ const call = `recreateTable({ tableName: ${jsonToTsSource(tableName)} })`;
1284
+ throw sqliteError("MIGRATION.COPY_EXPRESSION_COLUMN_UNKNOWN", `${call}: ${unknown.option} names no column of the new table. Its columns are ${columns.map((column) => JSON.stringify(column)).join(", ")}.`, {
1285
+ why: "Each key of copyExpressions and temporaryValues, and each entry of retypedColumns, names a column of the new table. One that names no column applies to nothing, so the column meant would be copied unchanged or left without a value, or its values would go unchecked.",
1286
+ fix: "Name a column in contractTable.columns, with the same letters and case.",
1287
+ meta: {
1288
+ call,
1289
+ key: unknown.key,
1290
+ columns
1291
+ }
1292
+ });
1293
+ }
1294
+ /**
1295
+ * A temporary value fills a column the old table does not have, and only that: for a column the
1296
+ * old table has it would replace every existing value, and a column with a copy expression is
1297
+ * already filled by its conversion.
1298
+ */
1299
+ function refuseMisplacedTemporaryValues(tableName, schemaColumnNames, copyExpressions, temporaryValues) {
1300
+ const call = `recreateTable({ tableName: ${jsonToTsSource(tableName)} })`;
1301
+ for (const column of Object.keys(temporaryValues)) {
1302
+ if (schemaColumnNames.includes(column)) throw sqliteError("MIGRATION.TEMPORARY_VALUE_INVALID", `${call}: temporaryValues.${column} names a column the old table already has, so the copy would replace every value of it.`, {
1303
+ why: "A temporary value fills a new column in the existing rows. A column the old table has keeps its values through the copy, or is converted by a copy expression.",
1304
+ fix: `Remove temporaryValues.${column}. To change the values of "${column}", write a conversion in copyExpressions.${column} instead.`,
1305
+ meta: {
1306
+ call,
1307
+ column,
1308
+ reason: "existingColumn"
1309
+ }
1310
+ });
1311
+ if (Object.hasOwn(copyExpressions, column)) throw sqliteError("MIGRATION.TEMPORARY_VALUE_INVALID", `${call}: "${column}" is named in both copyExpressions and temporaryValues, so it would be filled twice.`, {
1312
+ why: "A column is filled either by the conversion in copyExpressions or by a temporary value, not both.",
1313
+ fix: `Keep one of copyExpressions.${column} and temporaryValues.${column}.`,
1314
+ meta: {
1315
+ call,
1316
+ column,
1317
+ reason: "alsoConverted"
1318
+ }
1319
+ });
1320
+ }
1321
+ }
1322
+ function sqlOfSlots(slots) {
1323
+ return Object.fromEntries(Object.entries(slots).flatMap(([column, slot]) => {
1324
+ const sql = sqlOfSlot(slot);
1325
+ return sql === void 0 ? [] : [[column, sql]];
1326
+ }));
1327
+ }
1328
+ var RecreateTableCall = class extends SqliteOpFactoryCallNode {
1329
+ factoryName = "recreateTable";
1330
+ operationClass;
1331
+ tableName;
1332
+ contractTable;
1333
+ schemaColumnNames;
1334
+ indexes;
1335
+ summary;
1336
+ postchecks;
1337
+ label;
1338
+ /** The conversion each named column of the new table is copied through, in place of the live column. */
1339
+ copyExpressions;
1340
+ /** The value each named new column takes in the existing rows. */
1341
+ temporaryValues;
1342
+ /** The columns whose type changes; the rebuild checks each after its copy, as a conversion when it has a copy expression and as SQLite's cast otherwise. */
1343
+ retypedColumns;
1344
+ constructor(args) {
1345
+ super();
1346
+ refuseUnsafeCopyExpressions(args.tableName, "copyExpressions", args.copyExpressions ?? {});
1347
+ refuseUnsafeCopyExpressions(args.tableName, "temporaryValues", args.temporaryValues ?? {});
1348
+ refuseUnknownCopyExpressionColumns(args.tableName, args.contractTable, {
1349
+ copyExpressions: args.copyExpressions ?? {},
1350
+ temporaryValues: args.temporaryValues ?? {},
1351
+ retypedColumns: args.retypedColumns ?? []
1352
+ });
1353
+ refuseMisplacedTemporaryValues(args.tableName, args.schemaColumnNames, args.copyExpressions ?? {}, args.temporaryValues ?? {});
1354
+ this.copyExpressions = Object.freeze({ ...args.copyExpressions });
1355
+ this.temporaryValues = Object.freeze({ ...args.temporaryValues });
1356
+ this.retypedColumns = Object.freeze([...args.retypedColumns ?? []]);
1357
+ this.tableName = args.tableName;
1358
+ this.contractTable = args.contractTable;
1359
+ this.schemaColumnNames = args.schemaColumnNames;
1360
+ this.indexes = args.indexes;
1361
+ this.summary = args.summary;
1362
+ this.postchecks = args.postchecks;
1363
+ this.operationClass = args.operationClass;
1364
+ this.label = `Recreate table ${args.tableName}`;
1365
+ this.freeze();
1366
+ }
1367
+ async toOp(lowerer) {
1368
+ if (lowerer === void 0) throw sqliteError("MIGRATION.SQLITE_CONTROL_STACK_MISSING", `RecreateTableCall.toOp: a lowerer is required on the SQLite planner path (table "${this.tableName}"). Pass the control adapter to createSqliteMigrationPlanner.`, { meta: {
1369
+ factory: this.factoryName,
1370
+ tableName: this.tableName
1371
+ } });
1372
+ const copies = Object.entries(this.copyExpressions);
1373
+ if (copies.some(([, expression]) => isUnfilledSlot(expression))) return unfilledPlaceholderOperation(this.label);
1374
+ return recreateTable({
1375
+ tableName: this.tableName,
1376
+ contractTable: this.contractTable,
1377
+ schemaColumnNames: this.schemaColumnNames,
1378
+ indexes: this.indexes,
1379
+ summary: this.summary,
1380
+ postchecks: this.postchecks,
1381
+ operationClass: this.operationClass,
1382
+ retypedColumns: this.retypedColumns,
1383
+ ...copies.length === 0 ? {} : { copyExpressions: sqlOfSlots(this.copyExpressions) },
1384
+ ...Object.keys(this.temporaryValues).length === 0 ? {} : { temporaryValues: sqlOfSlots(this.temporaryValues) }
1385
+ }, lowerer);
1386
+ }
1387
+ #slotsSource(slots, sql) {
1388
+ return `{ ${Object.entries(slots).map(([column, expression]) => `${jsonToTsSource(column)}: ${slotSource(expression, sql)}`).join(", ")} }`;
1389
+ }
1390
+ renderTypeScript() {
1391
+ return this.#written().source;
1392
+ }
1393
+ importRequirements() {
1394
+ return [...Object.values(this.copyExpressions).some(isUnfilledSlot) ? [{
1395
+ moduleSpecifier: MIGRATION_MODULE,
1396
+ symbol: "placeholder"
1397
+ }] : [], ...this.#written().imports];
1398
+ }
1399
+ #written() {
1400
+ const sql = createSqlTextSources(MIGRATION_MODULE);
1401
+ return {
1402
+ source: `this.recreateTable(${tsObjectSource([
1403
+ ["tableName", jsonToTsSource(this.tableName)],
1404
+ ["contractTable", renderTableSpec(this.contractTable, sql)],
1405
+ ["schemaColumnNames", jsonToTsSource(this.schemaColumnNames)],
1406
+ ["indexes", jsonToTsSource(this.indexes)],
1407
+ ["summary", jsonToTsSource(this.summary)],
1408
+ ["postchecks", tsArraySource(this.postchecks.map(renderPostcheck))],
1409
+ ["operationClass", jsonToTsSource(this.operationClass)],
1410
+ ...Object.keys(this.copyExpressions).length === 0 ? [] : [["copyExpressions", this.#slotsSource(this.copyExpressions, sql)]],
1411
+ ...Object.keys(this.temporaryValues).length === 0 ? [] : [["temporaryValues", this.#slotsSource(this.temporaryValues, sql)]],
1412
+ ...this.retypedColumns.length === 0 ? [] : [["retypedColumns", jsonToTsSource(this.retypedColumns)]]
1413
+ ])})`,
1414
+ imports: sql.imports()
1415
+ };
1416
+ }
1417
+ };
1418
+ var AddColumnCall = class extends SqliteOpFactoryCallNode {
1419
+ factoryName = "addColumn";
1420
+ operationClass = "additive";
1421
+ tableName;
1422
+ columnName;
1423
+ column;
1424
+ label;
1425
+ constructor(tableName, column) {
1426
+ super();
1427
+ this.tableName = tableName;
1428
+ this.columnName = column.name;
1429
+ this.column = column;
1430
+ this.label = `Add column ${column.name} on ${tableName}`;
1431
+ this.freeze();
1432
+ }
1433
+ async toOp(lowerer) {
1434
+ if (lowerer === void 0) throw sqliteError("MIGRATION.SQLITE_CONTROL_STACK_MISSING", `AddColumnCall.toOp: a lowerer is required on the SQLite planner path (column "${this.column.name}" on table "${this.tableName}"). Pass the control adapter to createSqliteMigrationPlanner.`, { meta: {
1435
+ factory: this.factoryName,
1436
+ tableName: this.tableName,
1437
+ columnName: this.column.name
1438
+ } });
1439
+ return addColumn(this.tableName, this.column, lowerer);
1440
+ }
1441
+ renderTypeScript() {
1442
+ return this.#written().source;
1443
+ }
1444
+ importRequirements() {
1445
+ return this.#written().imports;
1446
+ }
1447
+ #written() {
1448
+ const sql = createSqlTextSources(MIGRATION_MODULE);
1449
+ return {
1450
+ source: `this.addColumn({ table: ${jsonToTsSource(this.tableName)}, column: ${renderColumnSpec(this.column, sql)} })`,
1451
+ imports: sql.imports()
1452
+ };
1453
+ }
1454
+ };
1455
+ var DropColumnCall = class extends SqliteOpFactoryCallNode {
1456
+ factoryName = "dropColumn";
1457
+ operationClass = "destructive";
1458
+ tableName;
1459
+ columnName;
1460
+ label;
1461
+ constructor(tableName, columnName) {
1462
+ super();
1463
+ this.tableName = tableName;
1464
+ this.columnName = columnName;
1465
+ this.label = `Drop column "${columnName}" from "${tableName}"`;
1466
+ this.freeze();
1467
+ }
1468
+ async toOp(lowerer) {
1469
+ if (lowerer === void 0) throw sqliteError("MIGRATION.SQLITE_CONTROL_STACK_MISSING", `DropColumnCall.toOp: a lowerer is required on the SQLite planner path (column "${this.columnName}" on table "${this.tableName}"). Pass the control adapter to createSqliteMigrationPlanner.`, { meta: {
1470
+ factory: this.factoryName,
1471
+ tableName: this.tableName,
1472
+ columnName: this.columnName
1473
+ } });
1474
+ const checks = columnExistsAst(this.tableName, this.columnName);
1475
+ const present = await lowerer.lowerToExecuteRequest(checks.columnPresent());
1476
+ const absent = await lowerer.lowerToExecuteRequest(checks.columnAbsent());
1477
+ return {
1478
+ id: `dropColumn.${this.tableName}.${this.columnName}`,
1479
+ label: `Drop column "${this.columnName}" from "${this.tableName}"`,
1480
+ summary: `Drops column ${this.columnName} on ${this.tableName} which is not in the contract`,
1481
+ operationClass: "destructive",
1482
+ target: {
1483
+ id: "sqlite",
1484
+ details: buildTargetDetails("column", this.columnName, this.tableName)
1485
+ },
1486
+ precheck: [step(`ensure column "${this.columnName}" exists on "${this.tableName}"`, present.sql, present.params, expectPresent(`column "${this.columnName}" on "${this.tableName}"`))],
1487
+ execute: [step(`drop column "${this.columnName}" from "${this.tableName}"`, dropColumnExecuteSql(this.tableName, this.columnName))],
1488
+ postcheck: [step(`verify column "${this.columnName}" is gone from "${this.tableName}"`, absent.sql, absent.params, expectAbsent(`column "${this.columnName}" on "${this.tableName}"`))]
1489
+ };
1490
+ }
1491
+ renderTypeScript() {
1492
+ return `this.dropColumn({ table: ${jsonToTsSource(this.tableName)}, column: ${jsonToTsSource(this.columnName)} })`;
1493
+ }
1494
+ importRequirements() {
1495
+ return [];
1496
+ }
1497
+ };
1498
+ var CreateIndexCall = class extends SqliteOpFactoryCallNode {
1499
+ factoryName = "createIndex";
1500
+ operationClass = "additive";
1501
+ tableName;
1502
+ indexName;
1503
+ columns;
1504
+ label;
1505
+ constructor(tableName, indexName, columns) {
1506
+ super();
1507
+ this.tableName = tableName;
1508
+ this.indexName = indexName;
1509
+ this.columns = columns;
1510
+ this.label = `Create index ${indexName} on ${tableName}`;
1511
+ this.freeze();
1512
+ }
1513
+ /** The id of the operation this call lowers to. */
1514
+ get operationId() {
1515
+ return `index.${this.tableName}.${this.indexName}`;
1516
+ }
1517
+ async toOp(lowerer) {
1518
+ if (lowerer === void 0) throw sqliteError("MIGRATION.SQLITE_CONTROL_STACK_MISSING", `CreateIndexCall.toOp: a lowerer is required on the SQLite planner path (index "${this.indexName}" on table "${this.tableName}"). Pass the control adapter to createSqliteMigrationPlanner.`, { meta: {
1519
+ factory: this.factoryName,
1520
+ tableName: this.tableName,
1521
+ indexName: this.indexName
1522
+ } });
1523
+ const checks = indexExistsAst(this.indexName);
1524
+ const absent = await lowerer.lowerToExecuteRequest(checks.indexAbsent());
1525
+ const present = await lowerer.lowerToExecuteRequest(checks.indexPresent());
1526
+ return {
1527
+ id: this.operationId,
1528
+ label: `Create index ${this.indexName} on ${this.tableName}`,
1529
+ summary: `Creates index ${this.indexName} on ${this.tableName}`,
1530
+ operationClass: "additive",
1531
+ target: {
1532
+ id: "sqlite",
1533
+ details: buildTargetDetails("index", this.indexName, this.tableName)
1534
+ },
1535
+ precheck: [step(`ensure index "${this.indexName}" is missing`, absent.sql, absent.params, expectAbsent(`index "${this.indexName}"`))],
1536
+ execute: [step(`create index "${this.indexName}"`, buildCreateIndexSql(this.tableName, this.indexName, this.columns))],
1537
+ postcheck: [step(`verify index "${this.indexName}" exists`, present.sql, present.params, expectPresent(`index "${this.indexName}"`)), indexDefinitionCheck(this.tableName, this.indexName, this.columns, false)]
1538
+ };
1539
+ }
1540
+ renderTypeScript() {
1541
+ return `this.createIndex({ table: ${jsonToTsSource(this.tableName)}, index: ${jsonToTsSource(this.indexName)}, columns: ${jsonToTsSource(this.columns)} })`;
1542
+ }
1543
+ importRequirements() {
1544
+ return [];
1545
+ }
1546
+ };
1547
+ var DropIndexCall = class extends SqliteOpFactoryCallNode {
1548
+ factoryName = "dropIndex";
1549
+ operationClass = "widening";
1550
+ tableName;
1551
+ indexName;
1552
+ label;
1553
+ constructor(tableName, indexName) {
1554
+ super();
1555
+ this.tableName = tableName;
1556
+ this.indexName = indexName;
1557
+ this.label = `Drop index ${indexName} on ${tableName}`;
1558
+ this.freeze();
1559
+ }
1560
+ /** The id of the operation this call lowers to. */
1561
+ get operationId() {
1562
+ return `dropIndex.${this.tableName}.${this.indexName}`;
1563
+ }
1564
+ async toOp(lowerer) {
1565
+ if (lowerer === void 0) throw sqliteError("MIGRATION.SQLITE_CONTROL_STACK_MISSING", `DropIndexCall.toOp: a lowerer is required on the SQLite planner path (index "${this.indexName}" on table "${this.tableName}"). Pass the control adapter to createSqliteMigrationPlanner.`, { meta: {
1566
+ factory: this.factoryName,
1567
+ tableName: this.tableName,
1568
+ indexName: this.indexName
1569
+ } });
1570
+ const checks = indexExistsAst(this.indexName);
1571
+ const present = await lowerer.lowerToExecuteRequest(checks.indexPresent());
1572
+ const absent = await lowerer.lowerToExecuteRequest(checks.indexAbsent());
1573
+ return {
1574
+ id: this.operationId,
1575
+ label: `Drop index ${this.indexName} on ${this.tableName}`,
1576
+ summary: `Drops index ${this.indexName} on ${this.tableName} which is not in the contract`,
1577
+ operationClass: "widening",
1578
+ target: {
1579
+ id: "sqlite",
1580
+ details: buildTargetDetails("index", this.indexName, this.tableName)
1581
+ },
1582
+ precheck: [step(`ensure index "${this.indexName}" exists`, present.sql, present.params, expectPresent(`index "${this.indexName}"`))],
1583
+ execute: [step(`drop index "${this.indexName}"`, buildDropIndexSql(this.indexName))],
1584
+ postcheck: [step(`verify index "${this.indexName}" is gone`, absent.sql, absent.params, expectAbsent(`index "${this.indexName}"`))]
1585
+ };
1586
+ }
1587
+ renderTypeScript() {
1588
+ return `this.dropIndex({ table: ${jsonToTsSource(this.tableName)}, index: ${jsonToTsSource(this.indexName)} })`;
1589
+ }
1590
+ importRequirements() {
1591
+ return [];
1592
+ }
1593
+ };
1594
+ function replaceStoredValueSource(tableName, columnName, from, to, codec, path) {
1595
+ return `this.replaceStoredValue({ ${[
1596
+ `table: ${jsonToTsSource(tableName)}`,
1597
+ `column: ${jsonToTsSource(columnName)}`,
1598
+ ...pathSource(path),
1599
+ `from: ${from}`,
1600
+ `to: ${to}`,
1601
+ ...codecRefSource(codec)
1602
+ ].join(", ")} })`;
1603
+ }
1604
+ function pathSource(path) {
1605
+ return path === void 0 ? [] : [`path: ${jsonToTsSource(path.text)}`];
1606
+ }
1607
+ function storedValuePlace(path, tableName, columnName) {
1608
+ return path === void 0 ? `in column "${columnName}" of "${tableName}"` : `at path ${JSON.stringify(path.text)} in column "${columnName}" of "${tableName}"`;
1609
+ }
1610
+ /**
1611
+ * The path a stored value call acts at inside JSON: it ends at a member name or at a list
1612
+ * wildcard, and the value is compared as a JSON value, so it takes no codec.
1613
+ */
1614
+ function requireValuePath(path, codec, factory, tableName, columnName) {
1615
+ if (path === void 0) return void 0;
1616
+ const location = columnCallLocation(tableName, columnName);
1617
+ const parsed = requirePath(path, factory, location);
1618
+ if (parsed.steps.length === 0) refusedArgument(factory, location, "path", `path ${JSON.stringify(path)} does not end at a member name or a wildcard ([*] or .*)`);
1619
+ if (codec !== void 0) refusedArgument(factory, location, "path", "path takes no codecRef: a value inside JSON is compared as a JSON value");
1620
+ return parsed;
1621
+ }
1622
+ function codecRefSource(codec) {
1623
+ return codec === void 0 ? [] : [`codecRef: ${jsonToTsSource(codec.codecRef)}`];
1624
+ }
1625
+ function requireStoredValue(value, factory, tableName, columnName, argument) {
1626
+ if (typeof value === "string" || typeof value === "number" && Number.isFinite(value)) return value;
1627
+ const got = value;
1628
+ throw sqliteError("CONTRACT.ARGUMENT_INVALID", `${factory}({ table: ${jsonToTsSource(tableName)}, column: ${jsonToTsSource(columnName)} }): ${argument} must be a string or a number; got ${typeof got === "number" || got === void 0 ? String(got) : JSON.stringify(got)}`, { meta: { what: `${factory} ${argument}` } });
1629
+ }
1630
+ /** Changes one stored value of a column to another, in every row that holds it, or at a path inside the JSON of the column. */
1631
+ var ReplaceStoredValueCall = class extends SqliteOpFactoryCallNode {
1632
+ factoryName = "replaceStoredValue";
1633
+ operationClass = "widening";
1634
+ tableName;
1635
+ columnName;
1636
+ from;
1637
+ to;
1638
+ /** The column's codec, which writes `from` and `to` as the database stores them. */
1639
+ codec;
1640
+ /** The path inside the column's JSON at which the value is replaced, compared as a JSON value. */
1641
+ path;
1642
+ label;
1643
+ constructor(tableName, columnName, from, to, codec, path) {
1644
+ super();
1645
+ this.codec = codec;
1646
+ this.tableName = tableName;
1647
+ this.columnName = columnName;
1648
+ this.from = requireStoredValue(from, this.factoryName, tableName, columnName, "from");
1649
+ this.to = requireStoredValue(to, this.factoryName, tableName, columnName, "to");
1650
+ this.path = requireValuePath(path, codec, this.factoryName, tableName, columnName);
1651
+ this.label = `Replace value ${storedValueText(from)} with ${storedValueText(to)} ${storedValuePlace(this.path, tableName, columnName)}`;
1652
+ this.freeze();
1653
+ }
1654
+ async toOp() {
1655
+ if (this.path !== void 0) return replaceStoredValueAtPath(this.tableName, this.columnName, this.from, this.to, this.path);
1656
+ return replaceStoredValue(this.tableName, this.columnName, await encodeStoredValue(this.from, this.codec), await encodeStoredValue(this.to, this.codec));
1657
+ }
1658
+ renderTypeScript() {
1659
+ return replaceStoredValueSource(this.tableName, this.columnName, jsonToTsSource(this.from), jsonToTsSource(this.to), this.codec, this.path);
1660
+ }
1661
+ importRequirements() {
1662
+ return [];
1663
+ }
1664
+ };
1665
+ /** Removes one stored value of a column by setting it to NULL in every row that holds it, or removes it at a path inside the JSON of the column. */
1666
+ var RemoveStoredValueCall = class extends SqliteOpFactoryCallNode {
1667
+ factoryName = "removeStoredValue";
1668
+ operationClass = "destructive";
1669
+ tableName;
1670
+ columnName;
1671
+ value;
1672
+ /** The column's codec, which writes `value` as the database stores it. */
1673
+ codec;
1674
+ /** The enum value whose stored value is removed, which the check that fails while rows of a required column hold it names. */
1675
+ enumValue;
1676
+ /** The path inside the column's JSON at which the value is removed, compared as a JSON value. */
1677
+ path;
1678
+ /** Whether the member at `path` takes JSON `null`; when it does not, the check fails while a row holds the value. */
1679
+ nullable;
1680
+ label;
1681
+ constructor(tableName, columnName, value, codec, enumValue, path, nullable) {
1682
+ super();
1683
+ this.codec = codec;
1684
+ this.enumValue = enumValue;
1685
+ this.tableName = tableName;
1686
+ this.columnName = columnName;
1687
+ this.value = requireStoredValue(value, this.factoryName, tableName, columnName, "value");
1688
+ this.path = requireValuePath(path, codec, this.factoryName, tableName, columnName);
1689
+ if (nullable !== void 0 && this.path === void 0) refusedArgument(this.factoryName, columnCallLocation(tableName, columnName), "nullable", "nullable needs a path: a column says itself whether it takes NULL");
1690
+ this.nullable = nullable === true;
1691
+ this.label = `Remove value ${storedValueText(value)} ${this.path === void 0 ? `from column "${columnName}" of "${tableName}"` : storedValuePlace(this.path, tableName, columnName)}`;
1692
+ this.freeze();
1693
+ }
1694
+ async toOp() {
1695
+ const mark = this.enumValue === void 0 ? void 0 : {
1696
+ enumValue: this.enumValue,
1697
+ value: this.value,
1698
+ ...this.codec === void 0 ? {} : { codecRef: this.codec.codecRef }
1699
+ };
1700
+ if (this.path !== void 0) return removeStoredValueAtPath(this.tableName, this.columnName, this.value, this.path, this.nullable, mark);
1701
+ return removeStoredValue(this.tableName, this.columnName, await encodeStoredValue(this.value, this.codec), mark);
1702
+ }
1703
+ renderTypeScript() {
1704
+ return `this.removeStoredValue({ ${[
1705
+ `table: ${jsonToTsSource(this.tableName)}`,
1706
+ `column: ${jsonToTsSource(this.columnName)}`,
1707
+ ...pathSource(this.path),
1708
+ `value: ${jsonToTsSource(this.value)}`,
1709
+ ...this.nullable ? ["nullable: true"] : [],
1710
+ ...codecRefSource(this.codec),
1711
+ ...this.enumValue === void 0 ? [] : [`enumValue: ${jsonToTsSource(this.enumValue)}`]
1712
+ ].join(", ")} })`;
1713
+ }
1714
+ importRequirements() {
1715
+ return [];
1716
+ }
1717
+ };
1718
+ /** Deletes the rows whose column holds one stored value. */
1719
+ var DeleteRowsCall = class extends SqliteOpFactoryCallNode {
1720
+ factoryName = "deleteRows";
1721
+ operationClass = "destructive";
1722
+ tableName;
1723
+ columnName;
1724
+ value;
1725
+ /** The column's codec, which writes `value` as the database stores it. */
1726
+ codec;
1727
+ /** The tables whose rows reference the deleted rows through a foreign key that cascades, deleted first. */
1728
+ cascade;
1729
+ label;
1730
+ constructor(tableName, columnName, value, codec, cascade = []) {
1731
+ super();
1732
+ this.codec = codec;
1733
+ this.tableName = tableName;
1734
+ this.columnName = columnName;
1735
+ this.value = requireStoredValue(value, this.factoryName, tableName, columnName, "value");
1736
+ this.cascade = cascade.map((foreignKey) => requireCascade(foreignKey, this.factoryName, columnCallLocation(tableName, columnName)));
1737
+ this.label = deleteRowsLabel(tableName, columnName, value, this.cascade);
1738
+ this.freeze();
1739
+ }
1740
+ async toOp() {
1741
+ return deleteRows(this.tableName, this.columnName, await encodeStoredValue(this.value, this.codec), this.cascade);
1742
+ }
1743
+ renderTypeScript() {
1744
+ return `this.deleteRows({ ${[
1745
+ `table: ${jsonToTsSource(this.tableName)}`,
1746
+ `column: ${jsonToTsSource(this.columnName)}`,
1747
+ `value: ${jsonToTsSource(this.value)}`,
1748
+ ...codecRefSource(this.codec),
1749
+ ...this.cascade.length === 0 ? [] : [`cascade: ${jsonToTsSource(this.cascade)}`]
1750
+ ].join(", ")} })`;
1751
+ }
1752
+ importRequirements() {
1753
+ return [];
1754
+ }
1755
+ };
1756
+ function requireCascade(foreignKey, factory, location) {
1757
+ const { columns, references } = foreignKey;
1758
+ return columns.length > 0 && columns.length === references.length ? {
1759
+ table: foreignKey.table,
1760
+ columns: [...columns],
1761
+ references: [...references]
1762
+ } : refusedArgument(factory, location, "cascade", `cascade of table ${JSON.stringify(foreignKey.table)} must name as many columns as references, and at least one`);
1763
+ }
1764
+ function columnCallLocation(tableName, columnName) {
1765
+ return [`table: ${jsonToTsSource(tableName)}`, `column: ${jsonToTsSource(columnName)}`];
1766
+ }
1767
+ function refusedArgument(factory, location, argument, why) {
1768
+ throw sqliteError("CONTRACT.ARGUMENT_INVALID", `${factory}({ ${location.join(", ")} }): ${why}`, { meta: { what: `${factory} ${argument}` } });
1769
+ }
1770
+ function requirePath(text, factory, location) {
1771
+ const parsed = parseJsonPath(text);
1772
+ return parsed.ok ? parsed.value : refusedArgument(factory, location, "path", parsed.failure);
1773
+ }
1774
+ function requireKeyPath(text, factory, location) {
1775
+ return keyPathOf(requirePath(text, factory, location)) ?? refusedArgument(factory, location, "path", `path ${JSON.stringify(text)} does not end at a member name, the key the operation acts on`);
1776
+ }
1777
+ /** Renames the key at the end of a JSON path, in every object of a column the path reaches. */
1778
+ var RenameStoredKeyCall = class extends SqliteOpFactoryCallNode {
1779
+ factoryName = "renameStoredKey";
1780
+ operationClass = "widening";
1781
+ tableName;
1782
+ columnName;
1783
+ path;
1784
+ to;
1785
+ label;
1786
+ constructor(tableName, columnName, path, to) {
1787
+ super();
1788
+ const location = columnCallLocation(tableName, columnName);
1789
+ this.tableName = tableName;
1790
+ this.columnName = columnName;
1791
+ this.path = requireKeyPath(path, this.factoryName, location);
1792
+ if (typeof to !== "string" || to === this.path.key) refusedArgument(this.factoryName, location, "to", `to must be a key other than ${JSON.stringify(this.path.key)}; got ${JSON.stringify(to)}`);
1793
+ this.to = to;
1794
+ this.label = `Rename key "${this.path.key}" to "${to}" ${keyPlace(this.path, tableName, columnName)}`;
1795
+ this.freeze();
1796
+ }
1797
+ toOp() {
1798
+ return renameStoredKey(this.tableName, this.columnName, this.path, this.to);
1799
+ }
1800
+ renderTypeScript() {
1801
+ return `this.renameStoredKey({ ${[
1802
+ ...columnCallLocation(this.tableName, this.columnName),
1803
+ `path: ${jsonToTsSource(this.path.path.text)}`,
1804
+ `to: ${jsonToTsSource(this.to)}`
1805
+ ].join(", ")} })`;
1806
+ }
1807
+ importRequirements() {
1808
+ return [];
1809
+ }
1810
+ };
1811
+ /** Removes the key at the end of a JSON path, from every object of a column the path reaches. */
1812
+ var RemoveStoredKeyCall = class extends SqliteOpFactoryCallNode {
1813
+ factoryName = "removeStoredKey";
1814
+ operationClass = "destructive";
1815
+ tableName;
1816
+ columnName;
1817
+ path;
1818
+ label;
1819
+ constructor(tableName, columnName, path) {
1820
+ super();
1821
+ this.tableName = tableName;
1822
+ this.columnName = columnName;
1823
+ this.path = requireKeyPath(path, this.factoryName, columnCallLocation(tableName, columnName));
1824
+ this.label = `Remove key "${this.path.key}" ${keyPlace(this.path, tableName, columnName)}`;
1825
+ this.freeze();
1826
+ }
1827
+ toOp() {
1828
+ return removeStoredKey(this.tableName, this.columnName, this.path);
1829
+ }
1830
+ renderTypeScript() {
1831
+ return `this.removeStoredKey({ ${[...columnCallLocation(this.tableName, this.columnName), `path: ${jsonToTsSource(this.path.path.text)}`].join(", ")} })`;
1832
+ }
1833
+ importRequirements() {
1834
+ return [];
1835
+ }
1836
+ };
1837
+ function requireJsonValue(value, factory, location) {
1838
+ return JSON.stringify(value) === void 0 ? refusedArgument(factory, location, "value", "value must be a JSON value; got undefined") : value;
1839
+ }
1840
+ function requireFillValue(value, field, factory, location) {
1841
+ const json = requireJsonValue(value, factory, location);
1842
+ const problem = fillValueProblem(json, field);
1843
+ return problem === void 0 ? json : refusedArgument(factory, location, "value", problem);
1844
+ }
1845
+ /**
1846
+ * The operation of a fill whose value is an unfilled placeholder: a promise that rejects with
1847
+ * `MIGRATION.UNFILLED_PLACEHOLDER`, whose meta names the operation it stands for, so that a plan can
1848
+ * list it before the user fills the value.
1849
+ */
1850
+ function unfilledFillOperation(slot, standsFor) {
1851
+ const unfilled = errorUnfilledPlaceholder(slot);
1852
+ const operation = Promise.reject(new CliStructuredError(unfilled.code, unfilled.message, {
1853
+ ...ifDefined("why", unfilled.why),
1854
+ ...ifDefined("fix", unfilled.fix),
1855
+ meta: {
1856
+ slot,
1857
+ operation: {
1858
+ id: standsFor.id,
1859
+ label: standsFor.label,
1860
+ operationClass: standsFor.operationClass
1861
+ }
1862
+ }
1863
+ }));
1864
+ operation.catch(() => void 0);
1865
+ return operation;
1866
+ }
1867
+ /**
1868
+ * Sets the key at the end of a JSON path to a value, in every object of a column the path reaches that lacks it or holds JSON `null` there. An unfilled value is a placeholder the user fills in `migration.ts`; until then the call lowers to no operation.
1869
+ */
1870
+ var FillStoredKeyCall = class extends SqliteOpFactoryCallNode {
1871
+ factoryName = "fillStoredKey";
1872
+ operationClass = "widening";
1873
+ tableName;
1874
+ columnName;
1875
+ path;
1876
+ value;
1877
+ /** The value object field the key holds, which must take `value`. */
1878
+ field;
1879
+ label;
1880
+ constructor(tableName, columnName, path, value, field) {
1881
+ super();
1882
+ const location = columnCallLocation(tableName, columnName);
1883
+ this.tableName = tableName;
1884
+ this.columnName = columnName;
1885
+ this.path = requireKeyPath(path, this.factoryName, location);
1886
+ const keyProblem = fillKeyProblem({
1887
+ key: this.path.key,
1888
+ path: this.path.path.text
1889
+ }, field);
1890
+ if (keyProblem !== void 0) refusedArgument(this.factoryName, location, "field", keyProblem);
1891
+ this.field = field;
1892
+ this.value = value instanceof UnfilledValue ? value : requireFillValue(value, field, this.factoryName, location);
1893
+ this.label = `Fill key "${this.path.key}" ${keyPlace(this.path, tableName, columnName)}`;
1894
+ this.freeze();
1895
+ }
1896
+ toOp() {
1897
+ if (this.value instanceof UnfilledValue) return unfilledFillOperation(this.value.slot, fillStoredKey(this.tableName, this.columnName, this.path, "null"));
1898
+ return fillStoredKey(this.tableName, this.columnName, this.path, JSON.stringify(this.value));
1899
+ }
1900
+ renderTypeScript() {
1901
+ const value = this.value instanceof UnfilledValue ? `placeholder(${jsonToTsSource(this.value.slot)})` : jsonToTsSource(this.value);
1902
+ return `this.fillStoredKey({ ${[
1903
+ ...columnCallLocation(this.tableName, this.columnName),
1904
+ `path: ${jsonToTsSource(this.path.path.text)}`,
1905
+ `value: ${value}`,
1906
+ ...this.field === void 0 ? [] : [`field: ${jsonToTsSource(this.field.text)}`]
1907
+ ].join(", ")} })`;
1908
+ }
1909
+ importRequirements() {
1910
+ return this.value instanceof UnfilledValue ? [{
1911
+ moduleSpecifier: MIGRATION_MODULE,
1912
+ symbol: "placeholder"
1913
+ }] : [];
1914
+ }
1915
+ };
1916
+ /**
1917
+ * A planner-generated data-transform stub. The current default strategy
1918
+ * (`nullabilityTighteningBackfillStrategy`) emits one of these with a
1919
+ * backfill-flavored `id`/`label` when the policy allows `'data'` and the
1920
+ * contract tightens a column's nullability, but the op itself is generic —
1921
+ * any future strategy that needs a placeholder data step can construct one
1922
+ * with its own id/label.
1923
+ *
1924
+ * `toOp()` always rejects with `MIGRATION.UNFILLED_PLACEHOLDER`: the planner cannot lower a stubbed
1925
+ * transform to a runtime op — the user must edit the rendered
1926
+ * `migration.ts` and re-emit.
1927
+ */
1928
+ var DataTransformCall = class extends SqliteOpFactoryCallNode {
1929
+ factoryName = "dataTransform";
1930
+ operationClass = "data";
1931
+ id;
1932
+ label;
1933
+ tableName;
1934
+ columnName;
1935
+ /** The slot the user fills with the statement that fills the column: `<Model.field>:run`. */
1936
+ slot;
1937
+ constructor(id, label, tableName, columnName, slot) {
1938
+ super();
1939
+ this.id = id;
1940
+ this.label = label;
1941
+ this.tableName = tableName;
1942
+ this.columnName = columnName;
1943
+ this.slot = slot;
1944
+ this.freeze();
1945
+ }
1946
+ toOp(_lowerer) {
1947
+ return unfilledPlaceholderOperation(this.label);
1948
+ }
1949
+ renderTypeScript() {
1950
+ const slot = this.slot;
1951
+ return [
1952
+ "dataTransform({",
1953
+ ` id: ${jsonToTsSource(this.id)},`,
1954
+ ` label: ${jsonToTsSource(this.label)},`,
1955
+ ` table: ${jsonToTsSource(this.tableName)},`,
1956
+ ` description: ${jsonToTsSource(`Backfill NULL ${this.columnName} values in ${this.tableName}`)},`,
1957
+ ` run: () => placeholder(${jsonToTsSource(slot)}),`,
1958
+ "})"
1959
+ ].join("\n");
1960
+ }
1961
+ importRequirements() {
1962
+ return [{
1963
+ moduleSpecifier: MIGRATION_MODULE,
1964
+ symbol: this.factoryName
1965
+ }, {
1966
+ moduleSpecifier: MIGRATION_MODULE,
1967
+ symbol: "placeholder"
1968
+ }];
1969
+ }
1970
+ };
1971
+ /**
1972
+ * Laundered pre-built operation. Mirrors Postgres's `RawSqlCall`: wraps an
1973
+ * already-materialized `SqlMigrationPlanOperation` (typically produced by a
1974
+ * SQL-family helper or a codec lifecycle hook) so the planner can carry it
1975
+ * alongside structured call IR. `toOp()` returns the stored op unchanged;
1976
+ * `renderTypeScript()` emits `rawSql({...})` with the op serialized as a
1977
+ * JSON literal — round-tripping requires every field on the op to be
1978
+ * JSON-serializable (no closures).
1979
+ */
1980
+ var RawSqlCall = class extends SqliteOpFactoryCallNode {
1981
+ factoryName = "rawSql";
1982
+ operationClass;
1983
+ label;
1984
+ op;
1985
+ constructor(op) {
1986
+ super();
1987
+ this.op = op;
1988
+ this.label = op.label;
1989
+ this.operationClass = op.operationClass;
1990
+ this.freeze();
1991
+ }
1992
+ toOp(_lowerer) {
1993
+ return this.op;
1994
+ }
1995
+ renderTypeScript() {
1996
+ return `rawSql(${jsonToTsSource(this.op)})`;
1997
+ }
1998
+ };
1999
+ function definedSourceEntries(sources) {
2000
+ return Object.entries(sources).flatMap(([key, source]) => source === void 0 ? [] : [[key, source]]);
2001
+ }
2002
+ function renderIfDefined(value) {
2003
+ return value === void 0 ? void 0 : jsonToTsSource(value);
2004
+ }
2005
+ function renderColumnSpec(column, sql) {
2006
+ return tsObjectSource(definedSourceEntries({
2007
+ name: jsonToTsSource(column.name),
2008
+ typeSql: jsonToTsSource(column.typeSql),
2009
+ default: column.default === void 0 ? void 0 : renderSpecDefault(column.default, sql),
2010
+ codecRef: renderIfDefined(column.codecRef),
2011
+ nullable: jsonToTsSource(column.nullable),
2012
+ inlineAutoincrementPrimaryKey: renderIfDefined(column.inlineAutoincrementPrimaryKey)
2013
+ }));
2014
+ }
2015
+ function renderTableSpec(table, sql) {
2016
+ return tsObjectSource(definedSourceEntries({
2017
+ columns: tsArraySource(table.columns.map((column) => renderColumnSpec(column, sql))),
2018
+ primaryKey: renderIfDefined(table.primaryKey),
2019
+ uniques: renderIfDefined(table.uniques),
2020
+ foreignKeys: renderIfDefined(table.foreignKeys)
2021
+ }));
2022
+ }
2023
+ function renderSpecDefault(columnDefault, sql) {
2024
+ if (columnDefault.kind === "literal") return jsonToTsSource(columnDefault);
2025
+ return tsObjectSource(definedSourceEntries({
2026
+ kind: jsonToTsSource(columnDefault.kind),
2027
+ expression: sql.source(columnDefault.expression)
2028
+ }));
2029
+ }
2030
+ function renderPostcheck(postcheck) {
2031
+ if ("sql" in postcheck) return tsObjectSource(definedSourceEntries({
2032
+ description: jsonToTsSource(postcheck.description),
2033
+ sql: tsQuotedTextSource(postcheck.sql),
2034
+ requiredColumn: postcheck.requiredColumn === void 0 ? void 0 : jsonToTsSource(postcheck.requiredColumn)
2035
+ }));
2036
+ return tsObjectSource(definedSourceEntries({
2037
+ description: jsonToTsSource(postcheck.description),
2038
+ columnDefault: jsonToTsSource(postcheck.columnDefault)
2039
+ }));
2040
+ }
2041
+ //#endregion
2042
+ export { sqliteDefaultToDdlColumnDefault as A, buildRecreateSummary as C, isSqliteOpFactoryCall as D, indexReplacementCalls as E, step as M, rebuiltTableName as O, buildRecreatePostchecks as S, holdingStoredValue as T, RenameColumnCall as _, DataTransformCall as a, ReplaceStoredValueCall as b, DropIndexCall as c, INLINE_AUTOINCREMENT_PRIMARY_KEY as d, MIGRATION_MODULE as f, RemoveStoredValueCall as g, RemoveStoredKeyCall as h, CreateTableCall as i, sqliteIdentifiersCollide as j, renameTableSteps as k, DropTableCall as l, RecreateTableCall as m, ConversionCopyJson as n, DeleteRowsCall as o, RawSqlCall as p, CreateIndexCall as r, DropColumnCall as s, AddColumnCall as t, FillStoredKeyCall as u, RenameStoredKeyCall as v, conversionCopyOf as w, affinityStorageClasses as x, RenameTableCall as y };
2043
+
2044
+ //# sourceMappingURL=op-factory-call-DjbjegGT-DsQBI5Ll.mjs.map