@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 04:45 UTC

main
ts 291 lines 10 KB
Raw
1 import { recordsEqual } from "alchemy/Util/equal";
2 import * as Effect from "effect/Effect";
3 import type * as FileSystem from "effect/FileSystem";
4 import type * as Path from "effect/Path";
5 import { hashMigrations } from "../SqlFile.ts";
6 import { ALCHEMY_DEFAULT_TABLE, applyAlchemyFormat } from "./AlchemyFormat.ts";
7 import {
8 MigrationError,
9 type DrizzleV0LayoutError,
10 type MigrationApplyError,
11 type SqlExecutor,
12 } from "./Format.ts";
13 import { readMigrationRecords } from "./Records.ts";
14
15 /**
16 * The migrations input surface shared by every SQL database resource.
17 * A plain string is a directory; the object form overrides the
18 * applied-migrations table name. A `Drizzle.Schema` resource's attributes
19 * satisfy the `{ out }` shape structurally, so `migrations: schema` works
20 * without importing the Drizzle module.
21 *
22 * There is exactly ONE bookkeeping format — Alchemy's `__alchemy_migrations`
23 * table. A database previously migrated with drizzle-kit, Prisma, or
24 * wrangler is adopted by a one-way conversion: the foreign table's history
25 * is copied into Alchemy's table once and the foreign table is left frozen
26 * (never written, never dropped). From then on Alchemy's table is the only
27 * bookkeeping.
28 */
29 export type MigrationsInput =
30 | string
31 | {
32 /** Directory containing the migration files. */
33 dir: string;
34 /** Override the applied-migrations table name. */
35 table?: string;
36 }
37 | {
38 /** A `Drizzle.Schema`-shaped resource output. */
39 out: string;
40 };
41
42 export interface NormalizedMigrationsInput {
43 dir: string;
44 table?: string;
45 }
46
47 export const normalizeMigrationsInput = (input: MigrationsInput): NormalizedMigrationsInput => {
48 if (typeof input === "string") return { dir: input };
49 if ("out" in input) return { dir: input.out };
50 return input;
51 };
52
53 /**
54 * Normalize a resource's `migrations` prop into the registry input shape.
55 * Shared by every SQL database resource.
56 */
57 export const migrationsInputOf = (props: {
58 migrations?: MigrationsInput;
59 }): NormalizedMigrationsInput | undefined =>
60 props.migrations ? normalizeMigrationsInput(props.migrations) : undefined;
61
62 /**
63 * What prior state remembers about migrations — the bookkeeping table a
64 * previous deploy used. Rows written by pre-registry Alchemy persisted
65 * their table name (`d1_migrations`, `neon_migrations`, custom names), and
66 * honoring it keeps them converging against the same table (upgraded in
67 * place to the current column shape) instead of starting a new one.
68 */
69 export interface StampedMigrationsState {
70 table?: string | undefined;
71 }
72
73 export const stampedOf = (
74 output: { migrationsTable: string | undefined } | undefined,
75 ): StampedMigrationsState => ({ table: output?.migrationsTable });
76
77 export interface ResolvedMigrations {
78 dir: string;
79 table: string;
80 }
81
82 /**
83 * Resolve where this deploy's bookkeeping lives. Precedence: explicit
84 * `table` on the input, then the table persisted by a prior deploy, then
85 * the default `__alchemy_migrations`.
86 */
87 export const resolveMigrations = (options: {
88 input: NormalizedMigrationsInput;
89 stamped: StampedMigrationsState;
90 }): ResolvedMigrations => ({
91 dir: options.input.dir,
92 table: options.input.table ?? options.stamped.table ?? ALCHEMY_DEFAULT_TABLE,
93 });
94
95 /**
96 * Apply pending migrations. The directory layout only selects how records
97 * are read and keyed (drizzle-kit/Prisma dirs by directory name, flat dirs
98 * by file path) — the bookkeeping is always Alchemy's table, converting
99 * foreign or legacy history on first contact (see `AlchemyFormat.ts`).
100 */
101 export const applyMigrations = (options: {
102 resolved: ResolvedMigrations;
103 executor: SqlExecutor;
104 }): Effect.Effect<
105 void,
106 MigrationApplyError | DrizzleV0LayoutError,
107 FileSystem.FileSystem | Path.Path
108 > =>
109 Effect.gen(function* () {
110 const { resolved, executor } = options;
111 const records = yield* readMigrationRecords(resolved.dir);
112 yield* applyAlchemyFormat({
113 executor,
114 table: resolved.table,
115 records,
116 });
117 });
118
119 const hashMigrationsDir = (dir: string) =>
120 hashMigrations(dir).pipe(
121 Effect.mapError(
122 (cause) =>
123 new MigrationError({
124 message: `Failed to read migrations from ${dir}: ${String(cause)}`,
125 cause,
126 }),
127 ),
128 );
129
130 /** The result of one migration sync, ready to stamp into attributes. */
131 export interface MigrationRun {
132 resolved: ResolvedMigrations;
133 hashes: Record<string, string>;
134 }
135
136 /**
137 * The whole per-deploy migration pipeline: hash the directory (for state
138 * drift tracking), resolve the bookkeeping table, and — when the directory
139 * is non-empty — apply pending migrations. The database provider supplies
140 * only `withExecutor`, a bracket that acquires its target's
141 * {@link SqlExecutor} (a D1 HTTP handle, a pg client over a Neon URI or
142 * PlanetScale temp role, a mysql2 connection) around the apply.
143 */
144 export const runMigrations = <E, R>(options: {
145 input: NormalizedMigrationsInput;
146 stamped: StampedMigrationsState;
147 withExecutor: (
148 apply: (
149 executor: SqlExecutor,
150 ) => Effect.Effect<
151 void,
152 MigrationApplyError | DrizzleV0LayoutError,
153 FileSystem.FileSystem | Path.Path
154 >,
155 ) => Effect.Effect<void, E, R>;
156 }): Effect.Effect<MigrationRun, MigrationError | E, R | FileSystem.FileSystem | Path.Path> =>
157 Effect.gen(function* () {
158 const hashes = yield* hashMigrationsDir(options.input.dir);
159 const resolved = resolveMigrations(options);
160 if (Object.keys(hashes).length > 0) {
161 yield* options.withExecutor((executor) => applyMigrations({ resolved, executor }));
162 }
163 return { resolved, hashes };
164 });
165
166 /**
167 * Prior migration files whose contents changed or that disappeared from
168 * the directory, relative to the hashes persisted on the last deploy.
169 * Additive files (new names) are not rewritten history.
170 */
171 export const rewrittenMigrationHistory = (
172 previous: Record<string, string> | undefined,
173 next: Record<string, string>,
174 ): { changed: string[]; removed: string[] } | undefined => {
175 if (previous === undefined) return undefined;
176 const changed: string[] = [];
177 const removed: string[] = [];
178 for (const name of Object.keys(previous)) {
179 const hash = next[name];
180 if (hash === undefined) removed.push(name);
181 else if (hash !== previous[name]) changed.push(name);
182 }
183 changed.sort();
184 removed.sort();
185 if (changed.length === 0 && removed.length === 0) return undefined;
186 return { changed, removed };
187 };
188
189 export type MigrationHistoryChange =
190 | { readonly kind: "none" }
191 | { readonly kind: "pending" }
192 | {
193 readonly kind: "rewritten";
194 readonly changed: ReadonlyArray<string>;
195 readonly removed: ReadonlyArray<string>;
196 };
197
198 /**
199 * Classify the migration half of a provider `diff`:
200 * - `none` — hashes and bookkeeping table are unchanged
201 * - `pending` — new files and/or a table rename; apply in place
202 * - `rewritten` — an already-applied file was edited or removed
203 */
204 export const classifyMigrationHistory = (options: {
205 news: { migrations?: MigrationsInput };
206 output:
207 | {
208 migrationsTable: string | undefined;
209 migrationsHashes: Record<string, string>;
210 }
211 | undefined;
212 }): Effect.Effect<MigrationHistoryChange, MigrationError, FileSystem.FileSystem | Path.Path> =>
213 Effect.gen(function* () {
214 const input = migrationsInputOf(options.news);
215 if (!input) return { kind: "none" } as const;
216 const newHashes = yield* hashMigrationsDir(input.dir);
217 const rewritten = rewrittenMigrationHistory(options.output?.migrationsHashes, newHashes);
218 if (rewritten) {
219 return { kind: "rewritten", ...rewritten } as const;
220 }
221 if (!recordsEqual(newHashes, options.output?.migrationsHashes ?? {})) {
222 return { kind: "pending" } as const;
223 }
224 const resolved = resolveMigrations({
225 input,
226 stamped: stampedOf(options.output),
227 });
228 return resolved.table !== (options.output?.migrationsTable ?? resolved.table)
229 ? ({ kind: "pending" } as const)
230 : ({ kind: "none" } as const);
231 });
232
233 /**
234 * The shared migration half of a provider `diff`: true when pending file
235 * changes, rewritten history, or a bookkeeping-table move require an
236 * action. Callers that can replace (PlanetScale development branches)
237 * should consult {@link classifyMigrationHistory} instead of this boolean.
238 */
239 export const diffMigrations = (options: {
240 news: { migrations?: MigrationsInput };
241 output:
242 | {
243 migrationsTable: string | undefined;
244 migrationsHashes: Record<string, string>;
245 }
246 | undefined;
247 }): Effect.Effect<boolean, MigrationError, FileSystem.FileSystem | Path.Path> =>
248 classifyMigrationHistory(options).pipe(Effect.map((change) => change.kind !== "none"));
249
250 /** The attributes every SQL database resource with `migrations` exposes. */
251 export interface MigrationAttributes {
252 /** Directory of the applied SQL migrations. */
253 migrationsDir: string | undefined;
254 /** Migration bookkeeping table. */
255 migrationsTable: string | undefined;
256 /** Applied migration content hashes. */
257 migrationsHashes: Record<string, string>;
258 }
259
260 /**
261 * Carry migration attributes from prior state (`read`, `list`), defaulting
262 * to none recorded.
263 */
264 export const migrationAttributesOf = (
265 prior: Partial<MigrationAttributes> | undefined,
266 ): MigrationAttributes => ({
267 migrationsDir: prior?.migrationsDir,
268 migrationsTable: prior?.migrationsTable,
269 migrationsHashes: prior?.migrationsHashes ?? {},
270 });
271
272 /**
273 * The migration attributes every SQL database resource persists, threaded
274 * uniformly: the run's results when migrations ran, otherwise the prior
275 * state (so removing `migrations` keeps the stamp and hashes for a later
276 * re-add).
277 */
278 export const migrationsAttrs = (options: {
279 input: NormalizedMigrationsInput | undefined;
280 run: MigrationRun | undefined;
281 output:
282 | {
283 migrationsTable: string | undefined;
284 migrationsHashes: Record<string, string>;
285 }
286 | undefined;
287 }): MigrationAttributes => ({
288 migrationsDir: options.input?.dir,
289 migrationsTable: options.run?.resolved.table ?? options.output?.migrationsTable,
290 migrationsHashes: options.run?.hashes ?? options.output?.migrationsHashes ?? {},
291 });