@farm.js/core 0.1.17 → 0.1.18

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 (249) hide show
  1. package/dist/after.cjs +12 -225
  2. package/dist/agent-runtime.cjs +83 -2800
  3. package/dist/api/client.cjs +17 -4060
  4. package/dist/api/route-manager.cjs +34 -4354
  5. package/dist/api/runtime.cjs +29 -2696
  6. package/dist/api.cjs +88 -8434
  7. package/dist/app-markdown.cjs +39 -280
  8. package/dist/cache.cjs +38 -1560
  9. package/dist/chunk-22GUSVNJ.cjs +351 -0
  10. package/dist/chunk-2CQ74SP6.cjs +13 -0
  11. package/dist/chunk-2SJ4RQ6P.cjs +57 -0
  12. package/dist/chunk-3376ZTRC.cjs +1 -0
  13. package/dist/{chunk-YD4J4XCI.mjs → chunk-3XG26Z3J.mjs} +1 -1
  14. package/dist/chunk-4PNUXIVU.cjs +472 -0
  15. package/dist/chunk-4PPEPOZZ.cjs +21 -0
  16. package/dist/chunk-4ZFL5GFN.cjs +520 -0
  17. package/dist/chunk-5OVTOKGH.cjs +65 -0
  18. package/dist/chunk-5QIKR7RR.cjs +224 -0
  19. package/dist/chunk-5ZSWG4UX.cjs +127 -0
  20. package/dist/chunk-62YJ2IEB.cjs +238 -0
  21. package/dist/chunk-6EODJYCX.cjs +183 -0
  22. package/dist/chunk-6EXBPJ24.cjs +434 -0
  23. package/dist/chunk-6QQDAAAZ.cjs +38 -0
  24. package/dist/chunk-6V4TDWEC.cjs +455 -0
  25. package/dist/chunk-72ADZ6GQ.cjs +19 -0
  26. package/dist/chunk-75BRBIFP.cjs +172 -0
  27. package/dist/chunk-7W3CPVXS.cjs +24 -0
  28. package/dist/chunk-A6WIQH5Z.cjs +31 -0
  29. package/dist/chunk-AFOD3LYZ.cjs +377 -0
  30. package/dist/chunk-AMDMVWMI.cjs +39 -0
  31. package/dist/chunk-AORPIPNB.cjs +552 -0
  32. package/dist/chunk-ARJWXNQL.cjs +256 -0
  33. package/dist/chunk-AWRISO2H.cjs +2199 -0
  34. package/dist/chunk-AYJR42WX.cjs +711 -0
  35. package/dist/chunk-B4CH33IG.cjs +644 -0
  36. package/dist/chunk-BIDYX3SL.cjs +91 -0
  37. package/dist/chunk-BSTRERPP.cjs +40 -0
  38. package/dist/chunk-BYODCJD6.cjs +663 -0
  39. package/dist/chunk-C3VRMB6H.cjs +85 -0
  40. package/dist/chunk-C5GUTBZK.cjs +173 -0
  41. package/dist/chunk-CIAGU2X4.cjs +337 -0
  42. package/dist/chunk-CMGMGHUZ.cjs +27 -0
  43. package/dist/chunk-CXP5U3RW.cjs +54 -0
  44. package/dist/chunk-D2ULAULS.cjs +166 -0
  45. package/dist/chunk-D7JTOLFK.cjs +285 -0
  46. package/dist/chunk-DVM4FKZL.cjs +169 -0
  47. package/dist/chunk-DYEJQTDN.cjs +49 -0
  48. package/dist/chunk-E2BMSZ2W.cjs +151 -0
  49. package/dist/chunk-E3UK5IIB.cjs +593 -0
  50. package/dist/chunk-EM6SBQKM.cjs +470 -0
  51. package/dist/chunk-FJSWYIR7.cjs +482 -0
  52. package/dist/chunk-FK6GO24V.cjs +54 -0
  53. package/dist/chunk-FXUUWYAX.cjs +654 -0
  54. package/dist/chunk-G3HRIVEY.cjs +395 -0
  55. package/dist/chunk-G643DQCH.cjs +13 -0
  56. package/dist/chunk-G7HXGLEC.cjs +175 -0
  57. package/dist/chunk-GDSHDTJ4.cjs +152 -0
  58. package/dist/chunk-GNEO2XOF.cjs +2040 -0
  59. package/dist/{chunk-56DAX2BE.mjs → chunk-GYKJCFTS.mjs} +1 -1
  60. package/dist/chunk-H6G5INWM.cjs +1094 -0
  61. package/dist/chunk-HBTUGXHS.cjs +180 -0
  62. package/dist/chunk-HREOKQWT.cjs +45 -0
  63. package/dist/chunk-I4J452B7.cjs +435 -0
  64. package/dist/chunk-I57LW5VZ.cjs +94 -0
  65. package/dist/chunk-I7PUUDGY.cjs +389 -0
  66. package/dist/chunk-IAMRBF3Z.cjs +86 -0
  67. package/dist/chunk-IKNRN4VS.cjs +14214 -0
  68. package/dist/chunk-IQXFRNY2.cjs +169 -0
  69. package/dist/chunk-IXTFU4PL.cjs +2355 -0
  70. package/dist/chunk-J2OP5GG3.cjs +725 -0
  71. package/dist/chunk-J3LOGE4T.cjs +42 -0
  72. package/dist/chunk-J7FSKED3.cjs +93 -0
  73. package/dist/chunk-JDNHKPTD.cjs +22 -0
  74. package/dist/chunk-JSROZYYO.cjs +164 -0
  75. package/dist/chunk-K6FNHVDR.cjs +696 -0
  76. package/dist/chunk-KGZIORNL.cjs +43 -0
  77. package/dist/{chunk-MVIWBEJF.mjs → chunk-KPNVGRBL.mjs} +1 -1
  78. package/dist/chunk-KR6CKSXT.cjs +15 -0
  79. package/dist/chunk-KROWKCUH.cjs +185 -0
  80. package/dist/chunk-KVFPGF2M.cjs +46 -0
  81. package/dist/chunk-LCCBO7PJ.cjs +46 -0
  82. package/dist/chunk-LIUGYUX3.cjs +22 -0
  83. package/dist/chunk-LTNGXMQ6.cjs +55 -0
  84. package/dist/chunk-M2L4MYDQ.cjs +14 -0
  85. package/dist/chunk-MCJLA63J.cjs +1 -0
  86. package/dist/chunk-MKB2EGIR.cjs +148 -0
  87. package/dist/chunk-MQ3H6LT5.cjs +202 -0
  88. package/dist/chunk-MT763TDW.cjs +43 -0
  89. package/dist/chunk-MWSK6C4J.cjs +18 -0
  90. package/dist/chunk-MWWVKDW3.cjs +169 -0
  91. package/dist/chunk-NO3WWW3N.cjs +192 -0
  92. package/dist/chunk-NV3A5DXM.cjs +862 -0
  93. package/dist/chunk-NWOD6NIT.cjs +9 -0
  94. package/dist/chunk-NZKJGRB3.cjs +230 -0
  95. package/dist/chunk-OAVTUMJP.cjs +1496 -0
  96. package/dist/chunk-OHY2ZWUG.cjs +25 -0
  97. package/dist/chunk-OI6CMLWX.cjs +47 -0
  98. package/dist/chunk-OIEOCXKG.cjs +453 -0
  99. package/dist/chunk-OWOUTKIJ.cjs +558 -0
  100. package/dist/chunk-OX6O6WVA.cjs +74 -0
  101. package/dist/chunk-OXSIH4D6.cjs +476 -0
  102. package/dist/chunk-OYEUREB6.cjs +35 -0
  103. package/dist/chunk-PCOTGFSM.cjs +139 -0
  104. package/dist/chunk-PZYCPSCC.cjs +35 -0
  105. package/dist/chunk-QBK2AA4U.cjs +445 -0
  106. package/dist/chunk-QBPXNZGV.cjs +487 -0
  107. package/dist/chunk-QNPEUFHQ.cjs +27 -0
  108. package/dist/chunk-QZRVZSPN.cjs +236 -0
  109. package/dist/chunk-R5A5KNVX.cjs +20 -0
  110. package/dist/chunk-R5JIFR6B.cjs +42 -0
  111. package/dist/chunk-R6AIILII.cjs +193 -0
  112. package/dist/chunk-RG3ZOTG5.cjs +34 -0
  113. package/dist/chunk-ROUTX2E5.cjs +390 -0
  114. package/dist/chunk-RTHIVJ2G.cjs +54 -0
  115. package/dist/chunk-S3A45T7F.cjs +166 -0
  116. package/dist/chunk-S3JO3N4H.cjs +17 -0
  117. package/dist/chunk-SK35NQKK.cjs +27 -0
  118. package/dist/chunk-SU7MH53P.cjs +180 -0
  119. package/dist/chunk-SVRTJOUF.cjs +113 -0
  120. package/dist/chunk-SWN467MP.cjs +18 -0
  121. package/dist/chunk-SYQ3MOWW.cjs +73 -0
  122. package/dist/chunk-T5CERMEH.cjs +417 -0
  123. package/dist/chunk-TFAXUHWX.cjs +206 -0
  124. package/dist/chunk-TIWHTW3Q.cjs +24 -0
  125. package/dist/chunk-TKJZFIML.cjs +20 -0
  126. package/dist/chunk-TKNSDBBN.cjs +193 -0
  127. package/dist/chunk-TWGMSEHX.cjs +525 -0
  128. package/dist/chunk-TYQUSXUG.cjs +1357 -0
  129. package/dist/chunk-U4KT7QP3.cjs +23 -0
  130. package/dist/chunk-UJ2C4ICS.cjs +277 -0
  131. package/dist/chunk-UN5GHC5V.cjs +10244 -0
  132. package/dist/chunk-UQZ4AYTH.cjs +168 -0
  133. package/dist/chunk-US2QVW3E.cjs +36 -0
  134. package/dist/chunk-VB6UCX3V.cjs +421 -0
  135. package/dist/chunk-VEKFLAQM.cjs +300 -0
  136. package/dist/chunk-VQDBNVOO.cjs +14 -0
  137. package/dist/chunk-W4E7WMXE.cjs +71 -0
  138. package/dist/chunk-WJ3HK3LJ.cjs +1102 -0
  139. package/dist/chunk-WMAPPDMM.cjs +28 -0
  140. package/dist/chunk-WMOGFOUJ.cjs +223 -0
  141. package/dist/chunk-WPYFSQKK.cjs +37 -0
  142. package/dist/chunk-WZMNW2IW.cjs +1415 -0
  143. package/dist/chunk-XGC343EY.cjs +443 -0
  144. package/dist/chunk-XSKZORAS.cjs +727 -0
  145. package/dist/chunk-XWAWFQFS.cjs +82 -0
  146. package/dist/chunk-Y4YMF2NQ.cjs +460 -0
  147. package/dist/chunk-Y4YWHNKU.cjs +250 -0
  148. package/dist/chunk-Y53ZSFN6.cjs +504 -0
  149. package/dist/chunk-YA6LLTIJ.cjs +411 -0
  150. package/dist/chunk-YFPGHF5F.cjs +202 -0
  151. package/dist/chunk-YJRZR7VU.cjs +28 -0
  152. package/dist/chunk-YTAABQEV.cjs +1 -0
  153. package/dist/chunk-YX3DBN4M.cjs +18 -0
  154. package/dist/chunk-YZTASLPQ.cjs +64 -0
  155. package/dist/chunk-Z5HIWVDP.cjs +2173 -0
  156. package/dist/chunk-ZEG3OPIB.cjs +93 -0
  157. package/dist/chunk-ZMN3H73H.cjs +155 -0
  158. package/dist/client/lifecycle.cjs +6 -35
  159. package/dist/client-plugins.cjs +7 -448
  160. package/dist/client.cjs +171 -9808
  161. package/dist/config.cjs +8 -36
  162. package/dist/cron.cjs +24 -491
  163. package/dist/deferred.cjs +26 -475
  164. package/dist/deployment.cjs +39 -210
  165. package/dist/devtools-OUIPHVV6.cjs +388 -0
  166. package/dist/devtools-client-4WAPJY5L.cjs +254 -0
  167. package/dist/devtools-ui-5GBDIGMK.cjs +1296 -0
  168. package/dist/docs.cjs +46 -5657
  169. package/dist/env-types.cjs +5 -226
  170. package/dist/env.cjs +21 -338
  171. package/dist/environment/vite.cjs +8 -372
  172. package/dist/environment.cjs +12 -94
  173. package/dist/font.cjs +13 -63
  174. package/dist/headers.cjs +7 -123
  175. package/dist/i18n/client.cjs +55 -294
  176. package/dist/i18n/index.cjs +22 -209
  177. package/dist/i18n/server.cjs +22 -745
  178. package/dist/image/server.cjs +13 -729
  179. package/dist/image/sharp.cjs +33 -171
  180. package/dist/image.cjs +41 -85
  181. package/dist/index.cjs +1151 -68080
  182. package/dist/index.mjs +3 -3
  183. package/dist/instrumentation.cjs +12 -138
  184. package/dist/integration-orm-55F7CII5.cjs +13 -0
  185. package/dist/integrations.cjs +55 -4090
  186. package/dist/internal/app-markdown-runtime.cjs +27 -224
  187. package/dist/internal/build-runtime.cjs +120 -52259
  188. package/dist/internal/build-runtime.mjs +3 -3
  189. package/dist/internal/cli-runtime.cjs +67 -13811
  190. package/dist/internal/client-error-overlay.cjs +80 -733
  191. package/dist/internal/client-error-overlay.mjs +1 -1
  192. package/dist/internal/client-runtime.cjs +81 -913
  193. package/dist/internal/compression-runtime.cjs +8 -214
  194. package/dist/internal/config-runtime.cjs +42 -6547
  195. package/dist/internal/docs-precompiled-runtime.cjs +26 -46
  196. package/dist/internal/infra-analytics-runtime.cjs +10 -536
  197. package/dist/internal/isolated-boundary.cjs +14 -414
  198. package/dist/internal/metadata-image-runtime.cjs +7 -285
  199. package/dist/internal/product-telemetry-runtime.cjs +42 -97
  200. package/dist/internal/product-telemetry-runtime.mjs +1 -1
  201. package/dist/internal/production-node-env.cjs +6 -63
  202. package/dist/internal/production-runtime.cjs +418 -7133
  203. package/dist/internal/request-cookies.cjs +6 -54
  204. package/dist/json-ld.cjs +24 -50
  205. package/dist/layers-E4WPJNY5.cjs +17 -0
  206. package/dist/manager-G4B2IPYE.cjs +14 -0
  207. package/dist/markdown.cjs +21 -547
  208. package/dist/middleware.cjs +36 -2995
  209. package/dist/navigation.cjs +22 -2588
  210. package/dist/nitro-4I2MYLY2.cjs +652 -0
  211. package/dist/observability.cjs +22 -614
  212. package/dist/og.cjs +5 -28
  213. package/dist/plugin.cjs +106 -37442
  214. package/dist/plugin.mjs +2 -2
  215. package/dist/query/client.cjs +113 -449
  216. package/dist/query/index.cjs +26 -288
  217. package/dist/query/parsers.cjs +23 -247
  218. package/dist/query/server.cjs +36 -298
  219. package/dist/renderer/react/client.cjs +9 -43
  220. package/dist/renderer/react/server.cjs +40 -103
  221. package/dist/renderer/react/vite.cjs +7 -29
  222. package/dist/renderer-client.cjs +126 -4295
  223. package/dist/renderer.cjs +31 -249
  224. package/dist/request.cjs +5 -68
  225. package/dist/router.cjs +11 -474
  226. package/dist/routes.cjs +42 -2461
  227. package/dist/schema-dev-notice-MXSZMVDG.cjs +56 -0
  228. package/dist/schema.cjs +6 -33
  229. package/dist/search-client-G3RICOFU.cjs +13 -0
  230. package/dist/server-action-security.cjs +25 -541
  231. package/dist/server-fn-client.cjs +6 -337
  232. package/dist/server-fn.cjs +32 -1841
  233. package/dist/server-plugins.cjs +15 -884
  234. package/dist/server-query-client.cjs +15 -1883
  235. package/dist/server-query.cjs +16 -1838
  236. package/dist/server.cjs +296 -44681
  237. package/dist/server.mjs +2 -2
  238. package/dist/storage.cjs +57 -576
  239. package/dist/testing.cjs +89 -3186
  240. package/dist/theme/client.cjs +13 -108
  241. package/dist/theme/index.cjs +6 -68
  242. package/dist/theme/runtime.cjs +13 -78
  243. package/dist/theme/server.cjs +10 -179
  244. package/dist/version.cjs +4 -32
  245. package/dist/version.mjs +1 -1
  246. package/dist/vite.cjs +119 -37773
  247. package/dist/vite.mjs +2 -2
  248. package/dist/workflows.cjs +19 -1040
  249. package/package.json +1 -1
@@ -0,0 +1,2199 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+ var _chunkJSROZYYOcjs = require('./chunk-JSROZYYO.cjs');
6
+
7
+
8
+ var _chunkS3JO3N4Hcjs = require('./chunk-S3JO3N4H.cjs');
9
+
10
+ // src/schema-sql.ts
11
+ function describeSchemaReference(model, fieldKey) {
12
+ const field = model.model.fields[fieldKey];
13
+ const target = _optionalChain([model, 'access', _ => _.referenceTargets, 'optionalAccess', _2 => _2[fieldKey]]);
14
+ if (target) return `${target.table}.${target.column}`;
15
+ return `${_optionalChain([field, 'optionalAccess', _3 => _3.reference, 'optionalAccess', _4 => _4.model])}.${_optionalChain([field, 'optionalAccess', _5 => _5.reference, 'optionalAccess', _6 => _6.field])}`;
16
+ }
17
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeSchemaReference, "describeSchemaReference");
18
+ var SQL_ON_DELETE_ACTIONS = {
19
+ cascade: "CASCADE",
20
+ restrict: "RESTRICT",
21
+ setNull: "SET NULL",
22
+ noAction: "NO ACTION"
23
+ };
24
+ function collectSchemaModels(entries) {
25
+ const collectedModels = [];
26
+ const seenModelNames = /* @__PURE__ */ new Map();
27
+ for (const [ownerKey, schema, only] of entries) {
28
+ const resolvedModels = _chunkJSROZYYOcjs.resolveSchemaModels.call(void 0, ownerKey, schema);
29
+ for (const [modelKey, model] of Object.entries(resolvedModels)) {
30
+ if (only && !only.includes(modelKey)) continue;
31
+ if (model.external) continue;
32
+ const collisionKey = model.name.toLowerCase();
33
+ const previousOwner = seenModelNames.get(collisionKey);
34
+ if (previousOwner && previousOwner !== `${ownerKey}.${modelKey}`) {
35
+ throw new Error(
36
+ `Schema model "${ownerKey}.${modelKey}" resolves to "${model.name}", which conflicts with "${previousOwner}". Rename one of the models with schema.models.<model>.name.`
37
+ );
38
+ }
39
+ seenModelNames.set(collisionKey, `${ownerKey}.${modelKey}`);
40
+ const referenceTargets = {};
41
+ for (const [fieldKey, field] of Object.entries(model.fields)) {
42
+ const reference = field.reference;
43
+ if (!reference || !Object.prototype.hasOwnProperty.call(resolvedModels, reference.model)) {
44
+ continue;
45
+ }
46
+ const target = resolvedModels[reference.model];
47
+ if (!target.external && (!only || only.includes(reference.model))) continue;
48
+ referenceTargets[fieldKey] = {
49
+ table: target.name,
50
+ column: _nullishCoalesce(_optionalChain([target, 'access', _7 => _7.fields, 'access', _8 => _8[reference.field], 'optionalAccess', _9 => _9.name]), () => ( reference.field))
51
+ };
52
+ }
53
+ collectedModels.push({
54
+ ownerKey,
55
+ modelKey,
56
+ modelName: model.name,
57
+ exportName: toCamelCase(`${ownerKey}_${modelKey}`),
58
+ prismaModelName: toPascalCase(`${ownerKey}_${modelKey}`),
59
+ model,
60
+ ...Object.keys(referenceTargets).length > 0 ? { referenceTargets } : {}
61
+ });
62
+ }
63
+ }
64
+ return collectedModels;
65
+ }
66
+ _chunkS3JO3N4Hcjs.__name.call(void 0, collectSchemaModels, "collectSchemaModels");
67
+ function generateSqlStatements(models, dialect) {
68
+ const modelLookup = createModelLookup(models);
69
+ const orderedModels = orderSchemaModelsByReferences(models, modelLookup);
70
+ const statements = [];
71
+ for (const model of orderedModels) {
72
+ statements.push({
73
+ kind: "table",
74
+ target: model.modelName,
75
+ sql: renderSqlTable(model, dialect, modelLookup)
76
+ });
77
+ for (const index of renderSqlIndexes(model, dialect)) {
78
+ statements.push(index);
79
+ }
80
+ }
81
+ return statements;
82
+ }
83
+ _chunkS3JO3N4Hcjs.__name.call(void 0, generateSqlStatements, "generateSqlStatements");
84
+ function renderSqlSchemaFile(models, dialect) {
85
+ const lines = ["-- Generated by Farm.js CLI. Review before applying.", ""];
86
+ const modelLookup = createModelLookup(models);
87
+ const orderedModels = orderSchemaModelsByReferences(models, modelLookup);
88
+ for (const model of orderedModels) {
89
+ lines.push(
90
+ `-- Owner "${model.ownerKey}" model "${model.modelKey}"`,
91
+ renderSqlTable(model, dialect, modelLookup),
92
+ ""
93
+ );
94
+ for (const statement of renderSqlIndexes(model, dialect)) {
95
+ lines.push(statement.sql, "");
96
+ }
97
+ }
98
+ return lines.join("\n").trimEnd() + "\n";
99
+ }
100
+ _chunkS3JO3N4Hcjs.__name.call(void 0, renderSqlSchemaFile, "renderSqlSchemaFile");
101
+ function renderSqlTable(model, dialect, modelLookup) {
102
+ const tableName = quoteSqlIdentifier(dialect, model.modelName);
103
+ const lines = [`CREATE TABLE IF NOT EXISTS ${tableName} (`];
104
+ const columns = [];
105
+ const internalReferences = createInternalReferenceLookup(model, dialect, modelLookup);
106
+ for (const [fieldKey, field] of Object.entries(model.model.fields)) {
107
+ _chunkJSROZYYOcjs.assertNoSchemaListField.call(void 0,
108
+ field,
109
+ `${model.ownerKey}.${model.modelKey}.${fieldKey}`,
110
+ `${dialect} SQL generation`
111
+ );
112
+ const parts = [
113
+ ` ${quoteSqlIdentifier(dialect, field.name)}`,
114
+ getSqlColumnType(field, dialect)
115
+ ];
116
+ if (field.primaryKey) {
117
+ parts.push("PRIMARY KEY");
118
+ } else if (!isNullableField(field)) {
119
+ parts.push("NOT NULL");
120
+ }
121
+ if (!field.primaryKey && field.unique) {
122
+ parts.push("UNIQUE");
123
+ }
124
+ const defaultValue = getSqlDefaultExpression(field, dialect);
125
+ if (defaultValue) {
126
+ parts.push(`DEFAULT ${defaultValue}`);
127
+ }
128
+ const crossOwner = _optionalChain([model, 'access', _10 => _10.foreignKeys, 'optionalAccess', _11 => _11[fieldKey]]);
129
+ const reference = _nullishCoalesce(internalReferences.get(fieldKey), () => ( (crossOwner ? `REFERENCES ${quoteSqlIdentifier(dialect, crossOwner.table)} (${quoteSqlIdentifier(dialect, crossOwner.column)})${crossOwner.onDelete !== "noAction" ? ` ON DELETE ${SQL_ON_DELETE_ACTIONS[crossOwner.onDelete]}` : ""}` : void 0)));
130
+ if (reference) {
131
+ parts.push(reference);
132
+ } else if (field.reference) {
133
+ parts.push(
134
+ `/* references ${describeSchemaReference(model, fieldKey)}${field.reference.onDelete ? ` on delete ${field.reference.onDelete}` : ""} */`
135
+ );
136
+ }
137
+ columns.push(parts.join(" "));
138
+ }
139
+ if (dialect === "mysql") {
140
+ for (const definition of collectSchemaIndexes(model, dialect)) {
141
+ columns.push(
142
+ ` ${definition.unique ? "UNIQUE KEY" : "KEY"} ${quoteSqlIdentifier(dialect, definition.name)} (${definition.columns.join(", ")})`
143
+ );
144
+ }
145
+ }
146
+ lines.push(columns.join(",\n"));
147
+ lines.push(");");
148
+ return lines.join("\n");
149
+ }
150
+ _chunkS3JO3N4Hcjs.__name.call(void 0, renderSqlTable, "renderSqlTable");
151
+ function collectSchemaIndexes(model, dialect) {
152
+ const definitions = [];
153
+ for (const field of Object.values(model.model.fields)) {
154
+ if (!field.index) {
155
+ continue;
156
+ }
157
+ definitions.push({
158
+ name: `${model.modelName}_${field.name}_idx`,
159
+ columns: [quoteSqlIdentifier(dialect, field.name)],
160
+ unique: false
161
+ });
162
+ }
163
+ for (const constraint of model.model.constraints || []) {
164
+ definitions.push({
165
+ name: constraint.name || `${model.modelName}_${constraint.fields.map((fieldKey) => _optionalChain([model, 'access', _12 => _12.model, 'access', _13 => _13.fields, 'access', _14 => _14[fieldKey], 'optionalAccess', _15 => _15.name]) || fieldKey).join("_")}_${constraint.type}`,
166
+ columns: constraint.fields.map(
167
+ (fieldKey) => quoteSqlIdentifier(dialect, _optionalChain([model, 'access', _16 => _16.model, 'access', _17 => _17.fields, 'access', _18 => _18[fieldKey], 'optionalAccess', _19 => _19.name]) || fieldKey)
168
+ ),
169
+ unique: constraint.type === "unique"
170
+ });
171
+ }
172
+ return definitions;
173
+ }
174
+ _chunkS3JO3N4Hcjs.__name.call(void 0, collectSchemaIndexes, "collectSchemaIndexes");
175
+ function renderSqlIndexes(model, dialect) {
176
+ if (dialect === "mysql") {
177
+ return [];
178
+ }
179
+ const tableName = quoteSqlIdentifier(dialect, model.modelName);
180
+ return collectSchemaIndexes(model, dialect).map((definition) => ({
181
+ kind: "index",
182
+ target: definition.name,
183
+ sql: `CREATE ${definition.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${quoteSqlIdentifier(dialect, definition.name)} ON ${tableName} (${definition.columns.join(", ")});`
184
+ }));
185
+ }
186
+ _chunkS3JO3N4Hcjs.__name.call(void 0, renderSqlIndexes, "renderSqlIndexes");
187
+ function createInternalReferenceLookup(model, dialect, modelLookup) {
188
+ const lookup = /* @__PURE__ */ new Map();
189
+ for (const [fieldKey, field] of Object.entries(model.model.fields)) {
190
+ if (!field.reference || !_chunkJSROZYYOcjs.isDatabaseEnforcedReference.call(void 0, field.reference)) {
191
+ continue;
192
+ }
193
+ const referencedModel = modelLookup.get(`${model.ownerKey}.${field.reference.model}`);
194
+ if (referencedModel) {
195
+ const referencedField = field.reference.field;
196
+ const pieces = [
197
+ `REFERENCES ${quoteSqlIdentifier(dialect, referencedModel.modelName)} (${quoteSqlIdentifier(dialect, _optionalChain([referencedModel, 'access', _20 => _20.model, 'access', _21 => _21.fields, 'access', _22 => _22[referencedField], 'optionalAccess', _23 => _23.name]) || referencedField)})`
198
+ ];
199
+ if (field.reference.onDelete) {
200
+ pieces.push(`ON DELETE ${SQL_ON_DELETE_ACTIONS[field.reference.onDelete]}`);
201
+ }
202
+ lookup.set(fieldKey, pieces.join(" "));
203
+ }
204
+ }
205
+ return lookup;
206
+ }
207
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createInternalReferenceLookup, "createInternalReferenceLookup");
208
+ function getSqlColumnType(field, dialect) {
209
+ if (dialect === "postgres") {
210
+ switch (field.type) {
211
+ case "boolean":
212
+ return "BOOLEAN";
213
+ case "integer":
214
+ return "INTEGER";
215
+ case "number":
216
+ return "DOUBLE PRECISION";
217
+ case "datetime":
218
+ return "TIMESTAMPTZ";
219
+ case "json":
220
+ return "JSONB";
221
+ default:
222
+ return "TEXT";
223
+ }
224
+ }
225
+ if (dialect === "mysql") {
226
+ switch (field.type) {
227
+ case "boolean":
228
+ return "BOOLEAN";
229
+ case "integer":
230
+ return "INT";
231
+ case "number":
232
+ return "DOUBLE";
233
+ case "datetime":
234
+ return "DATETIME";
235
+ case "json":
236
+ return "JSON";
237
+ case "text":
238
+ return "TEXT";
239
+ default:
240
+ return "VARCHAR(255)";
241
+ }
242
+ }
243
+ switch (field.type) {
244
+ case "boolean":
245
+ case "integer":
246
+ return "INTEGER";
247
+ case "number":
248
+ return "REAL";
249
+ default:
250
+ return "TEXT";
251
+ }
252
+ }
253
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getSqlColumnType, "getSqlColumnType");
254
+ function getSqlDefaultExpression(field, dialect) {
255
+ if (field.default === void 0) {
256
+ return null;
257
+ }
258
+ if (field.type === "datetime" && field.default === "now") {
259
+ return "CURRENT_TIMESTAMP";
260
+ }
261
+ if (typeof field.default === "string") {
262
+ return `'${escapeSqlString(field.default, dialect)}'`;
263
+ }
264
+ if (typeof field.default === "number") {
265
+ return String(field.default);
266
+ }
267
+ if (typeof field.default === "boolean") {
268
+ if (dialect === "sqlite") {
269
+ return field.default ? "1" : "0";
270
+ }
271
+ return field.default ? "TRUE" : "FALSE";
272
+ }
273
+ return null;
274
+ }
275
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getSqlDefaultExpression, "getSqlDefaultExpression");
276
+ function isNullableField(field) {
277
+ return field.nullable === true || field.required === false;
278
+ }
279
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isNullableField, "isNullableField");
280
+ function quoteSqlIdentifier(dialect, value) {
281
+ if (dialect === "mysql") {
282
+ return `\`${value.replace(/`/g, "``")}\``;
283
+ }
284
+ return `"${value.replace(/"/g, '""')}"`;
285
+ }
286
+ _chunkS3JO3N4Hcjs.__name.call(void 0, quoteSqlIdentifier, "quoteSqlIdentifier");
287
+ function createModelLookup(models) {
288
+ return new Map(models.map((model) => [`${model.ownerKey}.${model.modelKey}`, model]));
289
+ }
290
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createModelLookup, "createModelLookup");
291
+ function orderSchemaModelsByReferences(models, modelLookup) {
292
+ const ordered = [];
293
+ const states = /* @__PURE__ */ new Map();
294
+ const stack = [];
295
+ const visit = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (model) => {
296
+ const modelKey = getCollectedModelKey(model);
297
+ if (states.get(modelKey) === "visited") {
298
+ return;
299
+ }
300
+ states.set(modelKey, "visiting");
301
+ stack.push(model);
302
+ const dependencies = /* @__PURE__ */ new Set();
303
+ for (const field of Object.values(model.model.fields)) {
304
+ if (field.reference && _chunkJSROZYYOcjs.isDatabaseEnforcedReference.call(void 0, field.reference)) {
305
+ dependencies.add(`${model.ownerKey}.${field.reference.model}`);
306
+ }
307
+ }
308
+ for (const dependencyKey of dependencies) {
309
+ const dependency = modelLookup.get(dependencyKey);
310
+ if (!dependency || dependency === model) {
311
+ continue;
312
+ }
313
+ if (states.get(dependencyKey) === "visiting") {
314
+ const cycleStart = stack.findIndex(
315
+ (candidate) => getCollectedModelKey(candidate) === dependencyKey
316
+ );
317
+ const cycle = [...stack.slice(cycleStart), dependency].map((candidate) => `"${getCollectedModelKey(candidate)}"`).join(" -> ");
318
+ throw new Error(
319
+ `Schema table references contain a cycle: ${cycle}. Database-enforced cross-table cycles cannot be created inline; remove one edge or manage that constraint separately.`
320
+ );
321
+ }
322
+ visit(dependency);
323
+ }
324
+ stack.pop();
325
+ states.set(modelKey, "visited");
326
+ ordered.push(model);
327
+ }, "visit");
328
+ for (const model of models) {
329
+ visit(model);
330
+ }
331
+ return ordered;
332
+ }
333
+ _chunkS3JO3N4Hcjs.__name.call(void 0, orderSchemaModelsByReferences, "orderSchemaModelsByReferences");
334
+ function getCollectedModelKey(model) {
335
+ return `${model.ownerKey}.${model.modelKey}`;
336
+ }
337
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getCollectedModelKey, "getCollectedModelKey");
338
+ function toSnakeCase(value) {
339
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[\s.-]+/g, "_").replace(/__+/g, "_").toLowerCase();
340
+ }
341
+ _chunkS3JO3N4Hcjs.__name.call(void 0, toSnakeCase, "toSnakeCase");
342
+ function toPascalCase(value) {
343
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[\s._-]+/g, " ").split(" ").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
344
+ }
345
+ _chunkS3JO3N4Hcjs.__name.call(void 0, toPascalCase, "toPascalCase");
346
+ function toCamelCase(value) {
347
+ const pascal = toPascalCase(value);
348
+ return pascal ? pascal.charAt(0).toLowerCase() + pascal.slice(1) : pascal;
349
+ }
350
+ _chunkS3JO3N4Hcjs.__name.call(void 0, toCamelCase, "toCamelCase");
351
+ function escapeSqlString(value, dialect) {
352
+ const quoted = value.replace(/'/g, "''");
353
+ return dialect === "mysql" ? quoted.replace(/\\/g, "\\\\") : quoted;
354
+ }
355
+ _chunkS3JO3N4Hcjs.__name.call(void 0, escapeSqlString, "escapeSqlString");
356
+
357
+ // src/schema-migrate.ts
358
+ async function planSchemaMigration(models, dialect, executor) {
359
+ const statements = [];
360
+ const upToDate = [];
361
+ const drift = [];
362
+ const addableForeignKeys = [];
363
+ const upgrades = [];
364
+ const modelLookup = new Map(
365
+ models.map((model) => [`${model.ownerKey}.${model.modelKey}`, model])
366
+ );
367
+ const byTable = /* @__PURE__ */ new Map();
368
+ let currentTable;
369
+ for (const statement of generateSqlStatements(models, dialect)) {
370
+ if (statement.kind === "table") {
371
+ currentTable = [];
372
+ byTable.set(statement.target, currentTable);
373
+ }
374
+ _optionalChain([currentTable, 'optionalAccess', _24 => _24.push, 'call', _25 => _25(statement)]);
375
+ }
376
+ for (const model of models) {
377
+ const existing = await describeTable(executor, dialect, model.modelName);
378
+ if (!existing) {
379
+ statements.push(..._nullishCoalesce(byTable.get(model.modelName), () => ( [])));
380
+ continue;
381
+ }
382
+ const expectedColumns = new Map(
383
+ Object.values(model.model.fields).map((field) => [field.name.toLowerCase(), field])
384
+ );
385
+ const actualColumns = new Map(
386
+ existing.columns.map((column) => [column.name.toLowerCase(), column])
387
+ );
388
+ const missingColumns = [...expectedColumns.values()].filter((field) => !actualColumns.has(field.name.toLowerCase())).map((field) => field.name);
389
+ const extraColumns = existing.columns.filter((column) => !expectedColumns.has(column.name.toLowerCase())).map((column) => column.name);
390
+ const changedColumns = [];
391
+ for (const [columnKey, field] of expectedColumns) {
392
+ const actualColumn = actualColumns.get(columnKey);
393
+ if (!actualColumn) continue;
394
+ const expectedDefinition = expectedColumnDefinition(field, dialect);
395
+ const actualDefinition = actualColumnDefinition(actualColumn, field, dialect);
396
+ const differences = [];
397
+ if (expectedDefinition.type !== actualDefinition.type) differences.push("type");
398
+ if (expectedDefinition.nullable !== actualDefinition.nullable) {
399
+ differences.push("nullability");
400
+ }
401
+ if (expectedDefinition.default !== actualDefinition.default) differences.push("default");
402
+ if (expectedDefinition.primaryKey !== actualDefinition.primaryKey) {
403
+ differences.push("primaryKey");
404
+ }
405
+ if (differences.length > 0) {
406
+ changedColumns.push({
407
+ column: field.name,
408
+ differences,
409
+ expected: expectedDefinition,
410
+ actual: actualDefinition
411
+ });
412
+ }
413
+ }
414
+ const expectedIndexes = collectExpectedIndexes(model);
415
+ const actualIndexes = existing.indexes.filter((index) => !index.primary);
416
+ const { missing: missingIndexes, extra: unmatchedIndexes } = compareDefinitions(
417
+ expectedIndexes,
418
+ actualIndexes,
419
+ indexSignature
420
+ );
421
+ const expectedReferences = collectExpectedReferences(model, modelLookup);
422
+ const crossOwner = Object.entries(_nullishCoalesce(model.foreignKeys, () => ( {}))).map(([fieldKey, key]) => ({
423
+ ...key,
424
+ column: model.model.fields[fieldKey].name,
425
+ referencedColumn: key.column
426
+ }));
427
+ const isCrossOwnerOf = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (key) => (reference) => key.column.toLowerCase() === reference.column.toLowerCase() && key.table.toLowerCase() === reference.referencedTable.toLowerCase(), "isCrossOwnerOf");
428
+ const isCrossOwner = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (reference) => crossOwner.some((key) => isCrossOwnerOf(key)(reference)), "isCrossOwner");
429
+ const { missing: missingReferences, extra: unmatchedReferences } = compareDefinitions(
430
+ expectedReferences,
431
+ existing.references,
432
+ referenceSignature
433
+ );
434
+ const extraReferences = unmatchedReferences.filter((reference) => !isCrossOwner(reference));
435
+ for (const key of crossOwner) {
436
+ if (existing.references.some(isCrossOwnerOf(key))) continue;
437
+ addableForeignKeys.push({
438
+ modelKey: model.modelKey,
439
+ table: model.modelName,
440
+ column: key.column,
441
+ referencedTable: key.table,
442
+ referencedColumn: key.referencedColumn,
443
+ onDelete: key.onDelete
444
+ });
445
+ }
446
+ const referenceColumns = new Set(
447
+ existing.references.map((reference) => reference.column.toLowerCase())
448
+ );
449
+ const extraIndexes = unmatchedIndexes.filter(
450
+ (index) => !(dialect === "mysql" && !index.unique && index.columns.length === 1 && referenceColumns.has(index.columns[0].toLowerCase()))
451
+ );
452
+ const remainingColumns = [];
453
+ for (const column of missingColumns) {
454
+ const field = expectedColumns.get(column.toLowerCase());
455
+ if (field.primaryKey || field.unique || unsupportedColumnReason(field, dialect)) {
456
+ remainingColumns.push(column);
457
+ continue;
458
+ }
459
+ upgrades.push({
460
+ kind: "column",
461
+ table: model.modelName,
462
+ target: `${model.modelName}.${column}`,
463
+ sql: addColumnStatement(dialect, model.modelName, field)
464
+ });
465
+ }
466
+ const remainingIndexes = [];
467
+ for (const index of missingIndexes) {
468
+ const columnsExist = index.columns.every(
469
+ (column) => actualColumns.has(column.toLowerCase()) || !remainingColumns.includes(column)
470
+ );
471
+ if (index.unique || !columnsExist) {
472
+ remainingIndexes.push(index);
473
+ continue;
474
+ }
475
+ const columns = index.columns.map((column) => quoteSqlIdentifier(dialect, column)).join(", ");
476
+ upgrades.push({
477
+ kind: "index",
478
+ table: model.modelName,
479
+ target: index.name,
480
+ sql: `CREATE INDEX${dialect === "mysql" ? "" : " IF NOT EXISTS"} ${quoteSqlIdentifier(dialect, index.name)} ON ${quoteTableName(dialect, model.modelName)} (${columns});`
481
+ });
482
+ }
483
+ const entry = {
484
+ table: model.modelName,
485
+ missingColumns: remainingColumns,
486
+ extraColumns,
487
+ changedColumns,
488
+ missingIndexes: remainingIndexes,
489
+ extraIndexes: extraIndexes.map(({ name, columns, unique }) => ({ name, columns, unique })),
490
+ missingReferences,
491
+ extraReferences
492
+ };
493
+ if (hasSchemaDrift(entry)) drift.push(entry);
494
+ else if (!upgrades.some((upgrade) => upgrade.table === model.modelName)) {
495
+ upToDate.push(model.modelName);
496
+ }
497
+ }
498
+ return { dialect, statements, upgrades, upToDate, drift, addableForeignKeys };
499
+ }
500
+ _chunkS3JO3N4Hcjs.__name.call(void 0, planSchemaMigration, "planSchemaMigration");
501
+ async function describeSchemaTable(executor, dialect, table) {
502
+ const described = await describeTable(executor, dialect, table);
503
+ if (!described) {
504
+ if (dialect === "sqlite") return void 0;
505
+ const dot = table.indexOf(".");
506
+ if (dot > 0) {
507
+ return describeQualifiedTable(executor, dialect, table.slice(0, dot), table.slice(dot + 1));
508
+ }
509
+ if (dialect === "postgres") {
510
+ const schema = await findOnSearchPath(executor, table);
511
+ return schema ? describeQualifiedTable(executor, dialect, schema, table) : void 0;
512
+ }
513
+ return void 0;
514
+ }
515
+ return {
516
+ columns: described.columns.map(({ name, type, nullable, primaryKey }) => ({
517
+ name,
518
+ type,
519
+ nullable,
520
+ primaryKey
521
+ }))
522
+ };
523
+ }
524
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeSchemaTable, "describeSchemaTable");
525
+ async function describeQualifiedTable(executor, dialect, schema, table) {
526
+ const rows = await executor.query(
527
+ dialect === "mysql" ? "select column_name, column_type as type, is_nullable from information_schema.columns where table_schema = ? and table_name = ? order by ordinal_position" : "select column_name, data_type as type, is_nullable from information_schema.columns where table_schema = $1 and table_name = $2 order by ordinal_position",
528
+ [schema, table]
529
+ );
530
+ if (rows.length === 0) return void 0;
531
+ return {
532
+ columns: rows.map((row) => ({
533
+ name: String(readRowValue(row, "column_name")),
534
+ type: normalizeColumnType(dialect, String(readRowValue(row, "type"))),
535
+ nullable: String(readRowValue(row, "is_nullable")).toUpperCase() === "YES",
536
+ primaryKey: false
537
+ }))
538
+ };
539
+ }
540
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeQualifiedTable, "describeQualifiedTable");
541
+ async function findOnSearchPath(executor, table) {
542
+ const rows = await executor.query(
543
+ `select namespace.nspname as schema_name
544
+ from unnest(current_schemas(false)) with ordinality as path(name, position)
545
+ join pg_namespace namespace on namespace.nspname = path.name
546
+ join pg_class relation on relation.relnamespace = namespace.oid
547
+ where relation.relname = $1 and relation.relkind in ('r', 'p', 'v', 'f')
548
+ order by path.position
549
+ limit 1`,
550
+ [table]
551
+ );
552
+ const schema = rows[0] && readRowValue(rows[0], "schema_name");
553
+ return schema ? String(schema) : void 0;
554
+ }
555
+ _chunkS3JO3N4Hcjs.__name.call(void 0, findOnSearchPath, "findOnSearchPath");
556
+ async function describeTable(executor, dialect, table) {
557
+ if (dialect === "sqlite") {
558
+ return describeSqliteTable(executor, table);
559
+ }
560
+ const [sql, params] = dialect === "mysql" ? [
561
+ "select column_name, data_type, column_type, is_nullable, column_default from information_schema.columns where table_name = ? and table_schema = database() order by ordinal_position",
562
+ [table]
563
+ ] : [
564
+ "select column_name, data_type, udt_name, is_nullable, column_default from information_schema.columns where table_name = $1 and table_schema = current_schema() order by ordinal_position",
565
+ [table]
566
+ ];
567
+ const rows = await executor.query(sql, params);
568
+ if (rows.length === 0) return void 0;
569
+ const columns = rows.map((row) => ({
570
+ name: String(readRowValue(row, "column_name")),
571
+ type: normalizeColumnType(
572
+ dialect,
573
+ String(
574
+ _nullishCoalesce(readRowValue(row, dialect === "mysql" ? "column_type" : "data_type"), () => ( readRowValue(row, "data_type")))
575
+ )
576
+ ),
577
+ nullable: String(readRowValue(row, "is_nullable")).toUpperCase() === "YES",
578
+ rawDefault: nullableString(readRowValue(row, "column_default")),
579
+ primaryKey: false
580
+ }));
581
+ const indexes = await describeServerIndexes(executor, dialect, table);
582
+ const primaryColumns = new Set(
583
+ indexes.filter((index) => index.primary).flatMap((index) => index.columns.map((column) => column.toLowerCase()))
584
+ );
585
+ for (const column of columns) {
586
+ if (primaryColumns.has(column.name.toLowerCase())) {
587
+ column.primaryKey = true;
588
+ column.nullable = false;
589
+ }
590
+ }
591
+ return {
592
+ columns,
593
+ indexes,
594
+ references: await describeServerReferences(executor, dialect, table)
595
+ };
596
+ }
597
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeTable, "describeTable");
598
+ async function describeSqliteTable(executor, table) {
599
+ const escapedTable = escapeSqlitePragmaValue(table);
600
+ const rows = await executor.query(`pragma table_info('${escapedTable}')`);
601
+ if (rows.length === 0) return void 0;
602
+ const columns = rows.map((row) => {
603
+ const primaryKey = Number(_nullishCoalesce(readRowValue(row, "pk"), () => ( 0))) > 0;
604
+ return {
605
+ name: String(readRowValue(row, "name")),
606
+ type: normalizeColumnType("sqlite", String(_nullishCoalesce(readRowValue(row, "type"), () => ( "")))),
607
+ nullable: !primaryKey && Number(_nullishCoalesce(readRowValue(row, "notnull"), () => ( 0))) === 0,
608
+ rawDefault: nullableString(readRowValue(row, "dflt_value")),
609
+ primaryKey
610
+ };
611
+ });
612
+ const indexRows = await executor.query(`pragma index_list('${escapedTable}')`);
613
+ const indexes = [];
614
+ for (const row of indexRows) {
615
+ const name = String(readRowValue(row, "name"));
616
+ const columnRows = await executor.query(
617
+ `pragma index_info('${escapeSqlitePragmaValue(name)}')`
618
+ );
619
+ indexes.push({
620
+ name,
621
+ columns: columnRows.sort(
622
+ (left, right) => Number(_nullishCoalesce(readRowValue(left, "seqno"), () => ( 0))) - Number(_nullishCoalesce(readRowValue(right, "seqno"), () => ( 0)))
623
+ ).map((column) => String(readRowValue(column, "name"))),
624
+ unique: asBoolean(readRowValue(row, "unique")),
625
+ primary: String(_nullishCoalesce(readRowValue(row, "origin"), () => ( ""))).toLowerCase() === "pk"
626
+ });
627
+ }
628
+ const referenceRows = await executor.query(`pragma foreign_key_list('${escapedTable}')`);
629
+ return {
630
+ columns,
631
+ indexes,
632
+ references: referenceRows.map((row) => ({
633
+ column: String(readRowValue(row, "from")),
634
+ referencedTable: String(readRowValue(row, "table")),
635
+ referencedColumn: String(readRowValue(row, "to")),
636
+ onDelete: normalizeDeleteAction(readRowValue(row, "on_delete"))
637
+ }))
638
+ };
639
+ }
640
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeSqliteTable, "describeSqliteTable");
641
+ async function describeServerIndexes(executor, dialect, table) {
642
+ const [sql, params] = dialect === "mysql" ? [
643
+ "select index_name, non_unique, column_name, seq_in_index from information_schema.statistics where table_name = ? and table_schema = database() order by index_name, seq_in_index",
644
+ [table]
645
+ ] : [
646
+ `select index_class.relname as index_name,
647
+ index_info.indisunique as is_unique,
648
+ index_info.indisprimary as is_primary,
649
+ attribute.attname as column_name,
650
+ index_key.column_position
651
+ from pg_catalog.pg_class table_class
652
+ join pg_catalog.pg_namespace namespace on namespace.oid = table_class.relnamespace
653
+ join pg_catalog.pg_index index_info on index_info.indrelid = table_class.oid
654
+ join pg_catalog.pg_class index_class on index_class.oid = index_info.indexrelid
655
+ join lateral unnest(index_info.indkey) with ordinality as index_key(attnum, column_position) on true
656
+ left join pg_catalog.pg_attribute attribute
657
+ on attribute.attrelid = table_class.oid and attribute.attnum = index_key.attnum
658
+ where table_class.relname = $1
659
+ and namespace.nspname = current_schema()
660
+ and index_key.column_position <= index_info.indnkeyatts
661
+ order by index_class.relname, index_key.column_position`,
662
+ [table]
663
+ ];
664
+ const rows = await executor.query(sql, params);
665
+ const grouped = /* @__PURE__ */ new Map();
666
+ for (const row of rows) {
667
+ const name = String(readRowValue(row, "index_name"));
668
+ const index = _nullishCoalesce(grouped.get(name), () => ( {
669
+ name,
670
+ columns: [],
671
+ unique: dialect === "mysql" ? Number(_nullishCoalesce(readRowValue(row, "non_unique"), () => ( 1))) === 0 : asBoolean(readRowValue(row, "is_unique")),
672
+ primary: dialect === "mysql" ? name.toUpperCase() === "PRIMARY" : asBoolean(readRowValue(row, "is_primary")),
673
+ orderedColumns: []
674
+ }));
675
+ const column = readRowValue(row, "column_name");
676
+ if (column !== void 0 && column !== null) {
677
+ index.orderedColumns.push({
678
+ position: Number(
679
+ _nullishCoalesce(readRowValue(row, dialect === "mysql" ? "seq_in_index" : "column_position"), () => ( 0))
680
+ ),
681
+ name: String(column)
682
+ });
683
+ }
684
+ grouped.set(name, index);
685
+ }
686
+ return [...grouped.values()].map(({ orderedColumns, ...index }) => ({
687
+ ...index,
688
+ columns: orderedColumns.sort((left, right) => left.position - right.position).map((column) => column.name)
689
+ }));
690
+ }
691
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeServerIndexes, "describeServerIndexes");
692
+ async function describeServerReferences(executor, dialect, table) {
693
+ const [sql, params] = dialect === "mysql" ? [
694
+ `select key_columns.column_name,
695
+ key_columns.referenced_table_name as referenced_table,
696
+ key_columns.referenced_column_name as referenced_column,
697
+ referential.delete_rule
698
+ from information_schema.key_column_usage key_columns
699
+ join information_schema.referential_constraints referential
700
+ on referential.constraint_schema = key_columns.constraint_schema
701
+ and referential.constraint_name = key_columns.constraint_name
702
+ and referential.table_name = key_columns.table_name
703
+ where key_columns.table_schema = database()
704
+ and key_columns.table_name = ?
705
+ and key_columns.referenced_table_name is not null
706
+ order by key_columns.constraint_name, key_columns.ordinal_position`,
707
+ [table]
708
+ ] : [
709
+ `select key_columns.column_name,
710
+ referenced_columns.table_name as referenced_table,
711
+ referenced_columns.column_name as referenced_column,
712
+ referential.delete_rule
713
+ from information_schema.table_constraints constraints
714
+ join information_schema.key_column_usage key_columns
715
+ on key_columns.constraint_catalog = constraints.constraint_catalog
716
+ and key_columns.constraint_schema = constraints.constraint_schema
717
+ and key_columns.constraint_name = constraints.constraint_name
718
+ join information_schema.referential_constraints referential
719
+ on referential.constraint_catalog = constraints.constraint_catalog
720
+ and referential.constraint_schema = constraints.constraint_schema
721
+ and referential.constraint_name = constraints.constraint_name
722
+ join information_schema.constraint_column_usage referenced_columns
723
+ on referenced_columns.constraint_catalog = referential.unique_constraint_catalog
724
+ and referenced_columns.constraint_schema = referential.unique_constraint_schema
725
+ and referenced_columns.constraint_name = referential.unique_constraint_name
726
+ where constraints.constraint_type = 'FOREIGN KEY'
727
+ and constraints.table_schema = current_schema()
728
+ and constraints.table_name = $1
729
+ order by constraints.constraint_name, key_columns.ordinal_position`,
730
+ [table]
731
+ ];
732
+ const rows = await executor.query(sql, params);
733
+ return rows.map((row) => ({
734
+ column: String(readRowValue(row, "column_name")),
735
+ referencedTable: String(readRowValue(row, "referenced_table")),
736
+ referencedColumn: String(readRowValue(row, "referenced_column")),
737
+ onDelete: normalizeDeleteAction(readRowValue(row, "delete_rule"))
738
+ }));
739
+ }
740
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeServerReferences, "describeServerReferences");
741
+ function expectedColumnDefinition(field, dialect) {
742
+ return {
743
+ type: normalizeColumnType(dialect, getSqlColumnType(field, dialect)),
744
+ nullable: !field.primaryKey && isNullableField(field),
745
+ default: expectedDefault(field),
746
+ primaryKey: field.primaryKey === true
747
+ };
748
+ }
749
+ _chunkS3JO3N4Hcjs.__name.call(void 0, expectedColumnDefinition, "expectedColumnDefinition");
750
+ function actualColumnDefinition(column, field, dialect) {
751
+ return {
752
+ type: column.type,
753
+ nullable: column.nullable,
754
+ default: normalizeDatabaseDefault(column.rawDefault, field, dialect),
755
+ primaryKey: column.primaryKey
756
+ };
757
+ }
758
+ _chunkS3JO3N4Hcjs.__name.call(void 0, actualColumnDefinition, "actualColumnDefinition");
759
+ function expectedDefault(field) {
760
+ if (field.default === void 0) return null;
761
+ if (field.type === "datetime" && field.default === "now") return "CURRENT_TIMESTAMP";
762
+ if (typeof field.default === "string") return JSON.stringify(field.default);
763
+ if (typeof field.default === "number" || typeof field.default === "boolean") {
764
+ return String(field.default);
765
+ }
766
+ return null;
767
+ }
768
+ _chunkS3JO3N4Hcjs.__name.call(void 0, expectedDefault, "expectedDefault");
769
+ function normalizeDatabaseDefault(value, field, dialect) {
770
+ if (value === null) return null;
771
+ let normalized = stripWrappingParentheses(value.trim());
772
+ if (dialect === "postgres") {
773
+ normalized = normalized.replace(/::[\w\s"]+$/u, "");
774
+ }
775
+ if (field.type === "datetime" && /^(?:current_timestamp(?:\(\d+\))?|now\(\))$/iu.test(normalized)) {
776
+ return "CURRENT_TIMESTAMP";
777
+ }
778
+ if (field.type === "boolean") {
779
+ const booleanValue = stripSqlQuotes(normalized).toLowerCase();
780
+ if (["1", "true", "t", "b'1'"].includes(booleanValue)) return "true";
781
+ if (["0", "false", "f", "b'0'"].includes(booleanValue)) return "false";
782
+ }
783
+ if (field.type === "integer" || field.type === "number") {
784
+ return stripSqlQuotes(normalized);
785
+ }
786
+ if (["id", "uuid", "string", "text", "enum", "datetime"].includes(field.type)) {
787
+ return JSON.stringify(stripSqlQuotes(normalized).replace(/''/gu, "'"));
788
+ }
789
+ return normalized.toUpperCase();
790
+ }
791
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeDatabaseDefault, "normalizeDatabaseDefault");
792
+ function normalizeColumnType(dialect, value) {
793
+ const type = value.trim().toLowerCase().replace(/\s+/gu, " ");
794
+ if (dialect === "sqlite") {
795
+ if (/int/u.test(type)) return "integer";
796
+ if (/(?:char|clob|text)/u.test(type)) return "text";
797
+ if (/(?:real|floa|doub)/u.test(type)) return "real";
798
+ if (/blob/u.test(type) || type === "") return "blob";
799
+ return "numeric";
800
+ }
801
+ if (dialect === "mysql") {
802
+ if (/^(?:bool|boolean|tinyint\(1\))/u.test(type)) return "boolean";
803
+ if (/^(?:int|integer)(?:\(\d+\))?/u.test(type)) return "integer";
804
+ if (/^(?:double|double precision)/u.test(type)) return "double";
805
+ return type;
806
+ }
807
+ if (["int4", "integer"].includes(type)) return "integer";
808
+ if (["float8", "double precision"].includes(type)) return "double precision";
809
+ if (["timestamptz", "timestamp with time zone"].includes(type)) return "timestamptz";
810
+ return type;
811
+ }
812
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeColumnType, "normalizeColumnType");
813
+ function collectExpectedIndexes(model) {
814
+ const indexes = [];
815
+ for (const field of Object.values(model.model.fields)) {
816
+ if (field.index) {
817
+ indexes.push({
818
+ name: `${model.modelName}_${field.name}_idx`,
819
+ columns: [field.name],
820
+ unique: false
821
+ });
822
+ }
823
+ if (!field.primaryKey && field.unique) {
824
+ indexes.push({
825
+ name: `${model.modelName}_${field.name}_unique`,
826
+ columns: [field.name],
827
+ unique: true
828
+ });
829
+ }
830
+ }
831
+ for (const constraint of _nullishCoalesce(model.model.constraints, () => ( []))) {
832
+ indexes.push({
833
+ name: _nullishCoalesce(constraint.name, () => ( `${model.modelName}_${constraint.fields.map((fieldKey) => _nullishCoalesce(_optionalChain([model, 'access', _26 => _26.model, 'access', _27 => _27.fields, 'access', _28 => _28[fieldKey], 'optionalAccess', _29 => _29.name]), () => ( fieldKey))).join("_")}_${constraint.type}`)),
834
+ columns: constraint.fields.map((fieldKey) => _nullishCoalesce(_optionalChain([model, 'access', _30 => _30.model, 'access', _31 => _31.fields, 'access', _32 => _32[fieldKey], 'optionalAccess', _33 => _33.name]), () => ( fieldKey))),
835
+ unique: constraint.type === "unique"
836
+ });
837
+ }
838
+ return indexes;
839
+ }
840
+ _chunkS3JO3N4Hcjs.__name.call(void 0, collectExpectedIndexes, "collectExpectedIndexes");
841
+ function collectExpectedReferences(model, modelLookup) {
842
+ const references = [];
843
+ for (const field of Object.values(model.model.fields)) {
844
+ if (!field.reference || !_chunkJSROZYYOcjs.isDatabaseEnforcedReference.call(void 0, field.reference)) continue;
845
+ const target = modelLookup.get(`${model.ownerKey}.${field.reference.model}`);
846
+ if (!target) continue;
847
+ references.push({
848
+ column: field.name,
849
+ referencedTable: target.modelName,
850
+ referencedColumn: _nullishCoalesce(_optionalChain([target, 'access', _34 => _34.model, 'access', _35 => _35.fields, 'access', _36 => _36[field.reference.field], 'optionalAccess', _37 => _37.name]), () => ( field.reference.field)),
851
+ onDelete: _nullishCoalesce(field.reference.onDelete, () => ( "noAction"))
852
+ });
853
+ }
854
+ return references;
855
+ }
856
+ _chunkS3JO3N4Hcjs.__name.call(void 0, collectExpectedReferences, "collectExpectedReferences");
857
+ function compareDefinitions(expected, actual, signature) {
858
+ const remaining = [...actual];
859
+ const missing = [];
860
+ for (const expectedValue of expected) {
861
+ const expectedSignature = signature(expectedValue);
862
+ const actualIndex = remaining.findIndex(
863
+ (actualValue) => signature(actualValue) === expectedSignature
864
+ );
865
+ if (actualIndex === -1) missing.push(expectedValue);
866
+ else remaining.splice(actualIndex, 1);
867
+ }
868
+ return { missing, extra: remaining };
869
+ }
870
+ _chunkS3JO3N4Hcjs.__name.call(void 0, compareDefinitions, "compareDefinitions");
871
+ function indexSignature(index) {
872
+ return `${index.unique ? "unique" : "index"}:${index.columns.map((column) => column.toLowerCase()).join(",")}`;
873
+ }
874
+ _chunkS3JO3N4Hcjs.__name.call(void 0, indexSignature, "indexSignature");
875
+ function referenceSignature(reference) {
876
+ return [
877
+ reference.column,
878
+ reference.referencedTable,
879
+ reference.referencedColumn,
880
+ reference.onDelete
881
+ ].map((value) => value.toLowerCase()).join(":");
882
+ }
883
+ _chunkS3JO3N4Hcjs.__name.call(void 0, referenceSignature, "referenceSignature");
884
+ function hasSchemaDrift(drift) {
885
+ return drift.missingColumns.length > 0 || drift.extraColumns.length > 0 || drift.changedColumns.length > 0 || drift.missingIndexes.length > 0 || drift.extraIndexes.length > 0 || drift.missingReferences.length > 0 || drift.extraReferences.length > 0;
886
+ }
887
+ _chunkS3JO3N4Hcjs.__name.call(void 0, hasSchemaDrift, "hasSchemaDrift");
888
+ function readRowValue(row, name) {
889
+ return _nullishCoalesce(row[name], () => ( row[name.toUpperCase()]));
890
+ }
891
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readRowValue, "readRowValue");
892
+ function nullableString(value) {
893
+ return value === void 0 || value === null ? null : String(value);
894
+ }
895
+ _chunkS3JO3N4Hcjs.__name.call(void 0, nullableString, "nullableString");
896
+ function asBoolean(value) {
897
+ return value === true || value === 1 || value === "1" || String(value).toLowerCase() === "true";
898
+ }
899
+ _chunkS3JO3N4Hcjs.__name.call(void 0, asBoolean, "asBoolean");
900
+ function normalizeDeleteAction(value) {
901
+ switch (String(_nullishCoalesce(value, () => ( "NO ACTION"))).toUpperCase().replace(/[_\s]+/gu, "")) {
902
+ case "CASCADE":
903
+ return "cascade";
904
+ case "RESTRICT":
905
+ return "restrict";
906
+ case "SETNULL":
907
+ return "setNull";
908
+ default:
909
+ return "noAction";
910
+ }
911
+ }
912
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeDeleteAction, "normalizeDeleteAction");
913
+ function stripWrappingParentheses(value) {
914
+ let result = value;
915
+ while (result.startsWith("(") && result.endsWith(")")) {
916
+ result = result.slice(1, -1).trim();
917
+ }
918
+ return result;
919
+ }
920
+ _chunkS3JO3N4Hcjs.__name.call(void 0, stripWrappingParentheses, "stripWrappingParentheses");
921
+ function stripSqlQuotes(value) {
922
+ if (value.length >= 2 && (value.startsWith("'") && value.endsWith("'") || value.startsWith('"') && value.endsWith('"'))) {
923
+ return value.slice(1, -1);
924
+ }
925
+ return value;
926
+ }
927
+ _chunkS3JO3N4Hcjs.__name.call(void 0, stripSqlQuotes, "stripSqlQuotes");
928
+ function escapeSqlitePragmaValue(value) {
929
+ return value.replace(/'/gu, "''");
930
+ }
931
+ _chunkS3JO3N4Hcjs.__name.call(void 0, escapeSqlitePragmaValue, "escapeSqlitePragmaValue");
932
+ async function applySchemaMigration(plan, executor) {
933
+ const applied = [];
934
+ for (const statement of [...plan.statements, ..._nullishCoalesce(plan.upgrades, () => ( []))]) {
935
+ await executor.execute(statement.sql);
936
+ applied.push(statement.target);
937
+ }
938
+ return { applied, skipped: plan.drift };
939
+ }
940
+ _chunkS3JO3N4Hcjs.__name.call(void 0, applySchemaMigration, "applySchemaMigration");
941
+ function columnTypeFamily(type) {
942
+ const value = type.trim().toLowerCase();
943
+ if (/^(bool|boolean|tinyint\(1\))/u.test(value)) return "boolean";
944
+ if (value.startsWith("uuid")) return "uuid";
945
+ if (/(char|text|clob|citext|string)/u.test(value)) return "text";
946
+ if (/^(int|integer|smallint|bigint|mediumint|tinyint|int[248]|serial|bigserial)/u.test(value)) {
947
+ return "integer";
948
+ }
949
+ if (/^(double|real|float|numeric|decimal|number)/u.test(value)) return "number";
950
+ if (/^(timestamp|datetime|date)/u.test(value)) return "datetime";
951
+ if (value.startsWith("json")) return "json";
952
+ return void 0;
953
+ }
954
+ _chunkS3JO3N4Hcjs.__name.call(void 0, columnTypeFamily, "columnTypeFamily");
955
+ async function planSchemaExtensions(extensions, dialect, executor) {
956
+ const plan = {
957
+ statements: [],
958
+ present: [],
959
+ missingTables: [],
960
+ conflicts: [],
961
+ unsupported: []
962
+ };
963
+ for (const extension of extensions) {
964
+ const table = await describeSchemaTable(executor, dialect, extension.table);
965
+ if (!table) {
966
+ plan.missingTables.push(extension);
967
+ continue;
968
+ }
969
+ for (const { fieldKey, field } of extension.fields) {
970
+ const existing = table.columns.find(
971
+ (column) => dialect === "postgres" ? column.name === field.name : column.name.toLowerCase() === field.name.toLowerCase()
972
+ );
973
+ const expected = getSqlColumnType(field, dialect);
974
+ if (existing) {
975
+ const mine = columnTypeFamily(expected);
976
+ const theirs = columnTypeFamily(existing.type);
977
+ if (dialect !== "sqlite" && mine && theirs && mine !== theirs) {
978
+ plan.conflicts.push({ extension, column: field.name, expected, actual: existing.type });
979
+ } else {
980
+ plan.present.push(`${extension.table}.${field.name}`);
981
+ }
982
+ continue;
983
+ }
984
+ const reason = unsupportedColumnReason(field, dialect);
985
+ if (reason) {
986
+ plan.unsupported.push({ extension, column: field.name, reason });
987
+ continue;
988
+ }
989
+ plan.statements.push({
990
+ kind: "column",
991
+ target: `${extension.table}.${field.name}`,
992
+ sql: addColumnStatement(dialect, extension.table, field),
993
+ extension,
994
+ fieldKey,
995
+ column: field.name
996
+ });
997
+ }
998
+ }
999
+ return plan;
1000
+ }
1001
+ _chunkS3JO3N4Hcjs.__name.call(void 0, planSchemaExtensions, "planSchemaExtensions");
1002
+ function addColumnStatement(dialect, table, field) {
1003
+ const defaultValue = getSqlDefaultExpression(field, dialect);
1004
+ const parts = [
1005
+ `ALTER TABLE ${quoteTableName(dialect, table)} ADD COLUMN`,
1006
+ quoteSqlIdentifier(dialect, field.name),
1007
+ getSqlColumnType(field, dialect),
1008
+ ...isNullableField(field) ? [] : ["NOT NULL"],
1009
+ ...defaultValue ? [`DEFAULT ${defaultValue}`] : []
1010
+ ];
1011
+ return `${parts.join(" ")};`;
1012
+ }
1013
+ _chunkS3JO3N4Hcjs.__name.call(void 0, addColumnStatement, "addColumnStatement");
1014
+ function unsupportedColumnReason(field, dialect) {
1015
+ const type = getSqlColumnType(field, dialect);
1016
+ const defaultValue = getSqlDefaultExpression(field, dialect);
1017
+ if (dialect === "mysql" && defaultValue && (type === "TEXT" || type === "JSON")) {
1018
+ return `MySQL cannot give a ${type} column a default. Make it nullable without a default.`;
1019
+ }
1020
+ if (dialect === "sqlite" && defaultValue === "CURRENT_TIMESTAMP") {
1021
+ return "SQLite cannot add a column whose default is the current time. Make it nullable.";
1022
+ }
1023
+ if (!isNullableField(field) && !defaultValue) {
1024
+ return "It is required but its default cannot be written in SQL. Make it nullable.";
1025
+ }
1026
+ return void 0;
1027
+ }
1028
+ _chunkS3JO3N4Hcjs.__name.call(void 0, unsupportedColumnReason, "unsupportedColumnReason");
1029
+ function quoteTableName(dialect, table) {
1030
+ const dot = table.indexOf(".");
1031
+ if (dialect === "sqlite" || dot <= 0) return quoteSqlIdentifier(dialect, table);
1032
+ return `${quoteSqlIdentifier(dialect, table.slice(0, dot))}.${quoteSqlIdentifier(dialect, table.slice(dot + 1))}`;
1033
+ }
1034
+ _chunkS3JO3N4Hcjs.__name.call(void 0, quoteTableName, "quoteTableName");
1035
+ function formatSchemaMigration(plan, owner, options = {}) {
1036
+ const header = [
1037
+ `-- Generated by \`farm ${owner} migrate\` from the ${owner} schema.`,
1038
+ `-- Dialect: ${plan.dialect}`,
1039
+ options.addsColumns || (_nullishCoalesce(_optionalChain([plan, 'access', _38 => _38.upgrades, 'optionalAccess', _39 => _39.length]), () => ( 0))) > 0 ? "-- Review before applying. Existing tables only get what is added below; nothing is changed or dropped." : "-- Review before applying. Farm never alters existing tables."
1040
+ ];
1041
+ const upgrades = _nullishCoalesce(plan.upgrades, () => ( []));
1042
+ if (plan.statements.length === 0 && upgrades.length === 0) {
1043
+ header.push("--", "-- Nothing to create: every declared model already has a table.");
1044
+ return `${header.join("\n")}
1045
+ `;
1046
+ }
1047
+ const sections = [
1048
+ ...plan.statements.map((statement) => statement.sql),
1049
+ ...upgrades.length > 0 ? [
1050
+ [
1051
+ "-- Added to tables that already exist:",
1052
+ ...upgrades.map((statement) => statement.sql)
1053
+ ].join("\n")
1054
+ ] : []
1055
+ ];
1056
+ return `${header.join("\n")}
1057
+
1058
+ ${sections.join("\n\n")}
1059
+ `;
1060
+ }
1061
+ _chunkS3JO3N4Hcjs.__name.call(void 0, formatSchemaMigration, "formatSchemaMigration");
1062
+ function describeSchemaDrift(drift) {
1063
+ return drift.map((entry) => {
1064
+ const lines = [` ${entry.table}`];
1065
+ if (entry.missingColumns.length > 0) {
1066
+ lines.push(` missing in the database: ${entry.missingColumns.join(", ")}`);
1067
+ }
1068
+ if (entry.extraColumns.length > 0) {
1069
+ lines.push(` not in the schema: ${entry.extraColumns.join(", ")}`);
1070
+ }
1071
+ for (const column of entry.changedColumns) {
1072
+ const differences = column.differences.map((difference) => {
1073
+ if (difference === "type") {
1074
+ return `type expected ${column.expected.type}, found ${column.actual.type}`;
1075
+ }
1076
+ if (difference === "nullability") {
1077
+ return `nullability expected ${column.expected.nullable ? "nullable" : "required"}, found ${column.actual.nullable ? "nullable" : "required"}`;
1078
+ }
1079
+ if (difference === "default") {
1080
+ return `default expected ${_nullishCoalesce(column.expected.default, () => ( "none"))}, found ${_nullishCoalesce(column.actual.default, () => ( "none"))}`;
1081
+ }
1082
+ return `primary key expected ${column.expected.primaryKey ? "yes" : "no"}, found ${column.actual.primaryKey ? "yes" : "no"}`;
1083
+ });
1084
+ lines.push(` changed column ${column.column}: ${differences.join("; ")}`);
1085
+ }
1086
+ if (entry.missingIndexes.length > 0) {
1087
+ lines.push(
1088
+ ` missing indexes: ${entry.missingIndexes.map(formatIndexDefinition).join(", ")}`
1089
+ );
1090
+ }
1091
+ if (entry.extraIndexes.length > 0) {
1092
+ lines.push(
1093
+ ` not in the schema indexes: ${entry.extraIndexes.map(formatIndexDefinition).join(", ")}`
1094
+ );
1095
+ }
1096
+ if (entry.missingReferences.length > 0) {
1097
+ lines.push(
1098
+ ` missing references: ${entry.missingReferences.map(formatReferenceDefinition).join(", ")}`
1099
+ );
1100
+ }
1101
+ if (entry.extraReferences.length > 0) {
1102
+ lines.push(
1103
+ ` not in the schema references: ${entry.extraReferences.map(formatReferenceDefinition).join(", ")}`
1104
+ );
1105
+ }
1106
+ return lines.join("\n");
1107
+ }).join("\n");
1108
+ }
1109
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeSchemaDrift, "describeSchemaDrift");
1110
+ function formatIndexDefinition(index) {
1111
+ return `${index.name} (${index.unique ? "unique: " : ""}${index.columns.join(", ")})`;
1112
+ }
1113
+ _chunkS3JO3N4Hcjs.__name.call(void 0, formatIndexDefinition, "formatIndexDefinition");
1114
+ function formatReferenceDefinition(reference) {
1115
+ return `${reference.column} -> ${reference.referencedTable}.${reference.referencedColumn} on delete ${reference.onDelete}`;
1116
+ }
1117
+ _chunkS3JO3N4Hcjs.__name.call(void 0, formatReferenceDefinition, "formatReferenceDefinition");
1118
+ function createSchemaExecutor(client, owner) {
1119
+ const candidate = client;
1120
+ if (candidate && typeof candidate.getItem === "function" && typeof candidate.setItem === "function") {
1121
+ return null;
1122
+ }
1123
+ if (typeof _optionalChain([candidate, 'optionalAccess', _40 => _40.prepare]) === "function" && typeof _optionalChain([candidate, 'optionalAccess', _41 => _41.exec]) === "function") {
1124
+ return {
1125
+ dialect: "sqlite",
1126
+ executor: {
1127
+ async execute(sql) {
1128
+ candidate.exec(sql);
1129
+ },
1130
+ async query(sql) {
1131
+ return candidate.prepare(sql).all();
1132
+ }
1133
+ }
1134
+ };
1135
+ }
1136
+ if (typeof _optionalChain([candidate, 'optionalAccess', _42 => _42.query]) === "function") {
1137
+ const isMysqlClient = typeof candidate.escapeId === "function" || typeof candidate.format === "function";
1138
+ return {
1139
+ dialect: isMysqlClient ? "mysql" : "postgres",
1140
+ executor: {
1141
+ async execute(sql) {
1142
+ await candidate.query(sql);
1143
+ },
1144
+ async query(sql, params) {
1145
+ const result = await candidate.query(sql, params);
1146
+ if (Array.isArray(result)) return _nullishCoalesce(result[0], () => ( []));
1147
+ return _nullishCoalesce(_optionalChain([result, 'optionalAccess', _43 => _43.rows]), () => ( []));
1148
+ }
1149
+ }
1150
+ };
1151
+ }
1152
+ throw new Error(
1153
+ `${owner}: the configured client cannot run migrations. Pass a pg, mysql, or sqlite connection, or create the tables with your own migration tooling.`
1154
+ );
1155
+ }
1156
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createSchemaExecutor, "createSchemaExecutor");
1157
+
1158
+ // src/schema-extend.ts
1159
+ function collectSchemaExtensions(owner, schema, models) {
1160
+ if (!schema.extend) return [];
1161
+ const resolved = _chunkJSROZYYOcjs.resolveSchemaModels.call(void 0, owner, schema);
1162
+ const extensions = [];
1163
+ for (const [modelKey, extension] of Object.entries(schema.extend)) {
1164
+ const model = resolved[modelKey];
1165
+ if (!model || !model.external && (!models || models.includes(modelKey))) continue;
1166
+ const fields = Object.keys(_nullishCoalesce(extension.fields, () => ( {}))).map((fieldKey) => {
1167
+ const field = model.fields[fieldKey];
1168
+ assertAddableColumn(owner, modelKey, fieldKey, field);
1169
+ return { fieldKey, field };
1170
+ });
1171
+ if (fields.length > 0) {
1172
+ extensions.push({ owner, modelKey, table: model.name, fields });
1173
+ }
1174
+ }
1175
+ return extensions;
1176
+ }
1177
+ _chunkS3JO3N4Hcjs.__name.call(void 0, collectSchemaExtensions, "collectSchemaExtensions");
1178
+ function assertAddableColumn(owner, modelKey, fieldKey, field) {
1179
+ const where = `${owner} adds "${modelKey}.${fieldKey}" to a table it does not own`;
1180
+ if (field.primaryKey || field.unique || field.index || field.list) {
1181
+ const what = field.primaryKey ? "a primary key" : field.unique ? "unique" : field.index ? "indexed" : "a list";
1182
+ throw new Error(`${where}, which cannot be ${what}. Remove it from the extension.`);
1183
+ }
1184
+ if (field.nullable !== true && field.required !== false && field.default === void 0) {
1185
+ throw new Error(
1186
+ `${where}. The table may already have rows, so the column needs a \`default\` or \`nullable: true\`.`
1187
+ );
1188
+ }
1189
+ }
1190
+ _chunkS3JO3N4Hcjs.__name.call(void 0, assertAddableColumn, "assertAddableColumn");
1191
+ function isSchemaExtensionAllowed(allowExtend, extension) {
1192
+ if (!allowExtend || !Object.prototype.hasOwnProperty.call(allowExtend, extension.owner)) {
1193
+ return false;
1194
+ }
1195
+ const allowed = _nullishCoalesce(allowExtend[extension.owner], () => ( []));
1196
+ return allowed.includes(extension.modelKey) || allowed.includes(extension.table);
1197
+ }
1198
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isSchemaExtensionAllowed, "isSchemaExtensionAllowed");
1199
+ function describeSchemaExtensionApproval(extension) {
1200
+ return `schema: { allowExtend: { ${JSON.stringify(extension.owner)}: [${JSON.stringify(extension.modelKey)}] } }`;
1201
+ }
1202
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeSchemaExtensionApproval, "describeSchemaExtensionApproval");
1203
+
1204
+ // src/schema-state.ts
1205
+ var literal = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (dialect, value) => value === null ? "NULL" : `'${escapeSqlString(value, dialect)}'`, "literal");
1206
+ var FARM_SCHEMA_STATE_TABLE = "farm_schema_state";
1207
+ function createSchemaSnapshot(models) {
1208
+ const tables = {};
1209
+ for (const model of models) {
1210
+ const columns = {};
1211
+ const indexes = [];
1212
+ for (const field of Object.values(model.model.fields)) {
1213
+ columns[field.name] = {
1214
+ type: field.type,
1215
+ nullable: field.nullable === true || field.required === false,
1216
+ primaryKey: field.primaryKey === true,
1217
+ unique: field.unique === true,
1218
+ ...field.default !== void 0 ? { default: field.default } : {}
1219
+ };
1220
+ if (field.index) indexes.push(`${model.modelName}_${field.name}_idx`);
1221
+ }
1222
+ for (const constraint of _nullishCoalesce(model.model.constraints, () => ( []))) {
1223
+ indexes.push(
1224
+ _nullishCoalesce(constraint.name, () => ( `${model.modelName}_${constraint.fields.map((key) => _nullishCoalesce(_optionalChain([model, 'access', _44 => _44.model, 'access', _45 => _45.fields, 'access', _46 => _46[key], 'optionalAccess', _47 => _47.name]), () => ( key))).join("_")}_${constraint.type}`))
1225
+ );
1226
+ }
1227
+ tables[model.modelName] = { columns, indexes: indexes.sort() };
1228
+ }
1229
+ return { tables };
1230
+ }
1231
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createSchemaSnapshot, "createSchemaSnapshot");
1232
+ function diffSchemaSnapshots(previous, next) {
1233
+ const changes = {
1234
+ addedTables: [],
1235
+ addedColumns: [],
1236
+ addedIndexes: [],
1237
+ otherChanges: [],
1238
+ removedColumns: []
1239
+ };
1240
+ for (const [table, definition] of Object.entries(next.tables)) {
1241
+ const before = previous.tables[table];
1242
+ if (!before) {
1243
+ changes.addedTables.push(table);
1244
+ continue;
1245
+ }
1246
+ for (const [column, columnDefinition] of Object.entries(definition.columns)) {
1247
+ const old = before.columns[column];
1248
+ if (!old) {
1249
+ changes.addedColumns.push({ table, column, type: columnDefinition.type });
1250
+ } else if (JSON.stringify(old) !== JSON.stringify(columnDefinition)) {
1251
+ changes.otherChanges.push(`${table}.${column} is redefined`);
1252
+ }
1253
+ }
1254
+ for (const [column, old] of Object.entries(before.columns)) {
1255
+ if (definition.columns[column]) continue;
1256
+ changes.otherChanges.push(`${table}.${column} is removed`);
1257
+ changes.removedColumns.push({ table, column, type: old.type });
1258
+ }
1259
+ for (const index of definition.indexes) {
1260
+ if (!before.indexes.includes(index)) changes.addedIndexes.push(index);
1261
+ }
1262
+ }
1263
+ for (const table of Object.keys(previous.tables)) {
1264
+ if (!next.tables[table]) changes.otherChanges.push(`${table} is removed`);
1265
+ }
1266
+ return changes;
1267
+ }
1268
+ _chunkS3JO3N4Hcjs.__name.call(void 0, diffSchemaSnapshots, "diffSchemaSnapshots");
1269
+ function hasSchemaChanges(changes) {
1270
+ return changes.addedTables.length + changes.addedColumns.length + changes.addedIndexes.length + changes.otherChanges.length > 0;
1271
+ }
1272
+ _chunkS3JO3N4Hcjs.__name.call(void 0, hasSchemaChanges, "hasSchemaChanges");
1273
+ async function readSchemaState(executor, dialect, owner) {
1274
+ const q = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (name) => quoteSqlIdentifier(dialect, name), "q");
1275
+ let rows;
1276
+ try {
1277
+ if (!await describeSchemaTable(executor, dialect, FARM_SCHEMA_STATE_TABLE)) return void 0;
1278
+ rows = await executor.query(
1279
+ `SELECT ${q("version")}, ${q("snapshot")}, ${q("applied_at")} FROM ${q(FARM_SCHEMA_STATE_TABLE)} WHERE ${q("owner")} = ${literal(dialect, owner)}`
1280
+ );
1281
+ } catch (e) {
1282
+ return void 0;
1283
+ }
1284
+ const row = rows[0];
1285
+ if (!row) return void 0;
1286
+ const read = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (name) => _nullishCoalesce(row[name], () => ( row[name.toUpperCase()])), "read");
1287
+ try {
1288
+ const snapshot = read("snapshot");
1289
+ return {
1290
+ version: read("version") == null ? void 0 : String(read("version")),
1291
+ snapshot: typeof snapshot === "string" ? JSON.parse(snapshot) : snapshot,
1292
+ appliedAt: String(read("applied_at"))
1293
+ };
1294
+ } catch (e2) {
1295
+ return void 0;
1296
+ }
1297
+ }
1298
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readSchemaState, "readSchemaState");
1299
+ async function writeSchemaState(executor, dialect, owner, state) {
1300
+ const q = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (name) => quoteSqlIdentifier(dialect, name), "q");
1301
+ const key = dialect === "mysql" ? "VARCHAR(191)" : "TEXT";
1302
+ await executor.execute(
1303
+ `CREATE TABLE IF NOT EXISTS ${q(FARM_SCHEMA_STATE_TABLE)} (${q("owner")} ${key} PRIMARY KEY, ${q("version")} ${dialect === "mysql" ? "VARCHAR(255)" : "TEXT"}, ${q("snapshot")} ${dialect === "mysql" ? "LONGTEXT" : "TEXT"} NOT NULL, ${q("applied_at")} ${dialect === "mysql" ? "VARCHAR(64)" : "TEXT"} NOT NULL)`
1304
+ );
1305
+ const values = [
1306
+ literal(dialect, owner),
1307
+ literal(dialect, _nullishCoalesce(state.version, () => ( null))),
1308
+ literal(dialect, JSON.stringify(state.snapshot)),
1309
+ literal(dialect, (/* @__PURE__ */ new Date()).toISOString())
1310
+ ];
1311
+ await executor.execute(
1312
+ `DELETE FROM ${q(FARM_SCHEMA_STATE_TABLE)} WHERE ${q("owner")} = ${values[0]}`
1313
+ );
1314
+ await executor.execute(
1315
+ `INSERT INTO ${q(FARM_SCHEMA_STATE_TABLE)} (${q("owner")}, ${q("version")}, ${q("snapshot")}, ${q("applied_at")}) VALUES (${values.join(", ")})`
1316
+ );
1317
+ }
1318
+ _chunkS3JO3N4Hcjs.__name.call(void 0, writeSchemaState, "writeSchemaState");
1319
+ function describeSchemaChanges(changes) {
1320
+ return [
1321
+ ...changes.addedTables.map((table) => ` + ${table} new table`),
1322
+ ...changes.addedColumns.map(({ table, column, type }) => ` + ${table}.${column} ${type}`),
1323
+ ...changes.addedIndexes.map((index) => ` + ${index} index`),
1324
+ ...changes.otherChanges.map((change) => ` ~ ${change} (Farm will not do this on its own)`)
1325
+ ];
1326
+ }
1327
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeSchemaChanges, "describeSchemaChanges");
1328
+
1329
+ // src/schema-steps.ts
1330
+ var FARM_SCHEMA_STEPS_TABLE = "farm_schema_steps";
1331
+ function schemaStepChecksum(step) {
1332
+ const { description: _description, ...definition } = step;
1333
+ let hash = 2166136261;
1334
+ for (const character of JSON.stringify(definition)) {
1335
+ hash ^= character.codePointAt(0);
1336
+ hash = Math.imul(hash, 16777619) >>> 0;
1337
+ }
1338
+ return hash.toString(16).padStart(8, "0");
1339
+ }
1340
+ _chunkS3JO3N4Hcjs.__name.call(void 0, schemaStepChecksum, "schemaStepChecksum");
1341
+ var literal2 = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (dialect, value) => `'${escapeSqlString(value, dialect)}'`, "literal");
1342
+ async function readAppliedSchemaSteps(executor, dialect, owner) {
1343
+ const applied = /* @__PURE__ */ new Map();
1344
+ try {
1345
+ if (!await describeSchemaTable(executor, dialect, FARM_SCHEMA_STEPS_TABLE)) return applied;
1346
+ const q = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (name) => quoteSqlIdentifier(dialect, name), "q");
1347
+ const rows = await executor.query(
1348
+ `SELECT ${q("id")}, ${q("checksum")} FROM ${q(FARM_SCHEMA_STEPS_TABLE)} WHERE ${q("owner")} = ${literal2(dialect, owner)}`
1349
+ );
1350
+ for (const row of rows) {
1351
+ const read = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (name) => _nullishCoalesce(row[name], () => ( row[name.toUpperCase()])), "read");
1352
+ applied.set(String(read("id")), String(read("checksum")));
1353
+ }
1354
+ } catch (e3) {
1355
+ }
1356
+ return applied;
1357
+ }
1358
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readAppliedSchemaSteps, "readAppliedSchemaSteps");
1359
+ function stepsTableStatement(dialect) {
1360
+ const q = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (name) => quoteSqlIdentifier(dialect, name), "q");
1361
+ const key = dialect === "mysql" ? "VARCHAR(191)" : "TEXT";
1362
+ return `CREATE TABLE IF NOT EXISTS ${q(FARM_SCHEMA_STEPS_TABLE)} (${q("owner")} ${key} NOT NULL, ${q("id")} ${key} NOT NULL, ${q("checksum")} ${dialect === "mysql" ? "VARCHAR(64)" : "TEXT"} NOT NULL, ${q("applied_at")} ${dialect === "mysql" ? "VARCHAR(64)" : "TEXT"} NOT NULL, PRIMARY KEY (${q("owner")}, ${q("id")}))`;
1363
+ }
1364
+ _chunkS3JO3N4Hcjs.__name.call(void 0, stepsTableStatement, "stepsTableStatement");
1365
+ function recordStatement(dialect, owner, step) {
1366
+ const q = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (name) => quoteSqlIdentifier(dialect, name), "q");
1367
+ return `INSERT INTO ${q(FARM_SCHEMA_STEPS_TABLE)} (${q("owner")}, ${q("id")}, ${q("checksum")}, ${q("applied_at")}) VALUES (${[owner, step.id, schemaStepChecksum(step), (/* @__PURE__ */ new Date()).toISOString()].map((value) => literal2(dialect, value)).join(", ")})`;
1368
+ }
1369
+ _chunkS3JO3N4Hcjs.__name.call(void 0, recordStatement, "recordStatement");
1370
+ async function planSchemaSteps(input) {
1371
+ const { owner, dialect, executor, applied } = input;
1372
+ const plan = { steps: [], edited: [], fresh: input.fresh };
1373
+ const models = _chunkJSROZYYOcjs.resolveSchemaModels.call(void 0, owner, input.schema);
1374
+ const q = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (name) => quoteSqlIdentifier(dialect, name), "q");
1375
+ const columnsOf = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async (table) => await _asyncOptionalChain([(await describeSchemaTable(executor, dialect, table)), 'optionalAccess', async _48 => _48.columns, 'access', async _49 => _49.map, 'call', async _50 => _50((column) => column.name)]), "columnsOf");
1376
+ const has = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (columns, name) => Boolean(
1377
+ _optionalChain([columns, 'optionalAccess', _51 => _51.some, 'call', _52 => _52(
1378
+ (column) => dialect === "postgres" ? column === name : column.toLowerCase() === name.toLowerCase()
1379
+ )])
1380
+ ), "has");
1381
+ for (const step of input.steps) {
1382
+ const recorded = applied.get(step.id);
1383
+ if (recorded !== void 0) {
1384
+ if (recorded !== schemaStepChecksum(step)) plan.edited.push(step.id);
1385
+ continue;
1386
+ }
1387
+ if (input.fresh) {
1388
+ plan.steps.push({
1389
+ step,
1390
+ summary: summarize(step, models),
1391
+ phase: "before",
1392
+ statements: [],
1393
+ state: "record"
1394
+ });
1395
+ continue;
1396
+ }
1397
+ if ("renameColumn" in step) {
1398
+ const table = models[step.renameColumn.model].name;
1399
+ const to = models[step.renameColumn.model].fields[step.renameColumn.to].name;
1400
+ const from = step.renameColumn.from;
1401
+ const columns = await columnsOf(table);
1402
+ const summary = `rename ${table}.${from} \u2192 ${table}.${to}`;
1403
+ const planned = {
1404
+ step,
1405
+ summary,
1406
+ phase: "before",
1407
+ statements: [`ALTER TABLE ${q(table)} RENAME COLUMN ${q(from)} TO ${q(to)}`],
1408
+ state: "run"
1409
+ };
1410
+ if (!columns) {
1411
+ Object.assign(planned, { state: "blocked", reason: `"${table}" does not exist.` });
1412
+ } else if (has(columns, from) && has(columns, to)) {
1413
+ Object.assign(planned, {
1414
+ state: "blocked",
1415
+ reason: `both "${from}" and "${to}" exist, so renaming would lose one. Move the data and drop one column yourself.`
1416
+ });
1417
+ } else if (!has(columns, from)) {
1418
+ Object.assign(planned, {
1419
+ state: has(columns, to) ? "record" : "blocked",
1420
+ statements: [],
1421
+ ...has(columns, to) ? {} : { reason: `"${table}" has neither "${from}" nor "${to}".` }
1422
+ });
1423
+ }
1424
+ plan.steps.push(planned);
1425
+ } else if ("renameTable" in step) {
1426
+ const to = models[step.renameTable.to].name;
1427
+ const from = step.renameTable.from;
1428
+ const summary = `rename table ${from} \u2192 ${to}`;
1429
+ const [hasFrom, hasTo] = [Boolean(await columnsOf(from)), Boolean(await columnsOf(to))];
1430
+ plan.steps.push({
1431
+ step,
1432
+ summary,
1433
+ phase: "before",
1434
+ statements: hasFrom && !hasTo ? [
1435
+ dialect === "mysql" ? `RENAME TABLE ${q(from)} TO ${q(to)}` : `ALTER TABLE ${q(from)} RENAME TO ${q(to)}`
1436
+ ] : [],
1437
+ state: hasFrom && !hasTo ? "run" : hasTo && !hasFrom ? "record" : "blocked",
1438
+ ...hasFrom && hasTo ? { reason: `both "${from}" and "${to}" exist, so renaming would lose one.` } : !hasFrom && !hasTo ? { reason: `neither "${from}" nor "${to}" exists.` } : {}
1439
+ });
1440
+ } else if ("dropColumn" in step) {
1441
+ const table = models[step.dropColumn.model].name;
1442
+ const column = step.dropColumn.column;
1443
+ const columns = await columnsOf(table);
1444
+ const summary = `drop ${table}.${column}`;
1445
+ const created = Boolean(_optionalChain([input, 'access', _53 => _53.recorded, 'optionalAccess', _54 => _54.tables, 'access', _55 => _55[table], 'optionalAccess', _56 => _56.columns, 'access', _57 => _57[column]]));
1446
+ const planned = {
1447
+ step,
1448
+ summary,
1449
+ phase: "before",
1450
+ statements: [`ALTER TABLE ${q(table)} DROP COLUMN ${q(column)}`],
1451
+ state: "run",
1452
+ destructive: true
1453
+ };
1454
+ if (!columns) {
1455
+ Object.assign(planned, { state: "blocked", reason: `"${table}" does not exist.` });
1456
+ } else if (!has(columns, column)) {
1457
+ Object.assign(planned, { state: "record", statements: [] });
1458
+ } else if (!created) {
1459
+ Object.assign(planned, {
1460
+ state: "blocked",
1461
+ reason: `Farm has no record of ${owner} creating "${table}.${column}", so it will not drop it. Drop it yourself if it is no longer needed.`
1462
+ });
1463
+ }
1464
+ plan.steps.push(planned);
1465
+ } else if ("dropTable" in step) {
1466
+ const table = step.dropTable.table;
1467
+ const exists = Boolean(await columnsOf(table));
1468
+ const created = Boolean(_optionalChain([input, 'access', _58 => _58.recorded, 'optionalAccess', _59 => _59.tables, 'access', _60 => _60[table]]));
1469
+ const ownedElsewhere = [..._nullishCoalesce(input.othersTables, () => ( []))].some(
1470
+ (other) => other.toLowerCase() === table.toLowerCase()
1471
+ );
1472
+ plan.steps.push({
1473
+ step,
1474
+ summary: `drop table ${table}`,
1475
+ phase: "before",
1476
+ statements: exists ? [`DROP TABLE ${q(table)}`] : [],
1477
+ destructive: true,
1478
+ ...!exists ? { state: "record" } : ownedElsewhere ? {
1479
+ state: "blocked",
1480
+ reason: `another plugin creates "${table}", so ${owner} will not drop it.`
1481
+ } : !created ? {
1482
+ state: "blocked",
1483
+ reason: `Farm has no record of ${owner} creating "${table}", so it will not drop it. Drop it yourself if it is no longer needed.`
1484
+ } : { state: "run" }
1485
+ });
1486
+ } else {
1487
+ const sql = step.sql[dialect];
1488
+ const statements = sql === void 0 ? [] : typeof sql === "string" ? [sql] : [...sql];
1489
+ plan.steps.push({
1490
+ step,
1491
+ summary: _nullishCoalesce(step.description, () => ( `custom SQL (${step.id})`)),
1492
+ phase: step.before ? "before" : "after",
1493
+ statements,
1494
+ state: sql === void 0 ? "blocked" : "run",
1495
+ ...sql === void 0 ? { reason: `it has no SQL for ${dialect}.` } : {}
1496
+ });
1497
+ }
1498
+ }
1499
+ return plan;
1500
+ }
1501
+ _chunkS3JO3N4Hcjs.__name.call(void 0, planSchemaSteps, "planSchemaSteps");
1502
+ function summarize(step, models) {
1503
+ if ("renameColumn" in step) {
1504
+ const model = models[step.renameColumn.model];
1505
+ return `rename ${model.name}.${step.renameColumn.from} \u2192 ${model.name}.${model.fields[step.renameColumn.to].name}`;
1506
+ }
1507
+ if ("renameTable" in step) {
1508
+ return `rename table ${step.renameTable.from} \u2192 ${models[step.renameTable.to].name}`;
1509
+ }
1510
+ if ("dropColumn" in step) {
1511
+ return `drop ${models[step.dropColumn.model].name}.${step.dropColumn.column}`;
1512
+ }
1513
+ if ("dropTable" in step) return `drop table ${step.dropTable.table}`;
1514
+ return _nullishCoalesce(step.description, () => ( `custom SQL (${step.id})`));
1515
+ }
1516
+ _chunkS3JO3N4Hcjs.__name.call(void 0, summarize, "summarize");
1517
+ async function runSchemaStep(executor, dialect, owner, planned) {
1518
+ await executor.execute(stepsTableStatement(dialect));
1519
+ const statements = [
1520
+ ...planned.state === "run" ? planned.statements : [],
1521
+ recordStatement(dialect, owner, planned.step)
1522
+ ];
1523
+ if (dialect === "postgres") {
1524
+ await executor.execute(
1525
+ statements.map((statement) => statement.replace(/;\s*$/u, "")).join(";\n")
1526
+ );
1527
+ return;
1528
+ }
1529
+ if (dialect === "sqlite") {
1530
+ await executor.execute("BEGIN");
1531
+ try {
1532
+ for (const statement of statements) await executor.execute(statement);
1533
+ await executor.execute("COMMIT");
1534
+ } catch (error) {
1535
+ await executor.execute("ROLLBACK").catch(() => {
1536
+ });
1537
+ throw error;
1538
+ }
1539
+ return;
1540
+ }
1541
+ for (const statement of statements) await executor.execute(statement);
1542
+ }
1543
+ _chunkS3JO3N4Hcjs.__name.call(void 0, runSchemaStep, "runSchemaStep");
1544
+ function withoutRenameTargets(models, stepPlan) {
1545
+ const pending = (_nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _61 => _61.steps]), () => ( []))).filter((planned) => planned.state === "run");
1546
+ if (pending.length === 0) return models;
1547
+ const tables = /* @__PURE__ */ new Set();
1548
+ const columns = /* @__PURE__ */ new Map();
1549
+ for (const { step } of pending) {
1550
+ if ("renameTable" in step) tables.add(step.renameTable.to);
1551
+ if ("renameColumn" in step) {
1552
+ const set = _nullishCoalesce(columns.get(step.renameColumn.model), () => ( /* @__PURE__ */ new Set()));
1553
+ set.add(step.renameColumn.to);
1554
+ columns.set(step.renameColumn.model, set);
1555
+ }
1556
+ }
1557
+ return models.filter((model) => !tables.has(model.modelKey)).map((model) => {
1558
+ const skip = columns.get(model.modelKey);
1559
+ if (!skip) return model;
1560
+ const fields = Object.fromEntries(
1561
+ Object.entries(model.model.fields).filter(([key]) => !skip.has(key))
1562
+ );
1563
+ return { ...model, model: { ...model.model, fields } };
1564
+ });
1565
+ }
1566
+ _chunkS3JO3N4Hcjs.__name.call(void 0, withoutRenameTargets, "withoutRenameTargets");
1567
+ async function planOwnerSchemaSteps(input) {
1568
+ const applied = input.readApplied === false ? /* @__PURE__ */ new Map() : await readAppliedSchemaSteps(input.executor, input.dialect, input.owner);
1569
+ const candidates = [
1570
+ ...input.tables,
1571
+ ...input.steps.flatMap((step) => "renameTable" in step ? [step.renameTable.from] : [])
1572
+ ];
1573
+ let fresh = applied.size === 0;
1574
+ for (const table of candidates) {
1575
+ if (!fresh) break;
1576
+ if (await describeSchemaTable(input.executor, input.dialect, table)) fresh = false;
1577
+ }
1578
+ const recorded = input.readApplied === false ? void 0 : await _asyncOptionalChain([(await readSchemaState(input.executor, input.dialect, input.owner)), 'optionalAccess', async _62 => _62.snapshot]);
1579
+ return planSchemaSteps({ ...input, applied, fresh, recorded });
1580
+ }
1581
+ _chunkS3JO3N4Hcjs.__name.call(void 0, planOwnerSchemaSteps, "planOwnerSchemaSteps");
1582
+
1583
+ // src/schema-owner.ts
1584
+ var FARM_SCHEMA_TABLES = /* @__PURE__ */ Symbol.for("farm.schema-tables");
1585
+ function declareSchemaTables(target, declaration) {
1586
+ Object.defineProperty(target, FARM_SCHEMA_TABLES, {
1587
+ value: declaration,
1588
+ enumerable: false,
1589
+ configurable: true
1590
+ });
1591
+ return target;
1592
+ }
1593
+ _chunkS3JO3N4Hcjs.__name.call(void 0, declareSchemaTables, "declareSchemaTables");
1594
+ function readSchemaTables(candidate) {
1595
+ if (!candidate || typeof candidate !== "object" && typeof candidate !== "function") {
1596
+ return void 0;
1597
+ }
1598
+ return candidate[FARM_SCHEMA_TABLES];
1599
+ }
1600
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readSchemaTables, "readSchemaTables");
1601
+
1602
+ // src/schema-foreign-keys.ts
1603
+ async function planCrossOwnerReferences(owner, others, dialect, executor) {
1604
+ const plan = { eligible: [], waiting: [], skipped: [] };
1605
+ const own = _chunkJSROZYYOcjs.resolveSchemaModels.call(void 0, owner.name, owner.schema);
1606
+ const creators = /* @__PURE__ */ new Map();
1607
+ const byKey = /* @__PURE__ */ new Map();
1608
+ for (const other of others) {
1609
+ if (other.name === owner.name) continue;
1610
+ try {
1611
+ for (const model of collectSchemaModels([[other.name, other.schema, other.models]])) {
1612
+ creators.set(model.modelName.toLowerCase(), { owner: other.name, model });
1613
+ byKey.set(model.modelKey, model);
1614
+ }
1615
+ } catch (e4) {
1616
+ }
1617
+ }
1618
+ for (const model of collectSchemaModels([[owner.name, owner.schema, owner.models]])) {
1619
+ for (const [fieldKey, field] of Object.entries(model.model.fields)) {
1620
+ const reference = field.reference;
1621
+ if (!reference || !_chunkJSROZYYOcjs.isDatabaseEnforcedReference.call(void 0, reference)) continue;
1622
+ const described = Object.prototype.hasOwnProperty.call(own, reference.model) ? own[reference.model].name : _optionalChain([byKey, 'access', _63 => _63.get, 'call', _64 => _64(reference.model), 'optionalAccess', _65 => _65.modelName]);
1623
+ const creator = described ? creators.get(described.toLowerCase()) : void 0;
1624
+ if (!creator) continue;
1625
+ const target = _optionalChain([Object, 'access', _66 => _66.entries, 'call', _67 => _67(creator.model.model.fields), 'access', _68 => _68.find, 'call', _69 => _69(
1626
+ ([key, candidate]) => key === reference.field || candidate.name === reference.field
1627
+ ), 'optionalAccess', _70 => _70[1]]);
1628
+ const entry = {
1629
+ owner: owner.name,
1630
+ modelKey: model.modelKey,
1631
+ fieldKey,
1632
+ table: model.modelName,
1633
+ column: field.name,
1634
+ referencedOwner: creator.owner,
1635
+ referencedTable: creator.model.modelName,
1636
+ referencedColumn: _nullishCoalesce(_optionalChain([target, 'optionalAccess', _71 => _71.name]), () => ( reference.field)),
1637
+ onDelete: _nullishCoalesce(reference.onDelete, () => ( "noAction"))
1638
+ };
1639
+ if (!target || !(target.primaryKey || target.unique)) {
1640
+ plan.skipped.push({
1641
+ reference: entry,
1642
+ reason: `"${entry.referencedTable}.${entry.referencedColumn}" is not its primary key or unique.`
1643
+ });
1644
+ continue;
1645
+ }
1646
+ const mine = columnTypeFamily(getSqlColumnType(field, dialect));
1647
+ const theirs = columnTypeFamily(getSqlColumnType(target, dialect));
1648
+ if (dialect !== "sqlite" && mine !== theirs) {
1649
+ plan.skipped.push({ reference: entry, reason: "the column types differ." });
1650
+ continue;
1651
+ }
1652
+ const table = await describeSchemaTable(executor, dialect, entry.referencedTable);
1653
+ if (!table) {
1654
+ plan.waiting.push(entry);
1655
+ continue;
1656
+ }
1657
+ const column = table.columns.find(
1658
+ (candidate) => dialect === "postgres" ? candidate.name === entry.referencedColumn : candidate.name.toLowerCase() === entry.referencedColumn.toLowerCase()
1659
+ );
1660
+ if (!column) {
1661
+ plan.skipped.push({
1662
+ reference: entry,
1663
+ reason: `"${entry.referencedTable}" has no column "${entry.referencedColumn}".`
1664
+ });
1665
+ continue;
1666
+ }
1667
+ plan.eligible.push(entry);
1668
+ }
1669
+ }
1670
+ return plan;
1671
+ }
1672
+ _chunkS3JO3N4Hcjs.__name.call(void 0, planCrossOwnerReferences, "planCrossOwnerReferences");
1673
+ function isForeignKeyAllowed(allowForeignKeys, reference) {
1674
+ if (!allowForeignKeys || !Object.prototype.hasOwnProperty.call(allowForeignKeys, reference.owner)) {
1675
+ return false;
1676
+ }
1677
+ const allowed = _nullishCoalesce(allowForeignKeys[reference.owner], () => ( []));
1678
+ return allowed.includes(reference.modelKey) || allowed.includes(reference.table);
1679
+ }
1680
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isForeignKeyAllowed, "isForeignKeyAllowed");
1681
+ function describeForeignKeyApproval(reference) {
1682
+ return `schema: { allowForeignKeys: { ${JSON.stringify(reference.owner)}: [${JSON.stringify(reference.modelKey)}] } }`;
1683
+ }
1684
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeForeignKeyApproval, "describeForeignKeyApproval");
1685
+
1686
+ // src/schema-tables.ts
1687
+ function findSchemaTableOwners(config) {
1688
+ const integrations = config.integrations;
1689
+ const candidates = [
1690
+ ..._nullishCoalesce(config.plugins, () => ( [])),
1691
+ ...Array.isArray(integrations) ? integrations : Object.values(_nullishCoalesce(integrations, () => ( {})))
1692
+ ];
1693
+ const owners = [];
1694
+ for (const candidate of candidates) {
1695
+ const declaration = readSchemaTables(candidate);
1696
+ if (declaration && !owners.some((owner) => owner.name === declaration.name)) {
1697
+ owners.push(declaration);
1698
+ }
1699
+ }
1700
+ return owners;
1701
+ }
1702
+ _chunkS3JO3N4Hcjs.__name.call(void 0, findSchemaTableOwners, "findSchemaTableOwners");
1703
+ function collectOwnerModels(owner) {
1704
+ return collectSchemaModels([[owner.name, owner.schema, owner.models]]);
1705
+ }
1706
+ _chunkS3JO3N4Hcjs.__name.call(void 0, collectOwnerModels, "collectOwnerModels");
1707
+ var emptyExtensionPlan = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => ({
1708
+ statements: [],
1709
+ present: [],
1710
+ missingTables: [],
1711
+ conflicts: [],
1712
+ unsupported: []
1713
+ }), "emptyExtensionPlan");
1714
+ async function migrateSchemaTables(owner, options = {}) {
1715
+ const log = _nullishCoalesce(options.log, () => ( (() => {
1716
+ })));
1717
+ const client = await owner.resolveClient(_nullishCoalesce(options.config, () => ( {})));
1718
+ const adapter = createSchemaExecutor(client, owner.name);
1719
+ if (!adapter) {
1720
+ log(
1721
+ `Nothing to create: ${owner.name} stores data through a storage mount, which has no tables.`
1722
+ );
1723
+ return {
1724
+ plan: { dialect: "sqlite", statements: [], upToDate: [], drift: [] },
1725
+ sql: "",
1726
+ applied: [],
1727
+ extensions: { ...emptyExtensionPlan(), unapproved: [], pending: [] },
1728
+ foreignKeys: { waiting: [], unapproved: [], unsupported: [], blocked: [] },
1729
+ steps: { ran: [], pending: [] },
1730
+ planned: 0
1731
+ };
1732
+ }
1733
+ const { executor } = adapter;
1734
+ const dialect = _nullishCoalesce(owner.dialect, () => ( adapter.dialect));
1735
+ const schemaConfig = _optionalChain([options, 'access', _72 => _72.config, 'optionalAccess', _73 => _73.schema]);
1736
+ const reportOnly = options.extensions === "report";
1737
+ const applying = Boolean(options.apply) && !reportOnly;
1738
+ const steps = _nullishCoalesce(owner.migrations, () => ( []));
1739
+ let stepPlan;
1740
+ const stepsRan = [];
1741
+ let stepsStopped;
1742
+ if (steps.length > 0) {
1743
+ const othersTables = new Set(
1744
+ (options.config ? findSchemaTableOwners(options.config) : []).filter((other) => other.name !== owner.name).flatMap((other) => {
1745
+ try {
1746
+ return collectOwnerModels(other).map((model) => model.modelName);
1747
+ } catch (e5) {
1748
+ return [];
1749
+ }
1750
+ })
1751
+ );
1752
+ stepPlan = await planOwnerSchemaSteps({
1753
+ owner: owner.name,
1754
+ schema: owner.schema,
1755
+ steps,
1756
+ tables: collectOwnerModels(owner).map((model) => model.modelName),
1757
+ dialect,
1758
+ executor,
1759
+ readApplied: !reportOnly,
1760
+ othersTables
1761
+ });
1762
+ for (const id of stepPlan.edited) {
1763
+ log(
1764
+ `Migration step "${id}" changed after it ran here. Farm never runs a step twice; review the change yourself.`
1765
+ );
1766
+ }
1767
+ }
1768
+ const runSteps = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async (phase) => {
1769
+ for (const planned of _nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _74 => _74.steps]), () => ( []))) {
1770
+ if (stepsStopped) return;
1771
+ if (planned.phase !== phase) continue;
1772
+ if (planned.state === "run" && planned.destructive && !options.allowDestructive) {
1773
+ stepsStopped = planned;
1774
+ log(
1775
+ `Stopped at migration step "${planned.step.id}" (${planned.summary}): it deletes data. Run again with --allow-destructive to let it. Later steps wait.`
1776
+ );
1777
+ return;
1778
+ }
1779
+ if (planned.state === "blocked") {
1780
+ stepsStopped = planned;
1781
+ log(
1782
+ `Stopped at migration step "${planned.step.id}" (${planned.summary}): ${planned.reason} Later steps wait for it.`
1783
+ );
1784
+ return;
1785
+ }
1786
+ await runSchemaStep(executor, dialect, owner.name, planned);
1787
+ stepsRan.push(planned.step.id);
1788
+ }
1789
+ }, "runSteps");
1790
+ if (applying) await runSteps("before");
1791
+ const models = collectOwnerModels(owner);
1792
+ const planningModels = applying ? models : withoutRenameTargets(models, stepPlan);
1793
+ const others = options.config ? findSchemaTableOwners(options.config) : [];
1794
+ const crossOwner = await planCrossOwnerReferences(owner, others, dialect, executor);
1795
+ for (const reference of crossOwner.eligible) {
1796
+ const model = planningModels.find((candidate) => candidate.modelKey === reference.modelKey);
1797
+ if (!model) continue;
1798
+ (_nullishCoalesce(model.foreignKeys, () => ( (model.foreignKeys = {}))))[reference.fieldKey] = {
1799
+ table: reference.referencedTable,
1800
+ column: reference.referencedColumn,
1801
+ onDelete: reference.onDelete
1802
+ };
1803
+ }
1804
+ const plan = await planSchemaMigration(planningModels, dialect, executor);
1805
+ const snapshot = createSchemaSnapshot(models);
1806
+ const state = await readSchemaState(executor, dialect, owner.name);
1807
+ const changes = state ? diffSchemaSnapshots(state.snapshot, snapshot) : void 0;
1808
+ const upgrade = state && changes && hasSchemaChanges(changes) ? { from: state.version, to: owner.version, changes } : void 0;
1809
+ const pendingSteps = (_nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _75 => _75.steps]), () => ( []))).filter((planned) => planned.state !== "record");
1810
+ if (upgrade || pendingSteps.length > 0) {
1811
+ const versions = _optionalChain([upgrade, 'optionalAccess', _76 => _76.from]) && upgrade.to && upgrade.from !== upgrade.to ? `${owner.name} ${upgrade.from} \u2192 ${upgrade.to} changes its tables:` : `${owner.name}'s tables changed since they were last migrated:`;
1812
+ log(
1813
+ [
1814
+ versions,
1815
+ ...describeStepChanges(stepPlan, Boolean(options.allowDestructive)),
1816
+ ...describeSchemaChanges(withoutStepChanges(changes, stepPlan)),
1817
+ ...renameHints(withoutStepChanges(changes, stepPlan))
1818
+ ].join("\n")
1819
+ );
1820
+ }
1821
+ const recordState = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async () => {
1822
+ if (options.extensions === "report") return;
1823
+ const unfinished = (_nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _77 => _77.steps]), () => ( []))).some(
1824
+ (planned) => !stepsRan.includes(planned.step.id)
1825
+ );
1826
+ if (stepsStopped || unfinished) return;
1827
+ try {
1828
+ await writeSchemaState(executor, dialect, owner.name, { version: owner.version, snapshot });
1829
+ } catch (error) {
1830
+ log(
1831
+ `Applied, but could not record it in "${FARM_SCHEMA_STATE_TABLE}" (${error instanceof Error ? error.message : String(error)}). The next upgrade of ${owner.name} will be compared with the database instead of this version.`
1832
+ );
1833
+ }
1834
+ }, "recordState");
1835
+ const addable = _nullishCoalesce(plan.addableForeignKeys, () => ( []));
1836
+ const foreignKeysUnsupported = dialect === "sqlite" ? addable : [];
1837
+ const foreignKeysAllowed = dialect === "sqlite" ? [] : addable.filter(
1838
+ (key) => isForeignKeyAllowed(_optionalChain([schemaConfig, 'optionalAccess', _78 => _78.allowForeignKeys]), { owner: owner.name, ...key })
1839
+ );
1840
+ const foreignKeysUnapproved = dialect === "sqlite" ? [] : addable.filter((key) => !foreignKeysAllowed.includes(key));
1841
+ const extensionsPlan = await planSchemaExtensions(
1842
+ collectSchemaExtensions(owner.name, owner.schema, owner.models),
1843
+ dialect,
1844
+ executor
1845
+ );
1846
+ const allowExtend = _optionalChain([schemaConfig, 'optionalAccess', _79 => _79.allowExtend]);
1847
+ const approved = reportOnly ? [] : extensionsPlan.statements.filter(
1848
+ (statement) => isSchemaExtensionAllowed(allowExtend, statement.extension)
1849
+ );
1850
+ const unapproved = reportOnly ? [] : extensionsPlan.statements.filter((statement) => !approved.includes(statement));
1851
+ const sql = formatSteps(stepPlan, "before", reportOnly) + formatSchemaMigration(plan, owner.name, {
1852
+ addsColumns: approved.length + foreignKeysAllowed.length > 0
1853
+ }) + formatSteps(stepPlan, "after", reportOnly) + formatForeignKeys(owner.name, dialect, foreignKeysAllowed, foreignKeysUnapproved) + formatExtensions(owner.name, {
1854
+ approved,
1855
+ unapproved,
1856
+ reported: reportOnly ? extensionsPlan.statements : []
1857
+ });
1858
+ const pendingAfter = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (added) => [
1859
+ ...extensionsPlan.statements.map((statement) => statement.target).filter((target) => !added.has(target)),
1860
+ ...extensionsPlan.unsupported.map((entry) => `${entry.extension.table}.${entry.column}`),
1861
+ ...extensionsPlan.missingTables.flatMap(
1862
+ (extension) => extension.fields.map(({ field }) => `${extension.table}.${field.name}`)
1863
+ )
1864
+ ], "pendingAfter");
1865
+ const blocked = [];
1866
+ const result = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (applied2) => ({
1867
+ plan,
1868
+ sql,
1869
+ applied: applied2,
1870
+ extensions: { ...extensionsPlan, unapproved, pending: pendingAfter(new Set(applied2)) },
1871
+ foreignKeys: {
1872
+ waiting: crossOwner.waiting,
1873
+ unapproved: foreignKeysUnapproved,
1874
+ unsupported: foreignKeysUnsupported,
1875
+ blocked
1876
+ },
1877
+ upgrade,
1878
+ steps: {
1879
+ plan: stepPlan,
1880
+ ran: stepsRan,
1881
+ pending: (_nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _80 => _80.steps]), () => ( []))).filter((planned) => !stepsRan.includes(planned.step.id)).map((planned) => planned.step.id)
1882
+ },
1883
+ planned: pendingStatements + runnableSteps
1884
+ }), "result");
1885
+ const creating = new Set(plan.statements.map((statement) => statement.target));
1886
+ for (const reference of crossOwner.waiting) {
1887
+ if (!creating.has(reference.table)) continue;
1888
+ log(
1889
+ `"${reference.table}.${reference.column}" is created without a foreign key: ${reference.referencedOwner} has not created "${reference.referencedTable}" yet. Run \`farm schema migrate\` to create both in order.`
1890
+ );
1891
+ }
1892
+ for (const key of foreignKeysUnsupported) {
1893
+ log(
1894
+ `"${key.table}.${key.column}" has no foreign key to "${key.referencedTable}". SQLite can only add one when it creates the table.`
1895
+ );
1896
+ }
1897
+ if (plan.upToDate.length > 0) {
1898
+ log(`Already up to date: ${plan.upToDate.join(", ")}`);
1899
+ }
1900
+ if (plan.drift.length > 0) {
1901
+ log(
1902
+ `These tables exist but no longer match the schema. Farm will not change them:
1903
+ ${describeSchemaDrift(plan.drift)}`
1904
+ );
1905
+ }
1906
+ logExtensionProblems(owner.name, extensionsPlan, log);
1907
+ const pendingStatements = plan.statements.length + (_nullishCoalesce(_optionalChain([plan, 'access', _81 => _81.upgrades, 'optionalAccess', _82 => _82.length]), () => ( 0))) + approved.length + foreignKeysAllowed.length;
1908
+ const blockedAt = (_nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _83 => _83.steps]), () => ( []))).findIndex(
1909
+ (planned) => planned.state === "blocked" || planned.state === "run" && planned.destructive && !options.allowDestructive
1910
+ );
1911
+ const runnableSteps = (_nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _84 => _84.steps]), () => ( []))).slice(0, blockedAt === -1 ? void 0 : blockedAt).filter((planned) => !stepsRan.includes(planned.step.id)).length;
1912
+ if (pendingStatements === 0 && runnableSteps === 0 && blockedAt === -1 && unapproved.length === 0 && foreignKeysUnapproved.length === 0 && (!reportOnly || extensionsPlan.statements.length === 0)) {
1913
+ log("Nothing to create.");
1914
+ if (options.apply) await recordState();
1915
+ return result([]);
1916
+ }
1917
+ if (options.write) {
1918
+ const { writeFile, mkdir } = await import("fs/promises");
1919
+ const { dirname } = await import("path");
1920
+ await mkdir(dirname(options.write), { recursive: true });
1921
+ await writeFile(options.write, sql, "utf8");
1922
+ log(`Wrote ${pendingStatements} statement(s) to ${options.write}`);
1923
+ return result([]);
1924
+ }
1925
+ if (!options.apply) {
1926
+ log(sql);
1927
+ return result([]);
1928
+ }
1929
+ for (const approval of new Set(
1930
+ unapproved.map((statement) => describeSchemaExtensionApproval(statement.extension))
1931
+ )) {
1932
+ const columns = unapproved.filter((statement) => describeSchemaExtensionApproval(statement.extension) === approval).map((statement) => statement.target);
1933
+ log(
1934
+ `Not allowed yet, so not added: ${columns.join(", ")}. To allow it, add to farm.config: ${approval}`
1935
+ );
1936
+ }
1937
+ const created = await applySchemaMigration(plan, executor);
1938
+ const applied = [...created.applied];
1939
+ for (const statement of approved) {
1940
+ await executor.execute(statement.sql);
1941
+ applied.push(statement.target);
1942
+ }
1943
+ for (const key of foreignKeysAllowed) {
1944
+ const orphans = await countOrphans(executor, dialect, key);
1945
+ if (orphans > 0) {
1946
+ blocked.push({ key, orphans });
1947
+ log(
1948
+ `Cannot add the foreign key "${key.table}.${key.column}" \u2192 "${key.referencedTable}": ${orphans} row(s) point at no "${key.referencedTable}". Fix or remove them, then run again.`
1949
+ );
1950
+ continue;
1951
+ }
1952
+ await executor.execute(foreignKeyStatement(dialect, key));
1953
+ applied.push(`${key.table}.${key.column} \u2192 ${key.referencedTable}`);
1954
+ }
1955
+ for (const key of foreignKeysUnapproved) {
1956
+ log(
1957
+ `Not allowed yet, so not added: the foreign key "${key.table}.${key.column}" \u2192 "${key.referencedTable}". To allow it, add to farm.config: ${describeForeignKeyApproval({ owner: owner.name, modelKey: key.modelKey })}`
1958
+ );
1959
+ }
1960
+ if (applied.length > 0) log(`Created: ${applied.join(", ")}`);
1961
+ await runSteps("after");
1962
+ if (stepsRan.length > 0) log(`Ran migration steps: ${stepsRan.join(", ")}`);
1963
+ await recordState();
1964
+ return result(applied);
1965
+ }
1966
+ _chunkS3JO3N4Hcjs.__name.call(void 0, migrateSchemaTables, "migrateSchemaTables");
1967
+ function foreignKeyStatement(dialect, key) {
1968
+ const name = `${key.table}_${key.column}_fkey`.slice(0, 63);
1969
+ const onDelete = key.onDelete !== "noAction" ? ` ON DELETE ${SQL_ON_DELETE[key.onDelete]}` : "";
1970
+ const q = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (value) => quoteSqlIdentifier(dialect, value), "q");
1971
+ return `ALTER TABLE ${q(key.table)} ADD CONSTRAINT ${q(name)} FOREIGN KEY (${q(key.column)}) REFERENCES ${q(key.referencedTable)} (${q(key.referencedColumn)})${onDelete};`;
1972
+ }
1973
+ _chunkS3JO3N4Hcjs.__name.call(void 0, foreignKeyStatement, "foreignKeyStatement");
1974
+ var SQL_ON_DELETE = {
1975
+ cascade: "CASCADE",
1976
+ restrict: "RESTRICT",
1977
+ setNull: "SET NULL",
1978
+ noAction: "NO ACTION"
1979
+ };
1980
+ async function countOrphans(executor, dialect, key) {
1981
+ const q = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (name) => quoteSqlIdentifier(dialect, name), "q");
1982
+ const rows = await executor.query(
1983
+ `SELECT COUNT(*) AS orphans FROM ${q(key.table)} child WHERE child.${q(key.column)} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${q(key.referencedTable)} parent WHERE parent.${q(key.referencedColumn)} = child.${q(key.column)})`
1984
+ );
1985
+ const row = _nullishCoalesce(rows[0], () => ( {}));
1986
+ return Number(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(row.orphans, () => ( row.ORPHANS)), () => ( Object.values(row)[0])), () => ( 0)));
1987
+ }
1988
+ _chunkS3JO3N4Hcjs.__name.call(void 0, countOrphans, "countOrphans");
1989
+ function formatForeignKeys(owner, dialect, allowed, unapproved) {
1990
+ const sections = [];
1991
+ if (allowed.length > 0) {
1992
+ sections.push(
1993
+ [
1994
+ `-- Foreign keys from ${owner}'s existing tables to other plugins' tables, allowed in farm.config.`,
1995
+ "-- Added only when no row points at nothing.",
1996
+ ...allowed.map((key) => foreignKeyStatement(dialect, key))
1997
+ ].join("\n")
1998
+ );
1999
+ }
2000
+ if (unapproved.length > 0) {
2001
+ const approvals = [
2002
+ ...new Set(
2003
+ unapproved.map((key) => describeForeignKeyApproval({ owner, modelKey: key.modelKey }))
2004
+ )
2005
+ ];
2006
+ sections.push(
2007
+ [
2008
+ `-- Foreign keys from ${owner}'s existing tables to other plugins' tables. Not allowed yet, so not run.`,
2009
+ "-- To allow them, add to farm.config:",
2010
+ ...approvals.map((approval) => `-- ${approval}`),
2011
+ ...unapproved.map((key) => `-- ${foreignKeyStatement(dialect, key)}`)
2012
+ ].join("\n")
2013
+ );
2014
+ }
2015
+ return sections.length > 0 ? `
2016
+ ${sections.join("\n\n")}
2017
+ ` : "";
2018
+ }
2019
+ _chunkS3JO3N4Hcjs.__name.call(void 0, formatForeignKeys, "formatForeignKeys");
2020
+ function describeStepChanges(stepPlan, allowDestructive) {
2021
+ const pending = (_nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _85 => _85.steps]), () => ( []))).filter((planned) => planned.state !== "record");
2022
+ return pending.map((planned, index) => {
2023
+ const when = planned.phase === "after" ? " (after the changes below)" : "";
2024
+ const deletes = planned.destructive && planned.state === "run" ? allowDestructive ? " \u26A0 deletes data" : " \u26A0 deletes data, needs --allow-destructive" : "";
2025
+ const blocked = planned.state === "blocked" ? ` \u2717 blocked: ${planned.reason}` : "";
2026
+ return ` ${index + 1}. ${planned.summary}${when}${deletes}${blocked}`;
2027
+ });
2028
+ }
2029
+ _chunkS3JO3N4Hcjs.__name.call(void 0, describeStepChanges, "describeStepChanges");
2030
+ function withoutStepChanges(changes, stepPlan) {
2031
+ const empty = {
2032
+ addedTables: [],
2033
+ addedColumns: [],
2034
+ addedIndexes: [],
2035
+ otherChanges: [],
2036
+ removedColumns: []
2037
+ };
2038
+ if (!changes) return empty;
2039
+ const renamedTo = /* @__PURE__ */ new Set();
2040
+ const renamedFrom = /* @__PURE__ */ new Set();
2041
+ for (const { summary, step } of _nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _86 => _86.steps]), () => ( []))) {
2042
+ const match = /^rename (?:table )?(\S+) → (\S+)$/u.exec(summary);
2043
+ if (!match || !("renameColumn" in step || "renameTable" in step)) continue;
2044
+ renamedFrom.add(match[1]);
2045
+ renamedTo.add(match[2]);
2046
+ }
2047
+ return {
2048
+ addedTables: changes.addedTables.filter((table) => !renamedTo.has(table)),
2049
+ addedColumns: changes.addedColumns.filter(
2050
+ ({ table, column }) => !renamedTo.has(`${table}.${column}`)
2051
+ ),
2052
+ addedIndexes: changes.addedIndexes,
2053
+ otherChanges: changes.otherChanges.filter(
2054
+ (change) => ![...renamedFrom].some((from) => change === `${from} is removed`)
2055
+ ),
2056
+ removedColumns: (_nullishCoalesce(changes.removedColumns, () => ( []))).filter(
2057
+ ({ table, column }) => !renamedFrom.has(`${table}.${column}`)
2058
+ )
2059
+ };
2060
+ }
2061
+ _chunkS3JO3N4Hcjs.__name.call(void 0, withoutStepChanges, "withoutStepChanges");
2062
+ function renameHints(changes) {
2063
+ const hints = [];
2064
+ for (const removed of _nullishCoalesce(changes.removedColumns, () => ( []))) {
2065
+ const added = changes.addedColumns.find(
2066
+ ({ table, type }) => table === removed.table && type === removed.type
2067
+ );
2068
+ if (!added) continue;
2069
+ hints.push(
2070
+ ` ? if ${removed.table}.${removed.column} was renamed to ${added.table}.${added.column}, the plugin needs a migration step, or the data stays in ${removed.column}`
2071
+ );
2072
+ }
2073
+ return hints;
2074
+ }
2075
+ _chunkS3JO3N4Hcjs.__name.call(void 0, renameHints, "renameHints");
2076
+ function formatSteps(stepPlan, phase, reportOnly) {
2077
+ const planned = (_nullishCoalesce(_optionalChain([stepPlan, 'optionalAccess', _87 => _87.steps]), () => ( []))).filter(
2078
+ (entry) => entry.phase === phase && entry.state !== "record"
2079
+ );
2080
+ if (planned.length === 0) return "";
2081
+ const heading = phase === "before" ? "-- Migration steps, run before the changes below:" : "-- Migration steps, run after the changes above:";
2082
+ const lines = [heading];
2083
+ for (const entry of planned) {
2084
+ lines.push(
2085
+ `-- ${entry.step.id}: ${entry.summary}${entry.destructive ? " (deletes data)" : ""}`
2086
+ );
2087
+ if (entry.state === "blocked") {
2088
+ lines.push(`-- blocked: ${entry.reason}`);
2089
+ continue;
2090
+ }
2091
+ for (const statement of entry.statements) {
2092
+ lines.push(reportOnly ? `-- ${statement};` : `${statement.replace(/;\s*$/u, "")};`);
2093
+ }
2094
+ }
2095
+ if (reportOnly) {
2096
+ lines.push("-- Your ORM owns these tables: add the steps to its migrations instead.");
2097
+ }
2098
+ return `${lines.join("\n")}
2099
+
2100
+ `;
2101
+ }
2102
+ _chunkS3JO3N4Hcjs.__name.call(void 0, formatSteps, "formatSteps");
2103
+ function formatExtensions(owner, groups) {
2104
+ const sections = [];
2105
+ if (groups.approved.length > 0) {
2106
+ sections.push(
2107
+ [
2108
+ `-- Columns ${owner} adds to tables it does not own, allowed in farm.config.`,
2109
+ ...groups.approved.map((statement) => statement.sql)
2110
+ ].join("\n")
2111
+ );
2112
+ }
2113
+ if (groups.unapproved.length > 0) {
2114
+ const approvals = [
2115
+ ...new Set(
2116
+ groups.unapproved.map((statement) => describeSchemaExtensionApproval(statement.extension))
2117
+ )
2118
+ ];
2119
+ sections.push(
2120
+ [
2121
+ `-- Columns ${owner} adds to tables it does not own. Not allowed yet, so not run.`,
2122
+ "-- To allow them, add to farm.config:",
2123
+ ...approvals.map((approval) => `-- ${approval}`),
2124
+ ...groups.unapproved.map((statement) => `-- ${statement.sql}`)
2125
+ ].join("\n")
2126
+ );
2127
+ }
2128
+ if (groups.reported.length > 0) {
2129
+ sections.push(
2130
+ [
2131
+ `-- Columns ${owner} adds to tables your ORM owns. Farm will not alter them:`,
2132
+ "-- add them to your ORM's schema and run its migration.",
2133
+ ...groups.reported.map((statement) => `-- ${statement.sql}`)
2134
+ ].join("\n")
2135
+ );
2136
+ }
2137
+ return sections.length > 0 ? `
2138
+ ${sections.join("\n\n")}
2139
+ ` : "";
2140
+ }
2141
+ _chunkS3JO3N4Hcjs.__name.call(void 0, formatExtensions, "formatExtensions");
2142
+ function logExtensionProblems(owner, plan, log) {
2143
+ for (const extension of plan.missingTables) {
2144
+ log(
2145
+ `Cannot add ${extension.fields.map(({ field }) => field.name).join(", ")} to "${extension.table}": the table does not exist. Run the migration that creates it (your ORM's, or a library's such as Better Auth) first.`
2146
+ );
2147
+ }
2148
+ for (const entry of plan.unsupported) {
2149
+ log(`Cannot add "${entry.extension.table}.${entry.column}" for ${owner}: ${entry.reason}`);
2150
+ }
2151
+ for (const entry of plan.conflicts) {
2152
+ log(
2153
+ `"${entry.extension.table}.${entry.column}" already exists as ${entry.actual}; ${owner} expects ${entry.expected.toLowerCase()}. Farm will not change it.`
2154
+ );
2155
+ }
2156
+ }
2157
+ _chunkS3JO3N4Hcjs.__name.call(void 0, logExtensionProblems, "logExtensionProblems");
2158
+
2159
+
2160
+
2161
+
2162
+
2163
+
2164
+
2165
+
2166
+
2167
+
2168
+
2169
+
2170
+
2171
+
2172
+
2173
+
2174
+
2175
+
2176
+
2177
+
2178
+
2179
+
2180
+
2181
+
2182
+
2183
+
2184
+
2185
+
2186
+
2187
+
2188
+
2189
+
2190
+
2191
+
2192
+
2193
+
2194
+
2195
+
2196
+
2197
+
2198
+
2199
+ exports.describeSchemaReference = describeSchemaReference; exports.collectSchemaModels = collectSchemaModels; exports.generateSqlStatements = generateSqlStatements; exports.renderSqlSchemaFile = renderSqlSchemaFile; exports.getSqlColumnType = getSqlColumnType; exports.getSqlDefaultExpression = getSqlDefaultExpression; exports.isNullableField = isNullableField; exports.quoteSqlIdentifier = quoteSqlIdentifier; exports.toSnakeCase = toSnakeCase; exports.toPascalCase = toPascalCase; exports.toCamelCase = toCamelCase; exports.escapeSqlString = escapeSqlString; exports.planSchemaMigration = planSchemaMigration; exports.describeSchemaTable = describeSchemaTable; exports.applySchemaMigration = applySchemaMigration; exports.columnTypeFamily = columnTypeFamily; exports.planSchemaExtensions = planSchemaExtensions; exports.formatSchemaMigration = formatSchemaMigration; exports.describeSchemaDrift = describeSchemaDrift; exports.createSchemaExecutor = createSchemaExecutor; exports.collectSchemaExtensions = collectSchemaExtensions; exports.isSchemaExtensionAllowed = isSchemaExtensionAllowed; exports.describeSchemaExtensionApproval = describeSchemaExtensionApproval; exports.FARM_SCHEMA_STATE_TABLE = FARM_SCHEMA_STATE_TABLE; exports.createSchemaSnapshot = createSchemaSnapshot; exports.diffSchemaSnapshots = diffSchemaSnapshots; exports.hasSchemaChanges = hasSchemaChanges; exports.readSchemaState = readSchemaState; exports.FARM_SCHEMA_STEPS_TABLE = FARM_SCHEMA_STEPS_TABLE; exports.withoutRenameTargets = withoutRenameTargets; exports.planOwnerSchemaSteps = planOwnerSchemaSteps; exports.planCrossOwnerReferences = planCrossOwnerReferences; exports.describeForeignKeyApproval = describeForeignKeyApproval; exports.FARM_SCHEMA_TABLES = FARM_SCHEMA_TABLES; exports.declareSchemaTables = declareSchemaTables; exports.readSchemaTables = readSchemaTables; exports.findSchemaTableOwners = findSchemaTableOwners; exports.collectOwnerModels = collectOwnerModels; exports.migrateSchemaTables = migrateSchemaTables;