The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import * as Drizzle from "@alchemy.run/drizzle"; |
| 2 | import { expect } from "@alchemy.run/test"; |
| 3 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 4 | import { |
| 5 | Interaction, |
| 6 | type InteractionError, |
| 7 | type SelectOptions, |
| 8 | TerminalCancelled, |
| 9 | } from "alchemy/Interaction"; |
| 10 | import * as Provider from "alchemy/Provider"; |
| 11 | import * as Stack from "alchemy/Stack"; |
| 12 | import { isResourceState, State } from "alchemy/State"; |
| 13 | import { generate, type GenerateOptions } from "drizzle-kit/cli"; |
| 14 | import * as PostgresKit from "drizzle-kit/payload/postgres"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as FileSystem from "effect/FileSystem"; |
| 17 | import * as Path from "effect/Path"; |
| 18 | import * as Predicate from "effect/Predicate"; |
| 19 | import * as Result from "effect/Result"; |
| 20 | import * as S from "effect/Schema"; |
| 21 | |
| 22 | const { test } = Test.make({ providers: Drizzle.providers() }); |
| 23 | |
| 24 | const DRIZZLE_ORIGIN_UUID = "00000000-0000-0000-0000-000000000000"; |
| 25 | |
| 26 | // Minimal drizzle-orm schema source — enough for `generateDrizzleJson` |
| 27 | // to produce a non-empty snapshot. |
| 28 | const SCHEMA_SOURCE = ` |
| 29 | import { pgTable, serial, text } from "drizzle-orm/pg-core"; |
| 30 | |
| 31 | export const users = pgTable("users", { |
| 32 | id: serial("id").primaryKey(), |
| 33 | name: text("name").notNull(), |
| 34 | }); |
| 35 | `; |
| 36 | |
| 37 | const DRIFTED_SCHEMA_SOURCE = |
| 38 | SCHEMA_SOURCE + |
| 39 | `\nexport const posts = pgTable("posts", {\n id: serial("id").primaryKey(),\n title: text("title").notNull(),\n});\n`; |
| 40 | |
| 41 | const SQLITE_SCHEMA_SOURCE = ` |
| 42 | import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; |
| 43 | |
| 44 | export const users = sqliteTable("users", { |
| 45 | id: integer("id").primaryKey(), |
| 46 | name: text("name").notNull(), |
| 47 | }); |
| 48 | `; |
| 49 | |
| 50 | const SQLITE_DRIFTED_SCHEMA_SOURCE = |
| 51 | SQLITE_SCHEMA_SOURCE + |
| 52 | ` |
| 53 | export const posts = sqliteTable("posts", { |
| 54 | id: integer("id").primaryKey(), |
| 55 | title: text("title").notNull(), |
| 56 | }); |
| 57 | `; |
| 58 | |
| 59 | const SQLITE_RENAMED_COLUMN_SCHEMA_SOURCE = ` |
| 60 | import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; |
| 61 | |
| 62 | export const users = sqliteTable("users", { |
| 63 | id: integer("id").primaryKey(), |
| 64 | fullName: text("full_name").notNull(), |
| 65 | }); |
| 66 | `; |
| 67 | |
| 68 | const RENAMED_SCHEMA_SOURCE = ` |
| 69 | import { pgTable, serial, text } from "drizzle-orm/pg-core"; |
| 70 | |
| 71 | export const people = pgTable("people", { |
| 72 | id: serial("id").primaryKey(), |
| 73 | fullName: text("full_name").notNull(), |
| 74 | }); |
| 75 | `; |
| 76 | |
| 77 | // The ambient Interaction with `select` answered by `answer`. |
| 78 | const scriptedSelect = Effect.fn(function* ( |
| 79 | answer: (options: SelectOptions<unknown>) => Effect.Effect<unknown, InteractionError>, |
| 80 | ) { |
| 81 | const base = yield* Interaction; |
| 82 | return Interaction.of({ |
| 83 | ...base, |
| 84 | prompt: { |
| 85 | ...base.prompt, |
| 86 | select: <Value>(options: SelectOptions<Value>) => |
| 87 | answer(options) as Effect.Effect<Value, InteractionError>, |
| 88 | }, |
| 89 | }); |
| 90 | }); |
| 91 | |
| 92 | const stageWorkspace = (initialSource: string) => |
| 93 | Effect.gen(function* () { |
| 94 | const fs = yield* FileSystem.FileSystem; |
| 95 | const path = yield* Path.Path; |
| 96 | // Stage inside the repo (not the OS temp dir): the schema module is |
| 97 | // loaded via dynamic `import()`, and bun resolves its bare |
| 98 | // `drizzle-orm/*` imports by walking up from the schema file — which |
| 99 | // only finds `node_modules` when the staging dir lives in the workspace. |
| 100 | const cwd = yield* Effect.sync(() => process.cwd()); |
| 101 | const tempParent = path.join(cwd, ".alchemy", "tmp"); |
| 102 | yield* fs.makeDirectory(tempParent, { recursive: true }); |
| 103 | const root = yield* fs.makeTempDirectory({ |
| 104 | directory: tempParent, |
| 105 | prefix: "alchemy-drizzle-schema-test-", |
| 106 | }); |
| 107 | const schemaPath = path.join(root, "schema.ts"); |
| 108 | yield* fs.writeFileString(schemaPath, initialSource); |
| 109 | const out = path.join(root, "migrations"); |
| 110 | return { root, out, schemaPath }; |
| 111 | }); |
| 112 | |
| 113 | const readMigrationDirs = (out: string) => |
| 114 | Effect.gen(function* () { |
| 115 | const fs = yield* FileSystem.FileSystem; |
| 116 | return (yield* fs.readDirectory(out)).filter((name) => /^\d+_/.test(name)).sort(); |
| 117 | }); |
| 118 | |
| 119 | // Returns snapshots in chain order (each entry's prevIds points at the one |
| 120 | // before it). Directory-name order is NOT reliable: two migrations generated |
| 121 | // within the same second share the timestamp prefix and then sort by the |
| 122 | // random name suffix. |
| 123 | const readSnapshots = (out: string) => |
| 124 | Effect.gen(function* () { |
| 125 | const fs = yield* FileSystem.FileSystem; |
| 126 | const path = yield* Path.Path; |
| 127 | const dirs = yield* readMigrationDirs(out); |
| 128 | const snapshots: Array<{ id: string; prevIds: string[] }> = []; |
| 129 | for (const dir of dirs) { |
| 130 | const text = yield* fs.readFileString(path.join(out, dir, "snapshot.json")); |
| 131 | snapshots.push( |
| 132 | yield* Effect.try({ |
| 133 | try: () => JSON.parse(text) as { id: string; prevIds: string[] }, |
| 134 | catch: (cause) => new Error(`Failed to parse snapshot: ${cause}`), |
| 135 | }), |
| 136 | ); |
| 137 | } |
| 138 | const byPrev = new Map(snapshots.map((s) => [s.prevIds[0], s])); |
| 139 | const ordered: typeof snapshots = []; |
| 140 | let cursor = byPrev.get("00000000-0000-0000-0000-000000000000"); |
| 141 | while (cursor !== undefined) { |
| 142 | ordered.push(cursor); |
| 143 | cursor = byPrev.get(cursor.id); |
| 144 | } |
| 145 | return ordered.length === snapshots.length ? ordered : snapshots; |
| 146 | }); |
| 147 | |
| 148 | const getStatus = Effect.fn(function* (fqn: string) { |
| 149 | const state = yield* yield* State; |
| 150 | const stk = yield* Stack.Stack; |
| 151 | const s = yield* state.get({ stack: stk.name, stage: stk.stage, fqn }); |
| 152 | return s?.status; |
| 153 | }); |
| 154 | |
| 155 | test.provider( |
| 156 | "initial snapshot starts from the Drizzle origin", |
| 157 | (stack) => |
| 158 | Effect.gen(function* () { |
| 159 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 160 | |
| 161 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out })); |
| 162 | |
| 163 | const snapshots = yield* readSnapshots(ws.out); |
| 164 | expect(snapshots).toHaveLength(1); |
| 165 | expect(snapshots[0]?.prevIds).toEqual([DRIZZLE_ORIGIN_UUID]); |
| 166 | }), |
| 167 | { tags: ["unit", "local"] }, |
| 168 | ); |
| 169 | |
| 170 | test.provider( |
| 171 | "repeated deploys with no schema drift produce noop, not update (regression: forced update cascaded into Neon.Branch)", |
| 172 | (stack) => |
| 173 | Effect.gen(function* () { |
| 174 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 175 | |
| 176 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out })); |
| 177 | expect(yield* getStatus("app-schema")).toEqual("created"); |
| 178 | |
| 179 | // Second deploy with the same schema. Before the fix, Schema.diff |
| 180 | // returned `{ action: "update" }` unconditionally, so status would |
| 181 | // flip to "updated" and downstream resources (e.g. Neon.Branch) |
| 182 | // would see `schema.out` as an unresolved Output during plan and |
| 183 | // cascade into their own spurious updates. |
| 184 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out })); |
| 185 | expect(yield* getStatus("app-schema")).toEqual("created"); |
| 186 | }), |
| 187 | { tags: ["unit", "local"] }, |
| 188 | ); |
| 189 | |
| 190 | test.provider( |
| 191 | "deploy after a real schema change updates the resource", |
| 192 | (stack) => |
| 193 | Effect.gen(function* () { |
| 194 | const fs = yield* FileSystem.FileSystem; |
| 195 | const path = yield* Path.Path; |
| 196 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 197 | |
| 198 | const initial = yield* stack.deploy( |
| 199 | Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out }), |
| 200 | ); |
| 201 | const [initialSnapshot] = yield* readSnapshots(ws.out); |
| 202 | |
| 203 | // Write the drifted schema as a *new* file so the dynamic import |
| 204 | // cache doesn't hand us the original module. |
| 205 | const driftedSchemaPath = path.join(ws.root, "schema-drifted.ts"); |
| 206 | yield* fs.writeFileString(driftedSchemaPath, DRIFTED_SCHEMA_SOURCE); |
| 207 | yield* Effect.sleep("1 second"); |
| 208 | |
| 209 | const drifted = yield* stack.deploy( |
| 210 | Drizzle.Schema("app-schema", { schema: driftedSchemaPath, out: ws.out }), |
| 211 | ); |
| 212 | |
| 213 | expect(yield* getStatus("app-schema")).toEqual("updated"); |
| 214 | expect(drifted.snapshotHash).not.toEqual(initial.snapshotHash); |
| 215 | const snapshots = yield* readSnapshots(ws.out); |
| 216 | expect(snapshots).toHaveLength(2); |
| 217 | expect(snapshots[1]?.prevIds).toEqual([initialSnapshot?.id]); |
| 218 | }), |
| 219 | { tags: ["unit", "local"] }, |
| 220 | ); |
| 221 | |
| 222 | test.provider( |
| 223 | "list returns [] (non-listable local build artifact)", |
| 224 | (stack) => |
| 225 | Effect.gen(function* () { |
| 226 | yield* stack.destroy(); |
| 227 | |
| 228 | const provider = yield* Provider.findProvider(Drizzle.Schema); |
| 229 | const all = yield* provider.list(); |
| 230 | expect(all).toEqual([]); |
| 231 | |
| 232 | yield* stack.destroy(); |
| 233 | }), |
| 234 | { tags: ["unit", "local"] }, |
| 235 | ); |
| 236 | |
| 237 | test.provider( |
| 238 | "sqlite schemas generate migrations programmatically", |
| 239 | (stack) => |
| 240 | Effect.gen(function* () { |
| 241 | const ws = yield* stageWorkspace(SQLITE_SCHEMA_SOURCE); |
| 242 | |
| 243 | yield* stack.deploy( |
| 244 | Drizzle.Schema("sqlite-schema", { dialect: "sqlite", schema: ws.schemaPath, out: ws.out }), |
| 245 | ); |
| 246 | |
| 247 | const dirs = yield* readMigrationDirs(ws.out); |
| 248 | expect(dirs).toHaveLength(1); |
| 249 | |
| 250 | const snapshots = yield* readSnapshots(ws.out); |
| 251 | expect(snapshots).toHaveLength(1); |
| 252 | expect(snapshots[0]?.prevIds).toEqual([DRIZZLE_ORIGIN_UUID]); |
| 253 | }), |
| 254 | { tags: ["unit", "local"] }, |
| 255 | ); |
| 256 | |
| 257 | test.provider( |
| 258 | "sqlite repeated deploys with no drift stay noop", |
| 259 | (stack) => |
| 260 | Effect.gen(function* () { |
| 261 | const ws = yield* stageWorkspace(SQLITE_SCHEMA_SOURCE); |
| 262 | |
| 263 | yield* stack.deploy( |
| 264 | Drizzle.Schema("sqlite-schema", { dialect: "sqlite", schema: ws.schemaPath, out: ws.out }), |
| 265 | ); |
| 266 | const initialDirs = yield* readMigrationDirs(ws.out); |
| 267 | expect(yield* getStatus("sqlite-schema")).toEqual("created"); |
| 268 | |
| 269 | yield* stack.deploy( |
| 270 | Drizzle.Schema("sqlite-schema", { dialect: "sqlite", schema: ws.schemaPath, out: ws.out }), |
| 271 | ); |
| 272 | |
| 273 | expect(yield* getStatus("sqlite-schema")).toEqual("created"); |
| 274 | expect(yield* readMigrationDirs(ws.out)).toEqual(initialDirs); |
| 275 | }), |
| 276 | { tags: ["unit", "local"] }, |
| 277 | ); |
| 278 | |
| 279 | test.provider( |
| 280 | "sqlite updates after schema drift", |
| 281 | (stack) => |
| 282 | Effect.gen(function* () { |
| 283 | const fs = yield* FileSystem.FileSystem; |
| 284 | const path = yield* Path.Path; |
| 285 | const ws = yield* stageWorkspace(SQLITE_SCHEMA_SOURCE); |
| 286 | |
| 287 | yield* stack.deploy( |
| 288 | Drizzle.Schema("sqlite-schema", { dialect: "sqlite", schema: ws.schemaPath, out: ws.out }), |
| 289 | ); |
| 290 | const [initialSnapshot] = yield* readSnapshots(ws.out); |
| 291 | |
| 292 | const driftedSchemaPath = path.join(ws.root, "schema-sqlite-drifted.ts"); |
| 293 | yield* fs.writeFileString(driftedSchemaPath, SQLITE_DRIFTED_SCHEMA_SOURCE); |
| 294 | yield* Effect.sleep("1 second"); |
| 295 | |
| 296 | yield* stack.deploy( |
| 297 | Drizzle.Schema("sqlite-schema", { |
| 298 | dialect: "sqlite", |
| 299 | schema: driftedSchemaPath, |
| 300 | out: ws.out, |
| 301 | }), |
| 302 | ); |
| 303 | |
| 304 | expect(yield* getStatus("sqlite-schema")).toEqual("updated"); |
| 305 | const dirs = yield* readMigrationDirs(ws.out); |
| 306 | expect(dirs).toHaveLength(2); |
| 307 | |
| 308 | const snapshots = yield* readSnapshots(ws.out); |
| 309 | expect(snapshots).toHaveLength(2); |
| 310 | expect(snapshots[1]?.prevIds).toEqual([initialSnapshot?.id]); |
| 311 | }), |
| 312 | { tags: ["unit", "local"] }, |
| 313 | ); |
| 314 | |
| 315 | test.provider( |
| 316 | "sqlite refuses ambiguous drift", |
| 317 | (stack) => |
| 318 | Effect.gen(function* () { |
| 319 | const fs = yield* FileSystem.FileSystem; |
| 320 | const path = yield* Path.Path; |
| 321 | const ws = yield* stageWorkspace(SQLITE_SCHEMA_SOURCE); |
| 322 | |
| 323 | yield* stack.deploy( |
| 324 | Drizzle.Schema("sqlite-schema", { dialect: "sqlite", schema: ws.schemaPath, out: ws.out }), |
| 325 | ); |
| 326 | const initialDirs = yield* readMigrationDirs(ws.out); |
| 327 | |
| 328 | const renamedSchemaPath = path.join(ws.root, "schema-sqlite-renamed.ts"); |
| 329 | yield* fs.writeFileString(renamedSchemaPath, SQLITE_RENAMED_COLUMN_SCHEMA_SOURCE); |
| 330 | yield* Effect.sleep("1 second"); |
| 331 | |
| 332 | // A column rename is ambiguous (rename vs drop+create) and the chosen |
| 333 | // SQL is applied to the real database later in the same deploy, so the |
| 334 | // deploy must fail with guidance instead of deciding. |
| 335 | const result = yield* Effect.result( |
| 336 | stack.deploy( |
| 337 | Drizzle.Schema("sqlite-schema", { |
| 338 | dialect: "sqlite", |
| 339 | schema: renamedSchemaPath, |
| 340 | out: ws.out, |
| 341 | }), |
| 342 | ), |
| 343 | ); |
| 344 | |
| 345 | expect(Result.isFailure(result)).toBe(true); |
| 346 | if (Result.isFailure(result)) { |
| 347 | expect(String(result.failure)).toContain("needs a decision"); |
| 348 | } |
| 349 | // No migration was written for the undecided drift. |
| 350 | expect(yield* readMigrationDirs(ws.out)).toEqual(initialDirs); |
| 351 | }), |
| 352 | { tags: ["unit", "local"] }, |
| 353 | ); |
| 354 | |
| 355 | test.provider( |
| 356 | "ambiguous renames are answered through Alchemy's prompts", |
| 357 | (stack) => |
| 358 | Effect.gen(function* () { |
| 359 | const fs = yield* FileSystem.FileSystem; |
| 360 | const path = yield* Path.Path; |
| 361 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 362 | |
| 363 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out })); |
| 364 | |
| 365 | const renamedSchemaPath = path.join(ws.root, "schema-renamed.ts"); |
| 366 | yield* fs.writeFileString(renamedSchemaPath, RENAMED_SCHEMA_SOURCE); |
| 367 | yield* Effect.sleep("1 second"); |
| 368 | |
| 369 | // Answer every rename-or-create question with the offered rename. |
| 370 | const asked: Array<{ message: string; labels: string[] }> = []; |
| 371 | const scripted = yield* scriptedSelect((options) => |
| 372 | Effect.sync(() => { |
| 373 | asked.push({ |
| 374 | message: options.message, |
| 375 | labels: options.options.map((option) => option.label), |
| 376 | }); |
| 377 | const rename = options.options.find( |
| 378 | ({ value }) => Predicate.hasProperty(value, "type") && value.type === "rename", |
| 379 | ); |
| 380 | return (rename ?? options.options[0]!).value; |
| 381 | }), |
| 382 | ); |
| 383 | |
| 384 | yield* stack |
| 385 | .deploy(Drizzle.Schema("app-schema", { schema: renamedSchemaPath, out: ws.out })) |
| 386 | .pipe(Effect.provideService(Interaction, scripted)); |
| 387 | |
| 388 | // Table first, then the column inside the already-renamed table. |
| 389 | expect(asked).toEqual([ |
| 390 | { |
| 391 | message: "Is table people created or renamed from another table?", |
| 392 | labels: ["+ people", "~ users › people"], |
| 393 | }, |
| 394 | { |
| 395 | message: "Is column people.full_name created or renamed from another column?", |
| 396 | labels: ["+ people.full_name", "~ people.name › people.full_name"], |
| 397 | }, |
| 398 | ]); |
| 399 | const dirs = yield* readMigrationDirs(ws.out); |
| 400 | expect(dirs).toHaveLength(2); |
| 401 | const sql = yield* fs.readFileString(path.join(ws.out, dirs[1]!, "migration.sql")); |
| 402 | expect(sql).toContain('ALTER TABLE "users" RENAME TO "people"'); |
| 403 | expect(sql).toContain('RENAME COLUMN "name" TO "full_name"'); |
| 404 | expect(sql).not.toContain("DROP"); |
| 405 | }), |
| 406 | { tags: ["unit", "local"] }, |
| 407 | ); |
| 408 | |
| 409 | test.provider( |
| 410 | "cancelling a rename prompt cancels the deploy without writing a migration", |
| 411 | (stack) => |
| 412 | Effect.gen(function* () { |
| 413 | const fs = yield* FileSystem.FileSystem; |
| 414 | const path = yield* Path.Path; |
| 415 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 416 | |
| 417 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out })); |
| 418 | const initialDirs = yield* readMigrationDirs(ws.out); |
| 419 | |
| 420 | const renamedSchemaPath = path.join(ws.root, "schema-renamed.ts"); |
| 421 | yield* fs.writeFileString(renamedSchemaPath, RENAMED_SCHEMA_SOURCE); |
| 422 | |
| 423 | const scripted = yield* scriptedSelect(() => Effect.fail(new TerminalCancelled())); |
| 424 | const result = yield* stack |
| 425 | .deploy(Drizzle.Schema("app-schema", { schema: renamedSchemaPath, out: ws.out })) |
| 426 | .pipe(Effect.provideService(Interaction, scripted), Effect.result); |
| 427 | |
| 428 | // The CLI exits quietly on a `TerminalCancelled`, so it must reach the |
| 429 | // caller unwrapped rather than as a generic Error. |
| 430 | expect( |
| 431 | Result.isFailure(result) && Predicate.isTagged(result.failure, "TerminalCancelled"), |
| 432 | ).toBe(true); |
| 433 | expect(yield* readMigrationDirs(ws.out)).toEqual(initialDirs); |
| 434 | }), |
| 435 | { tags: ["unit", "local"] }, |
| 436 | ); |
| 437 | |
| 438 | test.provider( |
| 439 | "renames inside a table moved to another schema are offered, not dropped", |
| 440 | (stack) => |
| 441 | Effect.gen(function* () { |
| 442 | const fs = yield* FileSystem.FileSystem; |
| 443 | const path = yield* Path.Path; |
| 444 | const ws = yield* stageWorkspace(` |
| 445 | import { pgSchema, serial, text } from "drizzle-orm/pg-core"; |
| 446 | |
| 447 | export const a = pgSchema("a"); |
| 448 | export const b = pgSchema("b"); |
| 449 | export const users = a.table("users", { id: serial("id").primaryKey(), old: text("old") }); |
| 450 | `); |
| 451 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out })); |
| 452 | |
| 453 | const movedSchemaPath = path.join(ws.root, "schema-moved.ts"); |
| 454 | yield* fs.writeFileString( |
| 455 | movedSchemaPath, |
| 456 | ` |
| 457 | import { pgSchema, serial, text } from "drizzle-orm/pg-core"; |
| 458 | |
| 459 | export const a = pgSchema("a"); |
| 460 | export const b = pgSchema("b"); |
| 461 | export const users = b.table("users", { id: serial("id").primaryKey(), new: text("new") }); |
| 462 | `, |
| 463 | ); |
| 464 | yield* Effect.sleep("1 second"); |
| 465 | |
| 466 | const asked: Array<Array<string>> = []; |
| 467 | const scripted = yield* scriptedSelect((options) => |
| 468 | Effect.sync(() => { |
| 469 | asked.push(options.options.map((option) => option.label)); |
| 470 | const rename = options.options.find( |
| 471 | ({ value }) => Predicate.hasProperty(value, "type") && value.type === "rename", |
| 472 | ); |
| 473 | return (rename ?? options.options[0]!).value; |
| 474 | }), |
| 475 | ); |
| 476 | yield* stack |
| 477 | .deploy(Drizzle.Schema("app-schema", { schema: movedSchemaPath, out: ws.out })) |
| 478 | .pipe(Effect.provideService(Interaction, scripted)); |
| 479 | |
| 480 | // The column question refers to the moved table; its candidates must |
| 481 | // follow the table into schema `b`. |
| 482 | expect(asked).toEqual([ |
| 483 | ["+ b.users", "~ a.users › b.users"], |
| 484 | ["+ b.users.new", "~ b.users.old › b.users.new"], |
| 485 | ]); |
| 486 | const dirs = yield* readMigrationDirs(ws.out); |
| 487 | const sql = yield* fs.readFileString(path.join(ws.out, dirs[1]!, "migration.sql")); |
| 488 | expect(sql).toContain('RENAME COLUMN "old" TO "new"'); |
| 489 | expect(sql).not.toContain("DROP"); |
| 490 | }), |
| 491 | { tags: ["unit", "local"] }, |
| 492 | ); |
| 493 | |
| 494 | test.provider( |
| 495 | "a renamed schema is not offered again as a rename source", |
| 496 | (stack) => |
| 497 | Effect.gen(function* () { |
| 498 | const fs = yield* FileSystem.FileSystem; |
| 499 | const path = yield* Path.Path; |
| 500 | const ws = yield* stageWorkspace(` |
| 501 | import { pgSchema } from "drizzle-orm/pg-core"; |
| 502 | |
| 503 | export const a = pgSchema("a"); |
| 504 | `); |
| 505 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out })); |
| 506 | |
| 507 | const nextSchemaPath = path.join(ws.root, "schema-next.ts"); |
| 508 | yield* fs.writeFileString( |
| 509 | nextSchemaPath, |
| 510 | ` |
| 511 | import { pgSchema } from "drizzle-orm/pg-core"; |
| 512 | |
| 513 | export const b = pgSchema("b"); |
| 514 | export const c = pgSchema("c"); |
| 515 | `, |
| 516 | ); |
| 517 | yield* Effect.sleep("1 second"); |
| 518 | |
| 519 | const asked: Array<Array<string>> = []; |
| 520 | const scripted = yield* scriptedSelect((options) => |
| 521 | Effect.sync(() => { |
| 522 | asked.push(options.options.map((option) => option.label)); |
| 523 | const rename = options.options.find( |
| 524 | ({ value }) => Predicate.hasProperty(value, "type") && value.type === "rename", |
| 525 | ); |
| 526 | return (rename ?? options.options[0]!).value; |
| 527 | }), |
| 528 | ); |
| 529 | yield* stack |
| 530 | .deploy(Drizzle.Schema("app-schema", { schema: nextSchemaPath, out: ws.out })) |
| 531 | .pipe(Effect.provideService(Interaction, scripted)); |
| 532 | |
| 533 | // `a` was consumed by the first answer; offering it again for `c` |
| 534 | // would hand drizzle-kit an invalid hint. |
| 535 | expect(asked[0]).toEqual(["+ b", "~ a › b"]); |
| 536 | expect( |
| 537 | asked |
| 538 | .slice(1) |
| 539 | .flat() |
| 540 | .some((label) => label.startsWith("~ a")), |
| 541 | ).toBe(false); |
| 542 | }), |
| 543 | { tags: ["unit", "local"] }, |
| 544 | ); |
| 545 | |
| 546 | test.provider( |
| 547 | "a new resource over an existing folder asks its questions during plan", |
| 548 | (stack) => |
| 549 | Effect.gen(function* () { |
| 550 | const fs = yield* FileSystem.FileSystem; |
| 551 | const path = yield* Path.Path; |
| 552 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 553 | |
| 554 | // Leave the migrations behind but forget the resource, so the next |
| 555 | // deploy plans a create. |
| 556 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out })); |
| 557 | yield* stack.destroy(); |
| 558 | |
| 559 | const renamedSchemaPath = path.join(ws.root, "schema-renamed.ts"); |
| 560 | yield* fs.writeFileString(renamedSchemaPath, RENAMED_SCHEMA_SOURCE); |
| 561 | |
| 562 | const asked: Array<string> = []; |
| 563 | const scripted = yield* scriptedSelect((options) => |
| 564 | Effect.sync(() => { |
| 565 | asked.push(options.message); |
| 566 | return options.options[0]!.value; |
| 567 | }), |
| 568 | ); |
| 569 | const plan = yield* stack |
| 570 | .plan(Drizzle.Schema("app-schema", { schema: renamedSchemaPath, out: ws.out })) |
| 571 | .pipe(Effect.provideService(Interaction, scripted)); |
| 572 | |
| 573 | expect(plan.resources["app-schema"]?.action).toBe("create"); |
| 574 | expect(asked[0]).toEqual("Is table people created or renamed from another table?"); |
| 575 | }), |
| 576 | { tags: ["unit", "local"] }, |
| 577 | ); |
| 578 | |
| 579 | test.provider( |
| 580 | "an interrupted create is re-driven with the new props", |
| 581 | (stack) => |
| 582 | Effect.gen(function* () { |
| 583 | const fs = yield* FileSystem.FileSystem; |
| 584 | const path = yield* Path.Path; |
| 585 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 586 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: ws.out })); |
| 587 | |
| 588 | // The shape an interrupted first deploy leaves behind. |
| 589 | const state = yield* yield* State; |
| 590 | const key = { stack: stack.name, stage: stack.stage, fqn: "app-schema" }; |
| 591 | const row = yield* state.get(key); |
| 592 | if (!isResourceState(row)) return yield* Effect.die(new Error("no app-schema state row")); |
| 593 | yield* state.set({ |
| 594 | ...key, |
| 595 | value: { ...row, props: row.props!, status: "creating", attr: undefined }, |
| 596 | }); |
| 597 | |
| 598 | const otherOut = path.join(ws.root, "other-migrations"); |
| 599 | const result = yield* stack.deploy( |
| 600 | Drizzle.Schema("app-schema", { schema: ws.schemaPath, out: otherOut }), |
| 601 | ); |
| 602 | |
| 603 | expect(path.resolve(result.out)).toEqual(otherOut); |
| 604 | expect(yield* fs.exists(otherOut)).toBe(true); |
| 605 | }), |
| 606 | { tags: ["unit", "local"] }, |
| 607 | ); |
| 608 | |
| 609 | test.provider( |
| 610 | "continues a migrations folder generated by drizzle-kit, and drizzle-kit continues ours", |
| 611 | (stack) => |
| 612 | Effect.gen(function* () { |
| 613 | const fs = yield* FileSystem.FileSystem; |
| 614 | const path = yield* Path.Path; |
| 615 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 616 | const withEmailPath = path.join(ws.root, "schema-email.ts"); |
| 617 | yield* fs.writeFileString( |
| 618 | withEmailPath, |
| 619 | SCHEMA_SOURCE.replace( |
| 620 | 'name: text("name").notNull(),', |
| 621 | 'name: text("name").notNull(),\n email: text("email"),', |
| 622 | ), |
| 623 | ); |
| 624 | const kitGenerate = (schema: string) => |
| 625 | Effect.promise(() => generate({ dialect: "postgresql", schema, out: ws.out })); |
| 626 | |
| 627 | // drizzle-kit writes a `base` snapshot, then a `diff` snapshot. |
| 628 | expect((yield* kitGenerate(ws.schemaPath)).status).toEqual("ok"); |
| 629 | yield* Effect.sleep("1 second"); |
| 630 | expect((yield* kitGenerate(withEmailPath)).status).toEqual("ok"); |
| 631 | |
| 632 | const driftedPath = path.join(ws.root, "schema-drifted.ts"); |
| 633 | yield* fs.writeFileString( |
| 634 | driftedPath, |
| 635 | (yield* fs.readFileString(withEmailPath)) + |
| 636 | `\nexport const posts = pgTable("posts", {\n id: serial("id").primaryKey(),\n});\n`, |
| 637 | ); |
| 638 | yield* Effect.sleep("1 second"); |
| 639 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: driftedPath, out: ws.out })); |
| 640 | |
| 641 | const dirs = yield* readMigrationDirs(ws.out); |
| 642 | expect(dirs).toHaveLength(3); |
| 643 | const sql = yield* fs.readFileString(path.join(ws.out, dirs[2]!, "migration.sql")); |
| 644 | expect(sql).toContain('CREATE TABLE "posts"'); |
| 645 | expect(sql).not.toContain('"email"'); |
| 646 | // The snapshot Alchemy wrote is one drizzle-kit can build on. |
| 647 | expect((yield* kitGenerate(driftedPath)).status).toEqual("no_changes"); |
| 648 | }), |
| 649 | { tags: ["unit", "local"] }, |
| 650 | ); |
| 651 | |
| 652 | test.provider( |
| 653 | "renames after unmerged migration branches are offered from their combined state", |
| 654 | (stack) => |
| 655 | Effect.gen(function* () { |
| 656 | const fs = yield* FileSystem.FileSystem; |
| 657 | const path = yield* Path.Path; |
| 658 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 659 | const kitGenerate = (schema: string, out: string, hints?: GenerateOptions["hints"]) => |
| 660 | Effect.promise(() => generate({ dialect: "postgresql", schema, out, hints })); |
| 661 | const rename = (source: string, to: string) => |
| 662 | source.replace('name: text("name")', `name: text("${to}")`); |
| 663 | const posts = `\nexport const posts = pgTable("posts", {\n id: serial("id").primaryKey(),\n});\n`; |
| 664 | |
| 665 | // Two branches off one base: one renames `name`, the other adds a table. |
| 666 | expect((yield* kitGenerate(ws.schemaPath, ws.out)).status).toEqual("ok"); |
| 667 | const branchOut = path.join(ws.root, "branch"); |
| 668 | yield* fs.copy(ws.out, branchOut); |
| 669 | const fullNamePath = path.join(ws.root, "schema-full-name.ts"); |
| 670 | yield* fs.writeFileString(fullNamePath, rename(SCHEMA_SOURCE, "full_name")); |
| 671 | const postsPath = path.join(ws.root, "schema-posts.ts"); |
| 672 | yield* fs.writeFileString(postsPath, SCHEMA_SOURCE + posts); |
| 673 | yield* Effect.sleep("1 second"); |
| 674 | const renamed = yield* kitGenerate(fullNamePath, ws.out, [ |
| 675 | { |
| 676 | type: "rename", |
| 677 | kind: "column", |
| 678 | from: ["public", "users", "name"], |
| 679 | to: ["public", "users", "full_name"], |
| 680 | }, |
| 681 | ]); |
| 682 | expect(renamed.status).toEqual("ok"); |
| 683 | expect((yield* kitGenerate(postsPath, branchOut)).status).toEqual("ok"); |
| 684 | const [, postsDir] = yield* readMigrationDirs(branchOut); |
| 685 | yield* fs.copy(path.join(branchOut, postsDir!), path.join(ws.out, postsDir!)); |
| 686 | |
| 687 | // Both branches merged, with `full_name` renamed again on top. |
| 688 | const displayNamePath = path.join(ws.root, "schema-display-name.ts"); |
| 689 | yield* fs.writeFileString(displayNamePath, rename(SCHEMA_SOURCE + posts, "display_name")); |
| 690 | yield* Effect.sleep("1 second"); |
| 691 | const asked: Array<string[]> = []; |
| 692 | const scripted = yield* scriptedSelect((options) => |
| 693 | Effect.sync(() => { |
| 694 | asked.push(options.options.map((option) => option.label)); |
| 695 | return options.options.at(-1)!.value; |
| 696 | }), |
| 697 | ); |
| 698 | yield* stack |
| 699 | .deploy(Drizzle.Schema("app-schema", { schema: displayNamePath, out: ws.out })) |
| 700 | .pipe(Effect.provideService(Interaction, scripted)); |
| 701 | |
| 702 | // `name` is gone in the combined state, so it is not offered. |
| 703 | expect(asked).toEqual([["+ users.display_name", "~ users.full_name › users.display_name"]]); |
| 704 | const dirs = yield* readMigrationDirs(ws.out); |
| 705 | expect(dirs).toHaveLength(4); |
| 706 | const sql = yield* fs.readFileString(path.join(ws.out, dirs[3]!, "migration.sql")); |
| 707 | expect(sql).toContain('RENAME COLUMN "full_name" TO "display_name"'); |
| 708 | expect(sql).not.toContain("DROP"); |
| 709 | }), |
| 710 | { tags: ["unit", "local"] }, |
| 711 | ); |
| 712 | |
| 713 | test.provider( |
| 714 | "an invalid schema fails the deploy instead of exiting the process", |
| 715 | (stack) => |
| 716 | Effect.gen(function* () { |
| 717 | const ws = yield* stageWorkspace( |
| 718 | SQLITE_SCHEMA_SOURCE.replace('name: text("name")', 'name: text("id")'), |
| 719 | ); |
| 720 | const exit = yield* Effect.sync(() => process.exit); |
| 721 | |
| 722 | const result = yield* Effect.result( |
| 723 | stack.deploy( |
| 724 | Drizzle.Schema("sqlite-schema", { |
| 725 | dialect: "sqlite", |
| 726 | schema: ws.schemaPath, |
| 727 | out: ws.out, |
| 728 | }), |
| 729 | ), |
| 730 | ); |
| 731 | |
| 732 | expect(Result.isFailure(result)).toBe(true); |
| 733 | if (Result.isFailure(result)) { |
| 734 | expect(String(result.failure)).toContain("found errors in the schema"); |
| 735 | } |
| 736 | expect(yield* Effect.sync(() => process.exit)).toBe(exit); |
| 737 | }), |
| 738 | { tags: ["unit", "local"] }, |
| 739 | ); |
| 740 | |
| 741 | test.provider( |
| 742 | "converts postgres snapshots written by earlier Alchemy versions", |
| 743 | (stack) => |
| 744 | Effect.gen(function* () { |
| 745 | const fs = yield* FileSystem.FileSystem; |
| 746 | const path = yield* Path.Path; |
| 747 | const ws = yield* stageWorkspace(SCHEMA_SOURCE); |
| 748 | |
| 749 | // Earlier versions wrote each snapshot as a full, untyped `ddl` dump. |
| 750 | const v1 = yield* Effect.promise(() => import(ws.schemaPath)); |
| 751 | const v2Path = path.join(ws.root, "schema-v2.ts"); |
| 752 | yield* fs.writeFileString(v2Path, DRIFTED_SCHEMA_SOURCE); |
| 753 | const v2 = yield* Effect.promise(() => import(v2Path)); |
| 754 | const s1 = yield* Effect.promise(() => PostgresKit.generateDrizzleJson(v1)); |
| 755 | const s2 = yield* Effect.promise(() => PostgresKit.generateDrizzleJson(v2, s1.id)); |
| 756 | for (const [dir, snapshot] of [ |
| 757 | ["20260101000000_migration", s1], |
| 758 | ["20260102000000_migration", s2], |
| 759 | ] as const) { |
| 760 | yield* fs.makeDirectory(path.join(ws.out, dir), { recursive: true }); |
| 761 | yield* fs.writeFileString(path.join(ws.out, dir, "migration.sql"), "-- applied\n"); |
| 762 | yield* fs.writeFileString( |
| 763 | path.join(ws.out, dir, "snapshot.json"), |
| 764 | JSON.stringify(snapshot, null, 2), |
| 765 | ); |
| 766 | } |
| 767 | |
| 768 | const v3Path = path.join(ws.root, "schema-v3.ts"); |
| 769 | yield* fs.writeFileString( |
| 770 | v3Path, |
| 771 | DRIFTED_SCHEMA_SOURCE + |
| 772 | `\nexport const tags = pgTable("tags", {\n id: serial("id").primaryKey(),\n});\n`, |
| 773 | ); |
| 774 | yield* stack.deploy(Drizzle.Schema("app-schema", { schema: v3Path, out: ws.out })); |
| 775 | |
| 776 | const dirs = yield* readMigrationDirs(ws.out); |
| 777 | expect(dirs).toHaveLength(3); |
| 778 | const decodeSnapshot = S.decodeEffect( |
| 779 | S.fromJsonString(S.Struct({ type: S.optional(S.String) })), |
| 780 | ); |
| 781 | const types = yield* Effect.forEach(dirs, (dir) => |
| 782 | fs.readFileString(path.join(ws.out, dir, "snapshot.json")).pipe( |
| 783 | Effect.flatMap(decodeSnapshot), |
| 784 | Effect.map((snapshot) => snapshot.type), |
| 785 | ), |
| 786 | ); |
| 787 | expect(types).toEqual(["base", "diff", "diff"]); |
| 788 | // Applied migrations are untouched; only the new one has SQL to run. |
| 789 | expect(yield* fs.readFileString(path.join(ws.out, dirs[1]!, "migration.sql"))).toEqual( |
| 790 | "-- applied\n", |
| 791 | ); |
| 792 | const sql = yield* fs.readFileString(path.join(ws.out, dirs[2]!, "migration.sql")); |
| 793 | expect(sql).toContain('CREATE TABLE "tags"'); |
| 794 | expect(sql).not.toContain('"posts"'); |
| 795 | expect( |
| 796 | (yield* Effect.promise(() => |
| 797 | generate({ dialect: "postgresql", schema: v3Path, out: ws.out }), |
| 798 | )).status, |
| 799 | ).toEqual("no_changes"); |
| 800 | }), |
| 801 | { tags: ["unit", "local"] }, |
| 802 | ); |
| 803 | |
| 804 | test.provider( |
| 805 | "migrations generated within the same second keep their own folders", |
| 806 | (stack) => |
| 807 | Effect.gen(function* () { |
| 808 | const fs = yield* FileSystem.FileSystem; |
| 809 | const path = yield* Path.Path; |
| 810 | const ws = yield* stageWorkspace(SQLITE_SCHEMA_SOURCE); |
| 811 | const driftedPath = path.join(ws.root, "schema-drifted.ts"); |
| 812 | yield* fs.writeFileString(driftedPath, SQLITE_DRIFTED_SCHEMA_SOURCE); |
| 813 | |
| 814 | yield* stack.deploy( |
| 815 | Drizzle.Schema("sqlite-schema", { dialect: "sqlite", schema: ws.schemaPath, out: ws.out }), |
| 816 | ); |
| 817 | yield* stack.deploy( |
| 818 | Drizzle.Schema("sqlite-schema", { dialect: "sqlite", schema: driftedPath, out: ws.out }), |
| 819 | ); |
| 820 | |
| 821 | const sql = yield* Effect.forEach(yield* readMigrationDirs(ws.out), (dir) => |
| 822 | fs.readFileString(path.join(ws.out, dir, "migration.sql")), |
| 823 | ); |
| 824 | expect(sql).toHaveLength(2); |
| 825 | expect(sql.some((statements) => statements.includes("CREATE TABLE `users`"))).toBe(true); |
| 826 | expect(sql.some((statements) => statements.includes("CREATE TABLE `posts`"))).toBe(true); |
| 827 | }), |
| 828 | { tags: ["unit", "local"] }, |
| 829 | ); |
| 830 | |
| 831 | test.provider( |
| 832 | "mysql schemas generate migrations programmatically", |
| 833 | (stack) => |
| 834 | Effect.gen(function* () { |
| 835 | const ws = yield* stageWorkspace(` |
| 836 | import { int, mysqlTable, varchar } from "drizzle-orm/mysql-core"; |
| 837 | |
| 838 | export const users = mysqlTable("users", { |
| 839 | id: int("id").primaryKey(), |
| 840 | name: varchar("name", { length: 255 }).notNull(), |
| 841 | }); |
| 842 | `); |
| 843 | |
| 844 | yield* stack.deploy( |
| 845 | Drizzle.Schema("mysql-schema", { dialect: "mysql", schema: ws.schemaPath, out: ws.out }), |
| 846 | ); |
| 847 | |
| 848 | const snapshots = yield* readSnapshots(ws.out); |
| 849 | expect(snapshots).toHaveLength(1); |
| 850 | expect(snapshots[0]?.prevIds).toEqual([DRIZZLE_ORIGIN_UUID]); |
| 851 | }), |
| 852 | { tags: ["unit", "local"] }, |
| 853 | ); |
| 854 | |
| 855 | test.provider( |
| 856 | "generates DSQL-compatible PostgreSQL SQL without a new dialect", |
| 857 | (stack) => |
| 858 | Effect.gen(function* () { |
| 859 | yield* stack.destroy(); |
| 860 | const { prepareDsqlStatements } = yield* Effect.promise( |
| 861 | // Internal to alchemy, so not exported. |
| 862 | () => import("@alchemy.run/aws/DSQL/MigrationSql"), |
| 863 | ); |
| 864 | const fs = yield* FileSystem.FileSystem; |
| 865 | const path = yield* Path.Path; |
| 866 | const ws = yield* stageWorkspace(` |
| 867 | import { pgTable, uuid, text, index } from "drizzle-orm/pg-core"; |
| 868 | export const users = pgTable("users", { |
| 869 | id: uuid("id").primaryKey(), email: text("email").notNull(), |
| 870 | }, (table) => [index("users_email_idx").on(table.email)]); |
| 871 | `); |
| 872 | yield* Effect.gen(function* () { |
| 873 | yield* stack.deploy( |
| 874 | Drizzle.Schema("Schema", { |
| 875 | schema: ws.schemaPath, |
| 876 | out: ws.out, |
| 877 | dialect: "postgres", |
| 878 | }), |
| 879 | ); |
| 880 | const dirs = yield* readMigrationDirs(ws.out); |
| 881 | expect(dirs).toHaveLength(1); |
| 882 | const sql = yield* fs.readFileString(path.join(ws.out, dirs[0], "migration.sql")); |
| 883 | expect(sql).toContain('"id" uuid PRIMARY KEY'); |
| 884 | const statements = yield* prepareDsqlStatements(sql, dirs[0]); |
| 885 | expect(statements).toHaveLength(2); |
| 886 | expect(statements[1]).toContain("INDEX ASYNC"); |
| 887 | }).pipe( |
| 888 | Effect.ensuring(stack.destroy().pipe(Effect.orDie)), |
| 889 | Effect.ensuring(fs.remove(ws.root, { recursive: true }).pipe(Effect.orDie)), |
| 890 | ); |
| 891 | }), |
| 892 | { tags: ["unit", "local"] }, |
| 893 | ); |