The best way to control Claude Code, Codex and more from any computer or phone

main
ts 160 lines 6.67 KB
Raw
1 import {
2 MigrationError,
3 readMigrationRecords,
4 scanSqlScript,
5 type NormalizedMigrationsInput,
6 } from "@alchemy.run/sql/Migrations";
7 import { hashMigrations } from "@alchemy.run/sql/SqlFile";
8 import * as Effect from "effect/Effect";
9
10 /**
11 * Split a PostgreSQL script without splitting quoted values, identifiers,
12 * dollar-quoted bodies, or nested comments. Each statement's `code` masks
13 * literals and comments at the same offsets as its `sql`, hiding them from
14 * capability checks.
15 */
16 export const parseDsqlStatements = (sql: string) =>
17 scanSqlScript(sql, "postgres").map((statement) => {
18 if (statement.unterminated) {
19 throw new Error(`Unterminated SQL ${statement.unterminated}`);
20 }
21 return { sql: statement.sql, code: statement.code };
22 });
23
24 /** Validate known DSQL incompatibilities; this is not a full SQL parser. */
25 export const prepareDsqlStatements = (sql: string, migration: string) =>
26 Effect.try({
27 try: () =>
28 parseDsqlStatements(sql).map((statement) => {
29 const code = statement.code;
30 let reason: string | undefined;
31 if (
32 /^\s*(BEGIN|COMMIT|END|ROLLBACK|ABORT|SAVEPOINT|RELEASE|START\s+TRANSACTION|PREPARE\s+TRANSACTION|SET\s+(?:LOCAL\s+|SESSION\s+)?(?:TRANSACTION|CHARACTERISTICS))\b/i.test(
33 code,
34 )
35 ) {
36 reason =
37 "Transaction control is managed by Alchemy; DSQL permits one DDL statement per transaction and cannot combine DDL with bookkeeping.";
38 } else if (
39 /^\s*(?:CREATE|ALTER)\s+TABLE\b/i.test(code) &&
40 /[\w$]+\s+(?:smallserial|serial|bigserial|serial2|serial4|serial8)\b/i.test(code)
41 ) {
42 reason =
43 "Use a UUID primary key or a bigint identity with an explicit CACHE instead of serial.";
44 } else if (/^\s*CREATE\s+SEQUENCE\b/i.test(code) || /\bAS\s+IDENTITY\b/i.test(code)) {
45 const definitions = /^\s*CREATE\s+SEQUENCE\b/i.test(code)
46 ? [code]
47 : [...code.matchAll(/\bAS\s+IDENTITY\b(?:\s*\(([^)]*)\))?/gi)].map(
48 (match) => match[1] ?? "",
49 );
50 if (
51 definitions.some((definition) => {
52 const cache = /\bCACHE\s+(\d+)\b/i.exec(definition)?.[1];
53 return cache === undefined || (Number(cache) !== 1 && Number(cache) < 65536);
54 })
55 ) {
56 reason =
57 "DSQL sequences and identity columns require an explicit CACHE of 1 or at least 65536.";
58 }
59 }
60 if (
61 /^\s*ALTER\s+TABLE\b/i.test(code) &&
62 /\bADD\s+(?!CONSTRAINT\b)(?:COLUMN\s+)?/i.test(code) &&
63 /\b(?:DEFAULT|NOT\s+NULL|UNIQUE|CHECK|PRIMARY\s+KEY|REFERENCES|GENERATED)\b/i.test(code)
64 ) {
65 reason =
66 "DSQL cannot add a column with a constraint or default. Add the column bare, then backfill it in a later statement.";
67 }
68 if (/^\s*(?:SET|RESET)\b/i.test(code)) {
69 reason =
70 "Session settings cannot be changed inside DSQL migration files. Qualify table names with their schema instead of changing search_path.";
71 }
72 const index = /^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\b/i.exec(code);
73 if (index && /\bCONCURRENTLY\b/i.test(code)) {
74 reason = "Use CREATE INDEX ASYNC instead of CONCURRENTLY on DSQL.";
75 }
76 if (reason)
77 throw new Error(
78 `Unsupported DSQL migration ${migration}: ${reason}\nStatement:\n${statement.sql.trim()}`,
79 );
80 let prepared = statement.sql;
81 // Drizzle emits ordinary PostgreSQL CREATE INDEX ... USING btree.
82 // DSQL's equivalent is CREATE INDEX ASYNC without the access method.
83 if (index) {
84 const using = /\bUSING\s+btree\b/i.exec(code);
85 if (using)
86 prepared =
87 prepared.slice(0, using.index) + prepared.slice(using.index + using[0].length);
88 if (!/^\s*ASYNC\b/i.test(code.slice(index[0].length))) {
89 prepared =
90 prepared.slice(0, index[0].length) + " ASYNC" + prepared.slice(index[0].length);
91 }
92 }
93 return prepared.trim();
94 }),
95 catch: (cause) =>
96 new MigrationError({
97 message: `DSQL migration ${migration}: ${cause instanceof Error ? cause.message : String(cause)}`,
98 cause,
99 }),
100 });
101
102 /** Run before cluster mutation, and during diff when the directory resolves. */
103 export const validateDsqlMigrations = (
104 input: NormalizedMigrationsInput,
105 appliedHashes: Record<string, string> = {},
106 ) =>
107 Effect.gen(function* () {
108 const hashes = yield* hashMigrations(input.dir).pipe(
109 Effect.mapError(
110 (cause) =>
111 new MigrationError({
112 message: `Failed to read DSQL migrations from ${input.dir}`,
113 cause,
114 }),
115 ),
116 );
117 for (const [name, expected] of Object.entries(appliedHashes)) {
118 if (hashes[name] !== expected) {
119 return yield* new MigrationError({
120 message: `Migration ${name} has changed since the last successful deploy. Expected SHA256: ${expected}; actual SHA256: ${hashes[name] ?? "file missing"}. Restore it and create a new migration instead.`,
121 });
122 }
123 }
124 const records = yield* readMigrationRecords(input.dir);
125 for (const record of records) {
126 yield* prepareDsqlStatements(record.sql, record.name);
127 }
128 });
129
130 /** Resolve a named index's table for checking an IF NOT EXISTS no-op. */
131 export const dsqlIndexTarget = (sql: string) => {
132 const statement = parseDsqlStatements(sql)[0];
133 if (!statement) return undefined;
134 const prefix = /^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+ASYNC\s+(?:IF\s+NOT\s+EXISTS\s+)?/i.exec(
135 statement.code,
136 );
137 if (!prefix) return undefined;
138 const identifier = /^(?:"(?:[^"]|"")*"|[A-Za-z_][A-Za-z_0-9$]*)/;
139 const name = identifier.exec(statement.sql.slice(prefix[0].length))?.[0];
140 if (!name) return undefined;
141 const afterName = prefix[0].length + name.length;
142 const on = /^\s+ON\s+(?:ONLY\s+)?/i.exec(statement.code.slice(afterName));
143 if (!on) return undefined;
144 const tableStart = afterName + on[0].length;
145 let table = identifier.exec(statement.sql.slice(tableStart))?.[0];
146 if (!table) return undefined;
147 const dot = /^\s*\.\s*/.exec(statement.code.slice(tableStart + table.length));
148 if (dot) {
149 const next = identifier.exec(
150 statement.sql.slice(tableStart + table.length + dot[0].length),
151 )?.[0];
152 if (!next) return undefined;
153 table = `${table}${statement.sql.slice(tableStart + table.length, tableStart + table.length + dot[0].length)}${next}`;
154 }
155 if (!/^\s*\(/.test(statement.code.slice(tableStart + table.length))) return undefined;
156 return {
157 name: name.startsWith('"') ? name.slice(1, -1).replaceAll('""', '"') : name.toLowerCase(),
158 table,
159 };
160 };