Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MySQLMigrations.ts

133 lines3.9 KB

1import {
2 runMigrations,
3 withMySqlExecutor,
4 type NormalizedMigrationsInput,
5 type SqlExecutor,
6 type StampedMigrationsState,
7} from "@alchemy.run/sql/Migrations";
8import { applySqlImports, splitSqlStatements } from "@alchemy.run/sql/SqlFile";
9import * as ps from "@distilled.cloud/planetscale";
10import * as Effect from "effect/Effect";
11import * as Redacted from "effect/Redacted";
12import * as Schedule from "effect/Schedule";
13​
14const MIGRATION_PASSWORD_TTL_SECONDS = 600;
15​
16export interface MySQLMigrationTarget {
17 organization: string;
18 database: string;
19 branch: string;
21​
22/**
23 * PlanetScale MySQL's migration adaptation is exactly this: the shared
24 * pipeline with a temp-password-scoped mysql2 connection as its executor.
25 */
26export const runMySQLMigrations = (
27 target: MySQLMigrationTarget,
28 input: NormalizedMigrationsInput,
29 stamped: StampedMigrationsState,
30) =>
31 runMigrations({
32 input,
33 stamped,
34 withExecutor: (apply) => withMySQLExecutor(target, apply),
35 });
36​
37/**
38 * Apply `importFiles`, each once and again only when it changes. Vitess
39 * rejects drizzle-kit's `--> statement-breakpoint` markers, so statements
40 * run one at a time.
41 */
42export const runMySQLImports = (
43 target: MySQLMigrationTarget,
44 importFiles: ReadonlyArray<string>,
45 rootDir: string,
46 previous: Record<string, string>,
47) =>
48 applySqlImports({
49 importFiles,
50 rootDir,
51 previous,
52 apply: (file) =>
53 withMySQLExecutor(target, (executor) =>
54 Effect.forEach(splitSqlStatements(file.sql), (statement) => executor.query(statement), {
55 discard: true,
56 }),
57 ),
58 });
59​
60/** A verified-TLS `mysql2` session as a short-lived admin password. */
61const withMySQLExecutor = <A, E, R>(
62 target: MySQLMigrationTarget,
63 use: (executor: SqlExecutor) => Effect.Effect<A, E, R>,
64) =>
65 withTemporaryMySQLPassword(target, (password) =>
66 withMySqlExecutor(
67 {
68 host: password.host,
69 user: password.username,
70 password: Redacted.value(password.password),
71 database: target.database,
72 multipleStatements: true,
73 ssl: { rejectUnauthorized: true },
74 },
75 use,
76 ),
77 );
78​
79const withTemporaryMySQLPassword = <A, E, R>(
80 target: MySQLMigrationTarget,
81 use: (password: {
82 id: string;
83 host: string;
84 username: string;
85 password: Redacted.Redacted<string>;
86 }) => Effect.Effect<A, E, R>,
87) =>
88 Effect.acquireUseRelease(
89 Effect.gen(function* () {
90 const created = yield* ps.createPassword({
91 organization: target.organization,
92 database: target.database,
93 branch: target.branch,
94 role: "admin",
95 ttl: MIGRATION_PASSWORD_TTL_SECONDS,
96 });
97​
98 return {
99 id: created.id,
100 host: created.access_host_url,
101 username: created.username,
102 password: created.plain_text,
103 };
104 }),
105 use,
106 (password) =>
107 ps
108 .deletePassword({
109 organization: target.organization,
110 database: target.database,
111 branch: target.branch,
112 id: password.id,
113 })
114 .pipe(
115 // Already-deleted passwords are a success: nothing to clean up.
116 Effect.catchTag("NotFound", () => Effect.void),
117 Effect.retry({
118 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(5)]),
119 }),
120 // Migrations succeeded; don't fail the parent over a release-step
121 // hiccup. The password's TTL bounds the orphan window; log loudly
122 // so an operator can clean it up manually if needed.
123 Effect.catch((cause: unknown) =>
124 Effect.logWarning(
125 `Failed to delete temporary Planetscale migration password after retries. ` +
126 `It will expire via TTL (~${MIGRATION_PASSWORD_TTL_SECONDS}s). ` +
127 `organization=${target.organization} database=${target.database} ` +
128 `branch=${target.branch} id=${password.id}`,
129 cause,
130 ),
131 ),
132 ),
133 );