@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 233 lines 9.17 KB
Raw
1 import * as Effect from "effect/Effect";
2 import {
3 MigrationError,
4 MigrationHistoryConflictError,
5 type MigrationRecord,
6 type SqlExecutor,
7 } from "./Format.ts";
8 import { classifyTable, tableColumns } from "./Introspect.ts";
9 import {
10 bookkeepingColumns,
11 quoteIdentifier,
12 scalarText,
13 sqlLiteral,
14 timestampPrefixMillis,
15 } from "./Utils.ts";
16
17 /**
18 * A row of applied history harvested from a foreign migration tool's table,
19 * normalized for insertion into `__alchemy_migrations`.
20 */
21 export interface ConvertedRow {
22 name: string;
23 hash: string | undefined;
24 createdAtMillis: number | undefined;
25 appliedAt: string | undefined;
26 }
27
28 export interface ForeignHistory {
29 /** Which tool's bookkeeping this history came from. */
30 tool: "drizzle" | "prisma" | "wrangler" | "legacy-alchemy";
31 /** Display name of the source table (schema-qualified where relevant). */
32 source: string;
33 rows: ConvertedRow[];
34 }
35
36 /**
37 * Normalize a timestamp-ish column value for re-insertion as a SQL
38 * literal. Drivers differ: pg hands back JS Dates (whose default
39 * stringification pg itself cannot parse — "GMT-0700 (…)"), sqlite hands
40 * back strings.
41 */
42 export const toTimestampString = (value: unknown): string | undefined =>
43 value === null || value === undefined
44 ? undefined
45 : value instanceof Date
46 ? value.toISOString()
47 : scalarText(value);
48
49 const qualify = (table: string, dialect: SqlExecutor["dialect"], schema?: string) =>
50 schema
51 ? `${quoteIdentifier(schema, dialect)}.${quoteIdentifier(table, dialect)}`
52 : quoteIdentifier(table, dialect);
53
54 /**
55 * Discover applied-migration history left behind by the tool a user is
56 * migrating FROM — drizzle-kit, Prisma, or wrangler — so it can be copied
57 * into Alchemy's own table once. This is a ONE-WAY migration: the foreign
58 * table is read but never written or dropped (it is simply frozen), and
59 * from that point on Alchemy's table is the only bookkeeping.
60 *
61 * Sources probed, most-specific first:
62 * - drizzle: `__drizzle_migrations` (in the `drizzle` schema on Postgres) —
63 * drizzle's columns are Alchemy's columns, so rows copy verbatim.
64 * - prisma: `_prisma_migrations` — `migration_name`/`checksum` map to
65 * `name`/`hash` (both are sha256 of `migration.sql`). A failed migration
66 * (`finished_at IS NULL`, not rolled back) aborts the conversion: it must
67 * be repaired with `prisma migrate resolve` first. Rolled-back rows are
68 * skipped.
69 * - wrangler (sqlite): `d1_migrations` in wrangler's shape — names carry
70 * over; hashes backfill from local records.
71 */
72 export const findForeignHistory = (options: {
73 executor: SqlExecutor;
74 /** The resolved Alchemy table — a source with this name is not foreign. */
75 table: string;
76 }): Effect.Effect<ForeignHistory | undefined, MigrationError> =>
77 Effect.gen(function* () {
78 const { executor, table } = options;
79 const dialect = executor.dialect;
80
81 // drizzle
82 const drizzleSchema = dialect === "postgres" ? "drizzle" : undefined;
83 if (table !== "__drizzle_migrations") {
84 const columns = yield* tableColumns(executor, "__drizzle_migrations", drizzleSchema);
85 if (classifyTable(columns) === "drizzle-shaped") {
86 const rows = yield* executor.query(
87 `SELECT hash, created_at, name, applied_at FROM ${qualify("__drizzle_migrations", dialect, drizzleSchema)} ORDER BY id;`,
88 );
89 return {
90 tool: "drizzle" as const,
91 source: drizzleSchema ? `${drizzleSchema}.__drizzle_migrations` : "__drizzle_migrations",
92 rows: rows
93 .filter((row) => row.name !== null && row.name !== undefined)
94 .map((row) => ({
95 name: String(row.name),
96 hash: row.hash === null || row.hash === undefined ? undefined : scalarText(row.hash),
97 createdAtMillis:
98 row.created_at === null || row.created_at === undefined
99 ? undefined
100 : Number(row.created_at),
101 appliedAt: toTimestampString(row.applied_at),
102 })),
103 };
104 }
105 }
106
107 // prisma
108 if (table !== "_prisma_migrations") {
109 const columns = yield* tableColumns(executor, "_prisma_migrations");
110 const names = new Set(columns.map((c) => c.name));
111 if (names.has("migration_name") && names.has("checksum")) {
112 const rows = yield* executor.query(
113 `SELECT migration_name, checksum, started_at, finished_at, rolled_back_at FROM ${quoteIdentifier("_prisma_migrations", dialect)};`,
114 );
115 const failed = rows.filter(
116 (row) =>
117 (row.finished_at === null || row.finished_at === undefined) &&
118 (row.rolled_back_at === null || row.rolled_back_at === undefined),
119 );
120 if (failed.length > 0) {
121 return yield* new MigrationError({
122 message:
123 `_prisma_migrations records ${failed.length} failed migration(s) ` +
124 `(${failed.map((r) => String(r.migration_name)).join(", ")}). ` +
125 `Repair them with "prisma migrate resolve" before migrating this ` +
126 `database's bookkeeping to Alchemy.`,
127 });
128 }
129 return {
130 tool: "prisma" as const,
131 source: "_prisma_migrations",
132 rows: rows
133 .filter(
134 (row) =>
135 row.finished_at !== null &&
136 row.finished_at !== undefined &&
137 (row.rolled_back_at === null || row.rolled_back_at === undefined),
138 )
139 .map((row) => ({
140 name: String(row.migration_name),
141 hash:
142 row.checksum === null || row.checksum === undefined
143 ? undefined
144 : scalarText(row.checksum),
145 createdAtMillis: timestampPrefixMillis(String(row.migration_name)),
146 appliedAt: toTimestampString(row.finished_at),
147 })),
148 };
149 }
150 }
151
152 // wrangler / pre-registry Alchemy on D1 (which shared the
153 // d1_migrations name — covers state-lost adoption of old deploys)
154 if (dialect === "sqlite" && table !== "d1_migrations") {
155 const shape = classifyTable(yield* tableColumns(executor, "d1_migrations"));
156 if (shape === "wrangler" || shape === "legacy-alchemy" || shape === "legacy-2col") {
157 const nameExpr = shape === "legacy-2col" ? "id" : "name";
158 const rows = yield* executor.query(
159 `SELECT ${nameExpr} AS name, applied_at FROM ${quoteIdentifier("d1_migrations", dialect)} ORDER BY id;`,
160 );
161 return {
162 tool: shape === "wrangler" ? ("wrangler" as const) : ("legacy-alchemy" as const),
163 source: "d1_migrations",
164 rows: rows
165 .filter((row) => row.name !== null && row.name !== undefined)
166 .map((row) => ({
167 name: String(row.name),
168 hash: undefined,
169 createdAtMillis: timestampPrefixMillis(String(row.name)),
170 appliedAt: toTimestampString(row.applied_at),
171 })),
172 };
173 }
174 }
175
176 return undefined;
177 });
178
179 /**
180 * Validate foreign history against the local migrations directory and fill
181 * in missing hashes. Every foreign row must match a local record by name
182 * (or by the `<dir>/migration.sql` ⇄ `<dir>` aliasing between flat and
183 * directory layouts) — an unmatched row means migrations were applied that
184 * this checkout does not have.
185 */
186 export const matchForeignRows = (options: {
187 history: ForeignHistory;
188 records: ReadonlyArray<MigrationRecord>;
189 }): Effect.Effect<ConvertedRow[], MigrationHistoryConflictError> =>
190 Effect.gen(function* () {
191 const { history, records } = options;
192 const byName = new Map(records.map((r) => [r.name, r]));
193 const byAlias = new Map(
194 records.flatMap((r) => [
195 [`${r.name}/migration.sql`, r] as const,
196 [r.name.replace(/\/migration\.sql$/, ""), r] as const,
197 ]),
198 );
199 const matched: ConvertedRow[] = [];
200 const unmatched: string[] = [];
201 for (const row of history.rows) {
202 const record = byName.get(row.name) ?? byAlias.get(row.name);
203 if (!record) {
204 unmatched.push(row.name);
205 continue;
206 }
207 matched.push({
208 ...row,
209 hash: row.hash ?? record.hash,
210 createdAtMillis: row.createdAtMillis ?? record.createdAtMillis,
211 });
212 }
213 if (unmatched.length > 0) {
214 return yield* new MigrationHistoryConflictError({
215 table: history.source,
216 unmatched,
217 message:
218 `While migrating ${history.tool} bookkeeping (${history.source}) to ` +
219 `Alchemy, ${unmatched.length} recorded migration(s) match no local ` +
220 `file: ${unmatched.join(", ")}. Migrations were applied to this ` +
221 `database that are missing from the local environment.`,
222 });
223 }
224 return matched;
225 });
226
227 /** Render an INSERT for a converted history row into Alchemy's table. */
228 export const convertedRowInsertSql = (
229 table: string,
230 dialect: SqlExecutor["dialect"],
231 row: ConvertedRow,
232 ): string =>
233 `INSERT INTO ${quoteIdentifier(table, dialect)} (${bookkeepingColumns(dialect, "hash", "created_at", "name", "applied_at")}) VALUES (${sqlLiteral(row.hash ?? "", dialect)}, ${sqlLiteral(row.createdAtMillis ?? null, dialect)}, ${sqlLiteral(row.name, dialect)}, ${sqlLiteral(row.appliedAt ?? null, dialect)});`;