@alchemy.run/drizzle 2.0.0-beta.84 → 2.0.0-beta.85

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.
package/lib/Schema.js CHANGED
@@ -9,20 +9,84 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
9
9
  import * as crypto from "node:crypto";
10
10
  import * as Artifacts from "alchemy/Artifacts";
11
11
  import { isResolved } from "alchemy/Diff";
12
+ import { Interaction } from "alchemy/Interaction";
12
13
  import * as Provider from "alchemy/Provider";
13
14
  import { Resource } from "alchemy/Resource";
14
- import { exec } from "alchemy/Util/exec";
15
- import { isNonInteractive } from "alchemy/Util/interactive";
15
+ import * as Data from "effect/Data";
16
16
  import * as Effect from "effect/Effect";
17
17
  import * as FileSystem from "effect/FileSystem";
18
+ import * as Match from "effect/Match";
19
+ import * as Option from "effect/Option";
18
20
  import * as Path from "effect/Path";
19
- import { ChildProcess } from "effect/process";
21
+ import * as Record from "effect/Record";
22
+ import * as S from "effect/Schema";
23
+ import * as Semaphore from "effect/Semaphore";
24
+ // Unlisted fields are kept (the rest records), so a decoded snapshot can be
25
+ // written back whole.
26
+ const DdlEntry = S.StructWithRest(S.Struct({
27
+ entityType: S.String,
28
+ schema: S.optional(S.String),
29
+ table: S.optional(S.String),
30
+ name: S.optional(S.String),
31
+ }), [S.Record(S.String, S.Unknown)]);
32
+ // A `snapshot.json`. Postgres folders hold one `base` snapshot followed by
33
+ // `diff` snapshots carrying `deltas`; mysql and sqlite snapshots are full.
34
+ const Snapshot = S.StructWithRest(S.Struct({
35
+ type: S.optional(S.Literals(["base", "diff"])),
36
+ version: S.optional(S.String),
37
+ dialect: S.optional(S.String),
38
+ id: S.optional(S.String),
39
+ prevIds: S.String.pipe(S.Array, S.optional),
40
+ ddl: DdlEntry.pipe(S.Array, S.optional),
41
+ }), [S.Record(S.String, S.Unknown)]);
42
+ const decodeSnapshot = S.decodeEffect(S.fromJsonString(Snapshot));
43
+ class DrizzleKitLoadFailed extends Data.TaggedError("DrizzleKitLoadFailed") {
44
+ get message() {
45
+ return `Failed to load ${this.module} (is drizzle-kit installed?): ${this.cause instanceof Error ? this.cause.message : String(this.cause)}`;
46
+ }
47
+ }
48
+ class InvalidSnapshot extends Data.TaggedError("InvalidSnapshot") {
49
+ get message() {
50
+ return `Invalid drizzle snapshot at ${this.file}: ${this.cause.message}`;
51
+ }
52
+ }
53
+ class SchemaImportFailed extends Data.TaggedError("SchemaImportFailed") {
54
+ get message() {
55
+ return `Failed to import schema at ${this.schema}: ${this.cause instanceof Error ? this.cause.message : String(this.cause)}`;
56
+ }
57
+ }
58
+ class DrizzleKitFailed extends Data.TaggedError("DrizzleKitFailed") {
59
+ get message() {
60
+ // Thrown errors carry their own message; reported ones (`{ status:
61
+ // "error", error }`) are plain objects like `{ code, kind, snapshot }`.
62
+ const { cause } = this;
63
+ const detail = cause instanceof Error ? cause.message : JSON.stringify(cause);
64
+ return `drizzle-kit ${this.command} failed: ${detail}`;
65
+ }
66
+ }
67
+ class DrizzleKitExited extends Data.TaggedError("DrizzleKitExited") {
68
+ get message() {
69
+ return `drizzle-kit ${this.command} found errors in the schema (such as two columns with one name) and tried to exit the process`;
70
+ }
71
+ }
72
+ /** An ambiguous schema change with no terminal to ask. */
73
+ class UndecidedSchemaChange extends Data.TaggedError("UndecidedSchemaChange") {
74
+ get message() {
75
+ const { props, hint } = this;
76
+ return [
77
+ `${props.schema} has an ambiguous change that needs a decision:`,
78
+ ` ${formatEntity(hint.entity)}: created or renamed?`,
79
+ "Re-run in an interactive terminal to answer it.",
80
+ ].join("\n");
81
+ }
82
+ }
20
83
  /**
21
84
  * A Drizzle schema managed as an Alchemy resource.
22
85
  *
23
- * Wraps drizzle-kit's programmatic API (`generateDrizzleJson` /
24
- * `generateMigration`) so migration SQL is regenerated as part of `alchemy
25
- * deploy` whenever the source schema changes. The output directory is
86
+ * Runs `drizzle-kit generate` through drizzle-kit's programmatic API so
87
+ * migration SQL is regenerated as part of `alchemy deploy` whenever the
88
+ * source schema changes. Ambiguous changes (a rename or a new column/table?)
89
+ * are asked with Alchemy's prompts during plan. The output directory is
26
90
  * intended to be passed straight to a database resource's `migrations`
27
91
  * prop, giving you a single deploy-driven flow:
28
92
  *
@@ -53,18 +117,51 @@ import { ChildProcess } from "effect/process";
53
117
  * @resource
54
118
  */
55
119
  export const Schema = Resource("Drizzle.Schema");
56
- const dialectModule = (dialect) => {
57
- switch (dialect) {
58
- case "postgres":
59
- return "drizzle-kit/api-postgres";
60
- case "mysql":
61
- return "drizzle-kit/api-mysql";
62
- case "sqlite":
63
- return "drizzle-kit/api-sqlite";
120
+ const cliDialect = (props) => props.dialect === undefined || props.dialect === "postgres" ? "postgresql" : props.dialect;
121
+ const sha = (s) => crypto.createHash("sha256").update(s).digest("hex");
122
+ const importModule = (module) => Effect.tryPromise({
123
+ try: () => import(__rewriteRelativeImportExtension(/* @vite-ignore */ module)),
124
+ catch: (cause) => new DrizzleKitLoadFailed({ module, cause }),
125
+ });
126
+ // drizzle-kit runs in-process but calls `process.exit` on schema errors.
127
+ // Calls trap the exit and fail instead, one at a time since the trap swaps
128
+ // the global.
129
+ const exitTrap = Semaphore.makeUnsafe(1);
130
+ const callDrizzleKit = (command, run) => Effect.acquireUseRelease(Effect.sync(() => {
131
+ // oxlint-disable-next-line typescript/unbound-method -- saved only to restore `process.exit` verbatim, never called unbound
132
+ const trap = { exit: process.exit, exited: false };
133
+ process.exit = () => {
134
+ trap.exited = true;
135
+ throw new Error("drizzle-kit exited");
136
+ };
137
+ return trap;
138
+ }), (trap) =>
139
+ // `cli` commands catch the trap's throw and report it as an error result.
140
+ // Uninterruptible: the promise can't be cancelled, so the trap stays
141
+ // until it settles.
142
+ Effect.tryPromise({
143
+ try: run,
144
+ catch: (cause) => trap.exited
145
+ ? new DrizzleKitExited({ command })
146
+ : new DrizzleKitFailed({ command, cause }),
147
+ }).pipe(Effect.flatMap((result) => trap.exited ? Effect.fail(new DrizzleKitExited({ command })) : Effect.succeed(result)), Effect.uninterruptible), (trap) => Effect.sync(() => {
148
+ process.exit = trap.exit;
149
+ })).pipe((effect) => exitTrap.withPermit(effect));
150
+ // A `drizzle-kit/cli` command as an Effect, failing on a thrown or reported error.
151
+ const command = (name) => Effect.fn(`drizzleKit.${name}`)(function* (options) {
152
+ const cli = yield* importModule("drizzle-kit/cli");
153
+ const result = yield* callDrizzleKit(name, () => cli[name](options));
154
+ if (result.status === "error") {
155
+ return yield* new DrizzleKitFailed({ command: name, cause: result.error });
64
156
  }
157
+ return result;
158
+ });
159
+ const drizzleKit = {
160
+ /** `drizzle-kit generate`; with `explain` a dry run that writes nothing. */
161
+ generate: command("generate"),
162
+ /** `drizzle-kit up`: upgrade snapshots to the current format. */
163
+ up: command("up"),
65
164
  };
66
- const sha = (s) => crypto.createHash("sha256").update(s).digest("hex");
67
- const tsStamp = () => new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14);
68
165
  export const SchemaProvider = () => Provider.effect(Schema, Effect.gen(function* () {
69
166
  const fs = yield* FileSystem.FileSystem;
70
167
  const path = yield* Path.Path;
@@ -75,227 +172,176 @@ export const SchemaProvider = () => Provider.effect(Schema, Effect.gen(function*
75
172
  // `resolveOut` form.
76
173
  const relativeOut = (abs) => path.relative(process.cwd(), abs);
77
174
  const resolveSchema = (p) => path.resolve(process.cwd(), p.schema);
78
- const loadSchemaModule = (p) => Effect.gen(function* () {
79
- const schemaPath = resolveSchema(p);
80
- return yield* Effect.tryPromise({
81
- try: () => import(__rewriteRelativeImportExtension(/* @vite-ignore */ schemaPath)),
82
- catch: (cause) => new Error(`Failed to import schema at ${p.schema}: ${cause}`),
83
- });
84
- });
85
- const loadKit = (dialect) => Effect.tryPromise({
86
- try: () => import(__rewriteRelativeImportExtension(/* @vite-ignore */ dialectModule(dialect))),
87
- catch: (cause) => new Error(`Failed to load drizzle-kit/${dialect} (is drizzle-kit installed?): ${cause}`),
88
- });
89
- const drizzleKitBin = (dialect) => Effect.gen(function* () {
90
- const apiUrl = yield* Effect.try({
91
- try: () => import.meta.resolve(dialectModule(dialect)),
92
- catch: (cause) => new Error(`Failed to resolve drizzle-kit/${dialect}: ${cause}`),
93
- });
94
- const apiFileUrl = yield* Effect.try({
95
- try: () => new URL(apiUrl),
96
- catch: (cause) => new Error(`Failed to parse drizzle-kit/${dialect} URL: ${cause}`),
97
- });
98
- const apiPath = yield* path.fromFileUrl(apiFileUrl);
99
- return path.join(path.dirname(apiPath), "bin.cjs");
100
- });
101
- const runDrizzleGenerate = (props, out) => Effect.gen(function* () {
102
- const dialect = props.dialect ?? "postgres";
103
- const bin = yield* drizzleKitBin(dialect);
104
- const schemaPath = resolveSchema(props);
105
- const nodeExecPath = yield* Effect.sync(() => process.execPath);
106
- const nodeModulesPath = path.join(process.cwd(), "node_modules");
107
- // drizzle-kit globs the --schema/--out values; Windows backslashes
108
- // are treated as glob escapes and match nothing, so pass forward
109
- // slashes.
110
- const args = [
111
- bin,
112
- "generate",
113
- "--dialect",
114
- dialect === "postgres" ? "postgresql" : dialect,
115
- "--schema",
116
- schemaPath.replaceAll("\\", "/"),
117
- "--out",
118
- out.replaceAll("\\", "/"),
119
- ];
120
- const commandOptions = {
121
- cwd: process.cwd(),
122
- env: { NODE_PATH: nodeModulesPath },
123
- extendEnv: true,
124
- };
125
- // Hand the terminal to drizzle-kit only when this process may
126
- // prompt at all — the same detection (TTY, CI, `--no-input`,
127
- // `ALCHEMY_NO_TUI`, agent env) every other spawned command uses.
128
- if (!isNonInteractive() && process.stderr.isTTY) {
129
- const handle = yield* ChildProcess.make(nodeExecPath, args, {
130
- ...commandOptions,
131
- stdin: "inherit",
132
- stdout: "inherit",
133
- stderr: "inherit",
134
- }).pipe(Effect.mapError((cause) => new Error(`drizzle-kit generate failed: ${String(cause)}`)));
135
- const exitCode = yield* handle.exitCode;
136
- if (exitCode !== 0) {
137
- return yield* Effect.fail(new Error(`drizzle-kit generate failed with exit ${exitCode}`));
138
- }
139
- return;
140
- }
141
- const result = yield* exec(ChildProcess.make(nodeExecPath, args, commandOptions)).pipe(Effect.mapError((cause) => new Error(`drizzle-kit generate failed: ${String(cause)}`)));
142
- if (result.exitCode === 0)
143
- return;
144
- // Since drizzle-kit 1.0.0-rc.4 the non-interactive CLI refuses
145
- // ambiguous decisions (rename-vs-create, data-loss confirmation)
146
- // with a `missing_hints` report on exit 2. These are deliberate
147
- // safety prompts — the generated SQL is applied to the real
148
- // database later in the same deploy — so we never answer them
149
- // automatically. Ask the user to decide.
150
- if (result.exitCode === 2) {
151
- return yield* Effect.fail(new Error([
152
- `drizzle-kit needs a decision for ${props.schema} that cannot be made non-interactively (rename vs create, or a change that loses data):`,
153
- "",
154
- result.stdout.trim(),
155
- "",
156
- "To resolve, generate the migration yourself and commit it:",
157
- ` npx drizzle-kit generate --dialect ${dialect === "postgres" ? "postgresql" : dialect} --schema ${props.schema} --out ${props.out ?? "./migrations"}`,
158
- "then re-run the deploy (the schema resource will see no drift and apply the committed migration).",
159
- "Alternatively, run the deploy in a terminal to answer drizzle-kit's prompts interactively.",
160
- ].join("\n")));
161
- }
162
- return yield* Effect.fail(new Error(`drizzle-kit generate failed: ${result.stdout}\n${result.stderr}`));
163
- });
175
+ // drizzle-kit reads `schema` as a glob, where `\` is an escape.
176
+ const schemaGlob = (p) => resolveSchema(p).replaceAll("\\", "/");
164
177
  // List `<ts>_*` migration directories under `out`, sorted by numeric
165
178
  // prefix. Returns an empty array if `out` doesn't exist.
166
- const listMigrationDirs = (out) => Effect.gen(function* () {
167
- const exists = yield* fs.exists(out);
168
- if (!exists)
179
+ const listMigrationDirs = Effect.fn("Drizzle.listMigrationDirs")(function* (out) {
180
+ if (!(yield* fs.exists(out)))
169
181
  return [];
170
182
  const entries = yield* fs.readDirectory(out);
171
183
  return entries.filter((name) => /^\d+_/.test(name)).sort();
172
184
  });
185
+ const readSnapshots = Effect.fn("Drizzle.readSnapshots")(function* (out) {
186
+ const entries = yield* Effect.forEach(yield* listMigrationDirs(out), (dir) => Effect.gen(function* () {
187
+ const file = path.join(out, dir, "snapshot.json");
188
+ if (!(yield* fs.exists(file)))
189
+ return [];
190
+ const text = yield* fs.readFileString(file);
191
+ const snapshot = yield* decodeSnapshot(text).pipe(Effect.mapError((cause) => new InvalidSnapshot({ file, cause })));
192
+ return [[dir, { snapshot, text }]];
193
+ }));
194
+ return Record.fromEntries(entries.flat());
195
+ });
173
196
  // The latest snapshot is the head of the `prevIds` chain — the one no
174
197
  // other snapshot points back to. Directory-name order alone is not
175
198
  // enough: two migrations generated within the same second share the
176
199
  // timestamp prefix, and the random name suffix then decides the sort.
177
- const readLatestSnapshot = (out) => Effect.gen(function* () {
178
- const dirs = yield* listMigrationDirs(out);
179
- const entries = [];
180
- for (const dir of dirs) {
181
- const snapshotPath = path.join(out, dir, "snapshot.json");
182
- const exists = yield* fs.exists(snapshotPath);
183
- if (!exists)
184
- continue;
185
- const text = yield* fs.readFileString(snapshotPath);
186
- entries.push({
187
- snapshot: JSON.parse(text),
188
- hash: sha(text),
189
- });
190
- }
200
+ const readLatestSnapshot = Effect.fn("Drizzle.readLatestSnapshot")(function* (out) {
201
+ const entries = Record.values(yield* readSnapshots(out));
191
202
  if (entries.length === 0)
192
203
  return undefined;
193
204
  const referenced = new Set(entries.flatMap((entry) => entry.snapshot.prevIds ?? []));
194
205
  const head = entries.find((entry) => entry.snapshot.id !== undefined && !referenced.has(entry.snapshot.id));
195
206
  // Fall back to name order for snapshots without id/prevIds chains.
196
- return head ?? entries[entries.length - 1];
207
+ const latest = head ?? entries[entries.length - 1];
208
+ return { snapshot: latest.snapshot, hash: sha(latest.text) };
197
209
  });
198
- const detectDriftWithCli = (props) => Effect.gen(function* () {
199
- const out = resolveOut(props);
200
- const tmpOut = yield* fs.makeTempDirectory({
201
- prefix: "alchemy-drizzle-generate-",
202
- });
203
- return yield* Effect.gen(function* () {
204
- const outExists = yield* fs.exists(out);
205
- if (outExists)
206
- yield* copyDirectory(out, tmpOut);
207
- const before = yield* listMigrationDirs(tmpOut);
208
- yield* runDrizzleGenerate(props, tmpOut);
209
- const after = yield* listMigrationDirs(tmpOut);
210
- const latest = yield* readLatestSnapshot(tmpOut);
211
- const changed = after.some((dir) => !before.includes(dir));
212
- const prevEntry = outExists ? yield* readLatestSnapshot(out) : undefined;
213
- return {
214
- mode: "cli",
215
- out,
216
- cur: latest?.snapshot,
217
- prevEntry,
218
- changed,
219
- };
220
- }).pipe(Effect.ensuring(fs.remove(tmpOut, { recursive: true }).pipe(Effect.ignore)));
210
+ /**
211
+ * Bring a migrations folder up to drizzle-kit's current snapshot format
212
+ * with `drizzle-kit up`. Returns whether anything changed.
213
+ *
214
+ * Earlier Alchemy versions wrote every postgres snapshot as a full
215
+ * version-9 snapshot without a `type`. That is the version-8 shape, which
216
+ * `up` turns into drizzle-kit's base/diff chain, so relabel them first.
217
+ */
218
+ const upgradeFolder = Effect.fn("Drizzle.upgradeFolder")(function* (props, out) {
219
+ if (!(yield* fs.exists(out)))
220
+ return false;
221
+ if (cliDialect(props) === "postgresql") {
222
+ for (const [dir, { snapshot }] of Record.toEntries(yield* readSnapshots(out))) {
223
+ if (snapshot.type !== undefined || snapshot.version !== "9")
224
+ continue;
225
+ yield* fs.writeFileString(path.join(out, dir, "snapshot.json"), JSON.stringify({ ...snapshot, version: "8", renames: [] }, null, 2));
226
+ }
227
+ }
228
+ const { upgraded } = yield* drizzleKit.up({ dialect: cliDialect(props), out });
229
+ return upgraded.length > 0;
230
+ });
231
+ // The schema the migrations folder describes. Postgres folders are diff
232
+ // chains drizzle-kit rebuilds; other dialects store full snapshots.
233
+ const readPreviousSnapshot = Effect.fn("Drizzle.readPreviousSnapshot")(function* (kit, out) {
234
+ const reconstruct = kit.reconstruct;
235
+ if (reconstruct === undefined)
236
+ return (yield* readLatestSnapshot(out))?.snapshot;
237
+ const files = Record.map(yield* readSnapshots(out), ({ snapshot }) => snapshot);
238
+ if (Record.isEmptyRecord(files))
239
+ return undefined;
240
+ const parents = new Set(Record.values(files).flatMap((file) => file.prevIds ?? []));
241
+ const leaves = Record.values(files).filter(({ id }) => id !== undefined && !parents.has(id));
242
+ if (leaves.length < 2) {
243
+ return yield* callDrizzleKit("reconstruct", () => reconstruct(files));
244
+ }
245
+ // Unmerged branches: reconstruct an empty merge of their leaves, the
246
+ // combined state drizzle-kit's generate diffs against.
247
+ const merge = {
248
+ ...leaves[0],
249
+ id: MERGE_ID,
250
+ prevIds: leaves.map(({ id }) => id),
251
+ deltas: [],
252
+ };
253
+ return yield* callDrizzleKit("reconstruct", () => reconstruct({ ...files, [`99999999999999_${MERGE_ID}`]: merge }, MERGE_ID));
221
254
  });
222
255
  /**
223
- * Run drizzle-kit's diff against the latest stored snapshot and
224
- * return whether any SQL statements would be emitted. Used by both
225
- * `diff` (to decide whether the resource actually needs an update)
226
- * and `regenerate` (to decide whether to write a new migration dir).
256
+ * The previous and current schema, for working out which entities a
257
+ * rename-or-create question could have been renamed from.
227
258
  */
228
- const detectDrift = (props) => Effect.gen(function* () {
229
- const out = resolveOut(props);
259
+ const loadRenameContext = Effect.fn("Drizzle.loadRenameContext")(function* (props, out) {
230
260
  const dialect = props.dialect ?? "postgres";
231
- const kit = yield* loadKit(dialect);
232
- if (!kit.generateDrizzleJson || !kit.generateMigration) {
233
- return yield* detectDriftWithCli(props);
234
- }
235
- const generateDrizzleJson = kit.generateDrizzleJson;
236
- const generateMigration = kit.generateMigration;
237
- const schemaModule = yield* loadSchemaModule(props);
238
- const prevEntry = yield* readLatestSnapshot(out);
239
- const cur = yield* Effect.tryPromise({
240
- try: () => generateDrizzleJson(schemaModule, prevEntry?.snapshot.id),
241
- catch: (cause) => new Error(`drizzle-kit generateDrizzleJson failed: ${cause}`),
242
- });
243
- // For the initial migration, drizzle-kit needs an *empty* snapshot
244
- // produced by `generateDrizzleJson({})`, not a bare `{}` — the
245
- // snapshot has internal fields (`ddl`, etc.) that the differ reads.
246
- const prev = prevEntry?.snapshot ??
247
- (yield* Effect.tryPromise({
248
- try: () => generateDrizzleJson({}),
249
- catch: (cause) => new Error(`drizzle-kit generateDrizzleJson (empty baseline) failed: ${cause}`),
250
- }));
251
- const sqlStatements = yield* Effect.tryPromise({
252
- try: () => generateMigration(prev, cur),
253
- catch: (cause) => new Error(`drizzle-kit generateMigration failed: ${cause}`),
261
+ const kit = yield* importModule(`drizzle-kit/payload/${dialect}`);
262
+ const schemaModule = yield* Effect.tryPromise({
263
+ try: () => import(__rewriteRelativeImportExtension(/* @vite-ignore */ resolveSchema(props))),
264
+ catch: (cause) => new SchemaImportFailed({ schema: props.schema, cause }),
254
265
  });
255
- return {
256
- mode: "programmatic",
257
- out,
258
- cur,
259
- prevEntry,
260
- sqlStatements,
261
- };
262
- }).pipe(Artifacts.cached("detectDrift"));
266
+ const cur = yield* callDrizzleKit("generateDrizzleJson", () => kit.generateDrizzleJson(schemaModule));
267
+ const prev = yield* readPreviousSnapshot(kit, out);
268
+ return { prev: prev?.ddl ?? [], cur: cur.ddl ?? [] };
269
+ });
263
270
  /**
264
- * Generate a new migration directory if the schema has drifted from
265
- * the latest snapshot. Returns the new state regardless.
271
+ * Dry-run `drizzle-kit generate` until it has no unanswered questions,
272
+ * asking the user each rename-or-create question it reports. The SQL is
273
+ * applied to the real database later in the same deploy, so ambiguous
274
+ * changes are never answered automatically.
266
275
  */
267
- const regenerate = (props) => Effect.gen(function* () {
268
- const drift = yield* detectDrift(props);
269
- if (drift.mode === "cli") {
270
- if (drift.changed) {
271
- yield* runDrizzleGenerate(props, drift.out);
276
+ const resolveHints = Effect.fn("Drizzle.resolveHints")(function* (props, out) {
277
+ const hints = [];
278
+ const context = yield* Effect.cached(loadRenameContext(props, out));
279
+ // `explain` dry-runs generate: it reports the pending migration
280
+ // (`ok`), `no_changes`, or the questions it still needs answered
281
+ // (`missing_hints`) without writing anything. Answers can raise new
282
+ // questions (columns of a renamed table), so ask until none are left.
283
+ const result = yield* Effect.gen(function* () {
284
+ const result = yield* drizzleKit.generate({
285
+ dialect: cliDialect(props),
286
+ schema: schemaGlob(props),
287
+ out,
288
+ explain: true,
289
+ hints,
290
+ });
291
+ if (result.status === "missing_hints") {
292
+ const { prev, cur } = yield* context;
293
+ for (const hint of result.unresolved) {
294
+ hints.push(yield* askHint(props, hint, prev, cur, hints));
295
+ }
272
296
  }
273
- const migrations = yield* listMigrationDirs(drift.out);
274
- const latest = yield* readLatestSnapshot(drift.out);
275
- const snapshotHash = latest?.hash ?? sha(JSON.stringify(drift.cur));
276
- return {
277
- out: relativeOut(drift.out),
278
- snapshotHash,
279
- migrations,
280
- };
281
- }
282
- const { out, cur, sqlStatements } = drift;
283
- if (sqlStatements.length > 0) {
297
+ return result;
298
+ }).pipe(Effect.repeat({ until: (result) => result.status !== "missing_hints" }));
299
+ return { hints, changed: result.status === "ok" };
300
+ });
301
+ /**
302
+ * Decide what a deploy would change, without touching `out`: upgrade a
303
+ * scratch copy of the folder, then resolve every question drizzle-kit
304
+ * has about the schema change. Cached so `diff` and `reconcile` share
305
+ * one set of answers.
306
+ */
307
+ const detectDrift = Effect.fn("Drizzle.detectDrift")(function* (props) {
308
+ const out = resolveOut(props);
309
+ const scratch = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-drizzle-" });
310
+ const migrations = path.join(scratch, "migrations");
311
+ if (yield* fs.exists(out))
312
+ yield* fs.copy(out, migrations);
313
+ const upgraded = yield* upgradeFolder(props, migrations);
314
+ const { hints, changed } = yield* resolveHints(props, migrations);
315
+ return { out, upgraded, hints, changed };
316
+ },
317
+ // Keyed by props: an interrupted create's recovery `read` sees the
318
+ // persisted props, which may differ from the ones being deployed.
319
+ (effect, props) => effect.pipe(Effect.scoped, Artifacts.cached(`detectDrift:${cliDialect(props)}:${resolveSchema(props)}:${resolveOut(props)}`)));
320
+ /**
321
+ * Upgrade `out` if needed and generate the pending migration with the
322
+ * answers gathered by {@link detectDrift}.
323
+ */
324
+ const regenerate = Effect.fn("Drizzle.regenerate")(function* (props) {
325
+ const { out, upgraded, hints, changed } = yield* detectDrift(props);
326
+ if (upgraded)
327
+ yield* upgradeFolder(props, out);
328
+ if (changed) {
284
329
  yield* fs.makeDirectory(out, { recursive: true });
285
- const dirName = `${tsStamp()}_migration`;
286
- const dirPath = path.join(out, dirName);
287
- yield* fs.makeDirectory(dirPath, { recursive: true });
288
- const sql = sqlStatements.join("\n--> statement-breakpoint\n") + "\n";
289
- yield* fs.writeFileString(path.join(dirPath, "migration.sql"), sql);
290
- yield* fs.writeFileString(path.join(dirPath, "snapshot.json"), JSON.stringify(cur, null, 2));
330
+ const result = yield* drizzleKit.generate({
331
+ dialect: cliDialect(props),
332
+ schema: schemaGlob(props),
333
+ out,
334
+ hints,
335
+ });
336
+ if (result.status === "missing_hints") {
337
+ return yield* new UndecidedSchemaChange({ props, hint: result.unresolved[0] });
338
+ }
291
339
  }
292
- const migrations = yield* listMigrationDirs(out);
293
340
  const latest = yield* readLatestSnapshot(out);
294
- const snapshotHash = latest?.hash ?? sha(JSON.stringify(cur));
295
341
  return {
296
342
  out: relativeOut(out),
297
- snapshotHash,
298
- migrations,
343
+ snapshotHash: latest?.hash ?? sha(""),
344
+ migrations: yield* listMigrationDirs(out),
299
345
  };
300
346
  });
301
347
  return {
@@ -307,14 +353,17 @@ export const SchemaProvider = () => Provider.effect(Schema, Effect.gen(function*
307
353
  diff: Effect.fn(function* ({ news, output }) {
308
354
  if (!isResolved(news))
309
355
  return undefined;
310
- if (!output)
356
+ if (!output) {
357
+ // Re-driving an interrupted create: answer questions now, not
358
+ // during apply.
359
+ yield* detectDrift(news);
311
360
  return undefined;
312
- // Only flag an update when drizzle-kit would emit new SQL —
313
- // otherwise downstream resources (e.g. Neon.Branch) would see
314
- // `schema.out` as an unresolved Output during plan and cascade
315
- // into spurious updates of their own.
316
- const drift = yield* detectDrift(news);
317
- const changed = drift.mode === "cli" ? drift.changed : drift.sqlStatements.length > 0;
361
+ }
362
+ // Only flag an update when drizzle-kit would emit new SQL (or the
363
+ // folder needs upgrading) — otherwise downstream resources (e.g.
364
+ // Neon.Branch) would see `schema.out` as an unresolved Output during
365
+ // plan and cascade into spurious updates of their own.
366
+ const { changed, upgraded } = yield* detectDrift(news);
318
367
  // Originally `output.out` was an absolute path, which is not portable.
319
368
  // So, we trigger an update to migrate existing resources to the
320
369
  // canonical (cwd-relative) form. This is safe because `regenerate`
@@ -322,13 +371,19 @@ export const SchemaProvider = () => Provider.effect(Schema, Effect.gen(function*
322
371
  // testing `isAbsolute`: on Windows a cross-drive `out` can never be
323
372
  // relativized, so its canonical form IS absolute and an isAbsolute
324
373
  // check would flag an update on every deploy.
325
- return changed || output.out !== relativeOut(resolveOut(news))
374
+ return changed || upgraded || output.out !== relativeOut(resolveOut(news))
326
375
  ? { action: "update" }
327
376
  : undefined;
328
377
  }),
329
378
  read: Effect.fn(function* ({ olds, output }) {
330
- if (!output)
379
+ if (!output) {
380
+ // A create never reaches `diff`; plan only calls `read` to look
381
+ // for something to adopt. Ask any rename questions now so they
382
+ // are answered before apply starts changing other resources.
383
+ if (olds && isResolved(olds))
384
+ yield* detectDrift(olds);
331
385
  return undefined;
386
+ }
332
387
  const out = resolveOut(olds ?? {});
333
388
  const exists = yield* fs.exists(out);
334
389
  if (!exists)
@@ -351,22 +406,109 @@ export const SchemaProvider = () => Provider.effect(Schema, Effect.gen(function*
351
406
  }),
352
407
  };
353
408
  }));
354
- const copyDirectory = (from, to) => Effect.gen(function* () {
355
- const path = yield* Path.Path;
356
- const fs = yield* FileSystem.FileSystem;
357
- yield* fs.makeDirectory(to, { recursive: true });
358
- const entries = yield* fs.readDirectory(from);
359
- for (const entry of entries) {
360
- const source = path.join(from, entry);
361
- const target = path.join(to, entry);
362
- const stat = yield* fs.stat(source);
363
- if (stat.type === "Directory") {
364
- yield* copyDirectory(source, target);
365
- }
366
- else {
367
- const contents = yield* fs.readFile(source);
368
- yield* fs.writeFile(target, contents);
369
- }
370
- }
409
+ // drizzle-kit hint kinds → snapshot `ddl` entity types.
410
+ const ddlEntityTypes = {
411
+ table: "tables",
412
+ column: "columns",
413
+ index: "indexes",
414
+ enum: "enums",
415
+ sequence: "sequences",
416
+ view: "views",
417
+ schema: "schemas",
418
+ policy: "policies",
419
+ role: "roles",
420
+ check: "checks",
421
+ unique: "uniques",
422
+ primary_key: "pks",
423
+ "foreign key": "fks",
424
+ };
425
+ const MERGE_ID = "alchemy-unmerged-branches";
426
+ // mysql and sqlite have no schemas; drizzle-kit fills ids with `public`.
427
+ const DEFAULT_SCHEMA = "public";
428
+ const formatEntity = (entity) => (entity.length > 1 && entity[0] === DEFAULT_SCHEMA ? entity.slice(1) : entity).join(".");
429
+ const locate = (row) => ({
430
+ entityType: row.entityType,
431
+ schema: row.schema ?? DEFAULT_SCHEMA,
432
+ table: row.table ?? "",
433
+ name: row.name ?? "",
371
434
  });
435
+ const idOf = (row, arity) => Match.value(arity).pipe(Match.when(1, () => [row.name]), Match.when(2, () => [row.schema, row.name]), Match.orElse(() => [row.schema, row.table, row.name]));
436
+ // Give `row` the id `to`, shaped like the `from` id it was matched by.
437
+ const withId = (row, to) => Match.value(to.length).pipe(Match.when(1, () => ({ ...row, name: to[0] })), Match.when(2, () => ({ ...row, schema: to[0], name: to[1] })), Match.orElse(() => ({ ...row, schema: to[0], table: to[1], name: to[2] })));
438
+ const renameRow = (row, rename) => {
439
+ const { from, to } = rename;
440
+ return Match.value(rename).pipe(
441
+ // Schema rows name themselves; everything else names its schema.
442
+ Match.when({ kind: "schema" }, () => Match.value(row).pipe(Match.when({ entityType: "schemas", name: from[0] }, () => ({ ...row, name: to[0] })), Match.when({ entityType: (type) => type !== "schemas", schema: from[0] }, () => ({
443
+ ...row,
444
+ schema: to[0],
445
+ })), Match.orElse(() => row))),
446
+ // The table and everything inside it follow the rename (or move).
447
+ Match.when({ kind: "table" }, () => Match.value(row).pipe(Match.when({ entityType: "tables", schema: from[0], name: from[1] }, () => withId(row, to)), Match.when({ schema: from[0], table: from[1] }, () => ({
448
+ ...row,
449
+ schema: to[0],
450
+ table: to[1],
451
+ })), Match.orElse(() => row))), Match.orElse(({ kind }) => row.entityType === ddlEntityTypes[kind] &&
452
+ JSON.stringify(idOf(row, from.length)) === JSON.stringify(from)
453
+ ? withId(row, to)
454
+ : row));
455
+ };
456
+ /**
457
+ * Carry previous entities through the renames answered so far, so a later
458
+ * question about the renamed table (or a table moved to another schema)
459
+ * matches the entities that moved with it.
460
+ */
461
+ const applyRenames = (rows, hints) => {
462
+ let current = rows;
463
+ for (const hint of hints) {
464
+ if (hint.type === "rename")
465
+ current = current.map((row) => renameRow(row, hint));
466
+ }
467
+ return current;
468
+ };
469
+ /**
470
+ * Entities a rename-or-create question could have been renamed from: same
471
+ * kind, present before (after the renames answered so far), gone now.
472
+ * Columns, indexes, … are offered from the same table first.
473
+ */
474
+ const renameCandidates = (hint, prev, cur, hints) => {
475
+ const entityType = ddlEntityTypes[hint.kind];
476
+ const arity = hint.entity.length;
477
+ const ofKind = (rows) => rows.filter((row) => row.entityType === entityType);
478
+ const current = new Set(ofKind(cur.map(locate)).map((row) => JSON.stringify(idOf(row, arity))));
479
+ const gone = ofKind(applyRenames(prev.map(locate), hints))
480
+ .map((row) => idOf(row, arity))
481
+ .filter((id) => !current.has(JSON.stringify(id)));
482
+ const sameParent = gone.filter((id) => arity < 3 || (id[0] === hint.entity[0] && id[1] === hint.entity[1]));
483
+ return sameParent.length > 0 ? sameParent : gone;
484
+ };
485
+ /**
486
+ * Answer one drizzle-kit `MissingHint` with an Alchemy prompt. drizzle-kit
487
+ * only asks when a rename is possible, so the question is always shown —
488
+ * never answered with "create" on the user's behalf. A dismissed prompt stays
489
+ * a `TerminalCancelled` so the CLI exits quietly, the same as cancelling the
490
+ * deploy confirmation.
491
+ */
492
+ const askHint = Effect.fn("Drizzle.askHint")(function* (props, hint, prev, cur, hints) {
493
+ const interaction = yield* Effect.serviceOption(Interaction);
494
+ if (Option.isNone(interaction))
495
+ return yield* new UndecidedSchemaChange({ props, hint });
496
+ const name = formatEntity(hint.entity);
497
+ return yield* interaction.value.prompt.select({
498
+ message: `Is ${hint.kind} ${name} created or renamed from another ${hint.kind}?`,
499
+ options: [
500
+ {
501
+ value: { type: "create", kind: hint.kind, entity: hint.entity },
502
+ label: `+ ${name}`,
503
+ description: `create ${hint.kind}`,
504
+ },
505
+ ...renameCandidates(hint, prev, cur, hints).map((from) => ({
506
+ value: { type: "rename", kind: hint.kind, from, to: hint.entity },
507
+ label: `~ ${formatEntity(from)} › ${name}`,
508
+ description: `rename ${hint.kind}`,
509
+ })),
510
+ ],
511
+ descriptionPlacement: "inline",
512
+ });
513
+ }, (effect, props, hint) => effect.pipe(Effect.catchTag("NonInteractiveTerminal", () => Effect.fail(new UndecidedSchemaChange({ props, hint })))));
372
514
  //# sourceMappingURL=Schema.js.map