@subodh001/pg-safe-migrate 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ALL-MILESTONES-TESTING.md +41 -0
- package/README.md +94 -11
- package/bin/cli.js +49 -2
- package/examples/baseline.sql +7 -0
- package/examples/consumer-workflow.yml +35 -0
- package/examples/migrations/001_add_phone.sql +1 -0
- package/examples/migrations/002_add_email_index.sql +1 -0
- package/examples/safe.sql +2 -0
- package/examples/team-policy.json +7 -0
- package/examples/test-unsafe.sql +1 -0
- package/examples/unsafe.sql +2 -0
- package/examples/verify.sql +8 -0
- package/package.json +12 -3
- package/scripts/orm-runner/README.md +35 -0
- package/scripts/orm-runner/package-lock.json +659 -0
- package/scripts/orm-runner/package.json +14 -0
- package/scripts/orm-runner/verify.mjs +360 -0
- package/scripts/test-pg-matrix.cjs +30 -0
- package/src/analysis.js +8 -6
- package/src/combined.js +60 -0
- package/src/db-inspect.js +30 -0
- package/src/github.js +17 -0
- package/src/locks.js +8 -0
- package/src/plans.js +9 -0
- package/src/presets.js +5 -0
- package/src/risk.js +5 -0
- package/src/simulator.js +115 -0
- package/src/team-policy.js +23 -0
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import pg from 'pg';
|
|
8
|
+
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
9
|
+
import { migrate } from 'drizzle-orm/node-postgres/migrator';
|
|
10
|
+
|
|
11
|
+
const url = process.env.DATABASE_URL;
|
|
12
|
+
|
|
13
|
+
if (!url) {
|
|
14
|
+
throw new Error(
|
|
15
|
+
'Set DATABASE_URL to a disposable PostgreSQL database.'
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const runnerDir = path.dirname(fileURLToPath(import.meta.url));
|
|
20
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pg-safe-orm-'));
|
|
21
|
+
|
|
22
|
+
const prismaSchema = `orm_test_prisma_${process.pid}`;
|
|
23
|
+
const drizzleSchema = `orm_test_drizzle_${process.pid}`;
|
|
24
|
+
|
|
25
|
+
const quote = (value) =>
|
|
26
|
+
'"' + value.replaceAll('"', '""') + '"';
|
|
27
|
+
|
|
28
|
+
const pool = new pg.Pool({
|
|
29
|
+
connectionString: url
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
function exec(command, args, env) {
|
|
33
|
+
const result = spawnSync(command, args, {
|
|
34
|
+
cwd: root,
|
|
35
|
+
env,
|
|
36
|
+
stdio: 'inherit',
|
|
37
|
+
shell: false
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
if (result.error) {
|
|
41
|
+
throw result.error;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (result.status !== 0) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`${command} failed with exit code ${result.status}`
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function cleanupTemporaryDirectory() {
|
|
52
|
+
try {
|
|
53
|
+
fs.rmSync(root, {
|
|
54
|
+
recursive: true,
|
|
55
|
+
force: true,
|
|
56
|
+
maxRetries: 10,
|
|
57
|
+
retryDelay: 500
|
|
58
|
+
});
|
|
59
|
+
} catch (error) {
|
|
60
|
+
console.warn(
|
|
61
|
+
`Warning: Could not remove temporary directory: ${root}`
|
|
62
|
+
);
|
|
63
|
+
console.warn(error.message);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function verify() {
|
|
68
|
+
let prismaSchemaCreated = false;
|
|
69
|
+
let drizzleSchemaCreated = false;
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
// 1. Create isolated test schemas.
|
|
73
|
+
await pool.query(
|
|
74
|
+
`CREATE SCHEMA ${quote(prismaSchema)}`
|
|
75
|
+
);
|
|
76
|
+
prismaSchemaCreated = true;
|
|
77
|
+
|
|
78
|
+
await pool.query(
|
|
79
|
+
`CREATE SCHEMA ${quote(drizzleSchema)}`
|
|
80
|
+
);
|
|
81
|
+
drizzleSchemaCreated = true;
|
|
82
|
+
|
|
83
|
+
// 2. Prepare Prisma migrations.
|
|
84
|
+
const prismaUrl = new URL(url);
|
|
85
|
+
prismaUrl.searchParams.set('schema', prismaSchema);
|
|
86
|
+
|
|
87
|
+
const prismaDir = path.join(root, 'prisma');
|
|
88
|
+
const prismaMigrationsDir = path.join(
|
|
89
|
+
prismaDir,
|
|
90
|
+
'migrations'
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
const prismaMigrationDir = path.join(
|
|
94
|
+
prismaMigrationsDir,
|
|
95
|
+
'202611170001_baseline'
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
fs.mkdirSync(prismaMigrationDir, {
|
|
99
|
+
recursive: true
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const prismaSchemaFile = path.join(
|
|
103
|
+
prismaDir,
|
|
104
|
+
'schema.prisma'
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
fs.writeFileSync(
|
|
108
|
+
prismaSchemaFile,
|
|
109
|
+
`datasource db {
|
|
110
|
+
provider = "postgresql"
|
|
111
|
+
url = env("DATABASE_URL")
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
generator client {
|
|
115
|
+
provider = "prisma-client-js"
|
|
116
|
+
}
|
|
117
|
+
`
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
fs.writeFileSync(
|
|
121
|
+
path.join(
|
|
122
|
+
prismaMigrationsDir,
|
|
123
|
+
'migration_lock.toml'
|
|
124
|
+
),
|
|
125
|
+
'provider = "postgresql"\n'
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
// Prisma migration 1: create the table.
|
|
129
|
+
fs.writeFileSync(
|
|
130
|
+
path.join(prismaMigrationDir, 'migration.sql'),
|
|
131
|
+
`CREATE TABLE orm_prisma_users (
|
|
132
|
+
id bigint PRIMARY KEY,
|
|
133
|
+
email text
|
|
134
|
+
);
|
|
135
|
+
`
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
// Prisma migration 2: create the index separately.
|
|
139
|
+
const prismaIndexMigrationDir = path.join(
|
|
140
|
+
prismaMigrationsDir,
|
|
141
|
+
'202611170002_concurrent_index'
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
fs.mkdirSync(prismaIndexMigrationDir, {
|
|
145
|
+
recursive: true
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
fs.writeFileSync(
|
|
149
|
+
path.join(prismaIndexMigrationDir, 'migration.sql'),
|
|
150
|
+
`CREATE INDEX CONCURRENTLY orm_prisma_users_email_idx
|
|
151
|
+
ON orm_prisma_users (email);
|
|
152
|
+
`
|
|
153
|
+
);
|
|
154
|
+
|
|
155
|
+
// 3. Run the actual Prisma CLI using Node.js.
|
|
156
|
+
const prismaCli = path.join(
|
|
157
|
+
runnerDir,
|
|
158
|
+
'node_modules',
|
|
159
|
+
'prisma',
|
|
160
|
+
'build',
|
|
161
|
+
'index.js'
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
if (!fs.existsSync(prismaCli)) {
|
|
165
|
+
throw new Error(
|
|
166
|
+
`Prisma CLI not found: ${prismaCli}. Run npm install in scripts/orm-runner.`
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
console.log('\nRunning Prisma migrate deploy...');
|
|
171
|
+
|
|
172
|
+
exec(
|
|
173
|
+
process.execPath,
|
|
174
|
+
[
|
|
175
|
+
prismaCli,
|
|
176
|
+
'migrate',
|
|
177
|
+
'deploy',
|
|
178
|
+
'--schema',
|
|
179
|
+
prismaSchemaFile
|
|
180
|
+
],
|
|
181
|
+
{
|
|
182
|
+
...process.env,
|
|
183
|
+
DATABASE_URL: prismaUrl.toString()
|
|
184
|
+
}
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
// 4. Verify Prisma table and concurrent index.
|
|
188
|
+
const prismaResult = await pool.query(
|
|
189
|
+
'SELECT to_regclass($1) AS name',
|
|
190
|
+
[`${prismaSchema}.orm_prisma_users`]
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
if (!prismaResult.rows[0].name) {
|
|
194
|
+
throw new Error(
|
|
195
|
+
'Prisma migration did not create its table.'
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
console.log('PASS: Prisma baseline migration.');
|
|
200
|
+
|
|
201
|
+
const prismaIndex = await pool.query(
|
|
202
|
+
'SELECT to_regclass($1) AS name',
|
|
203
|
+
[`${prismaSchema}.orm_prisma_users_email_idx`]
|
|
204
|
+
);
|
|
205
|
+
|
|
206
|
+
if (!prismaIndex.rows[0].name) {
|
|
207
|
+
throw new Error(
|
|
208
|
+
'Prisma concurrent index was not created.'
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
console.log('PASS: Prisma concurrent index created.');
|
|
213
|
+
|
|
214
|
+
// 5. Prepare Drizzle migration.
|
|
215
|
+
const drizzleFolder = path.join(root, 'drizzle');
|
|
216
|
+
const drizzleMetaFolder = path.join(
|
|
217
|
+
drizzleFolder,
|
|
218
|
+
'meta'
|
|
219
|
+
);
|
|
220
|
+
|
|
221
|
+
fs.mkdirSync(drizzleMetaFolder, {
|
|
222
|
+
recursive: true
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
fs.writeFileSync(
|
|
226
|
+
path.join(drizzleFolder, '0000_baseline.sql'),
|
|
227
|
+
`CREATE TABLE ${quote(drizzleSchema)}.orm_drizzle_users (
|
|
228
|
+
id bigint PRIMARY KEY,
|
|
229
|
+
email text
|
|
230
|
+
);
|
|
231
|
+
--> statement-breakpoint
|
|
232
|
+
CREATE INDEX CONCURRENTLY orm_drizzle_users_email_idx
|
|
233
|
+
ON ${quote(drizzleSchema)}.orm_drizzle_users (email);
|
|
234
|
+
`
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
fs.writeFileSync(
|
|
238
|
+
path.join(drizzleMetaFolder, '_journal.json'),
|
|
239
|
+
JSON.stringify(
|
|
240
|
+
{
|
|
241
|
+
version: '7',
|
|
242
|
+
dialect: 'postgresql',
|
|
243
|
+
entries: [
|
|
244
|
+
{
|
|
245
|
+
idx: 0,
|
|
246
|
+
version: '7',
|
|
247
|
+
when: 1760000000000,
|
|
248
|
+
tag: '0000_baseline',
|
|
249
|
+
breakpoints: true
|
|
250
|
+
}
|
|
251
|
+
]
|
|
252
|
+
},
|
|
253
|
+
null,
|
|
254
|
+
2
|
|
255
|
+
)
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
// 6. Verify Drizzle's transaction restriction.
|
|
259
|
+
console.log(
|
|
260
|
+
'\nTesting Drizzle concurrent-index restriction...'
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
const db = drizzle(pool);
|
|
264
|
+
|
|
265
|
+
let drizzleRejectedConcurrentIndex = false;
|
|
266
|
+
|
|
267
|
+
try {
|
|
268
|
+
await migrate(db, {
|
|
269
|
+
migrationsFolder: drizzleFolder,
|
|
270
|
+
migrationsSchema: drizzleSchema,
|
|
271
|
+
migrationsTable: '__drizzle_migrations'
|
|
272
|
+
});
|
|
273
|
+
} catch (error) {
|
|
274
|
+
// Drizzle wraps the underlying PostgreSQL error.
|
|
275
|
+
let cause = error;
|
|
276
|
+
|
|
277
|
+
while (cause?.cause) {
|
|
278
|
+
cause = cause.cause;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (cause?.code === '25001') {
|
|
282
|
+
drizzleRejectedConcurrentIndex = true;
|
|
283
|
+
|
|
284
|
+
console.log(
|
|
285
|
+
'PASS: Drizzle migrator rejected CREATE INDEX CONCURRENTLY inside a transaction (PostgreSQL 25001).'
|
|
286
|
+
);
|
|
287
|
+
} else {
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (!drizzleRejectedConcurrentIndex) {
|
|
293
|
+
throw new Error(
|
|
294
|
+
'Expected Drizzle migrator to reject the concurrent-index migration, but it succeeded.'
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// 7. Confirm the rejected migration did not create the index.
|
|
299
|
+
const drizzleIndex = await pool.query(
|
|
300
|
+
'SELECT to_regclass($1) AS name',
|
|
301
|
+
[`${drizzleSchema}.orm_drizzle_users_email_idx`]
|
|
302
|
+
);
|
|
303
|
+
|
|
304
|
+
if (drizzleIndex.rows[0].name) {
|
|
305
|
+
throw new Error(
|
|
306
|
+
'Drizzle concurrent index unexpectedly exists after migration rejection.'
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
console.log(
|
|
311
|
+
'PASS: No Drizzle concurrent index was created.'
|
|
312
|
+
);
|
|
313
|
+
|
|
314
|
+
console.log(
|
|
315
|
+
'\nAll ORM migration verification checks passed.'
|
|
316
|
+
);
|
|
317
|
+
|
|
318
|
+
console.log(
|
|
319
|
+
'Prisma: standalone concurrent-index migration succeeded.'
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
console.log(
|
|
323
|
+
'Drizzle: concurrent-index migration was correctly rejected.'
|
|
324
|
+
);
|
|
325
|
+
|
|
326
|
+
if (process.env.KEEP_TEST_SCHEMAS === '1') {
|
|
327
|
+
console.log(
|
|
328
|
+
`Test schemas retained for inspection: ${prismaSchema}, ${drizzleSchema}`
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
} finally {
|
|
332
|
+
try {
|
|
333
|
+
if (process.env.KEEP_TEST_SCHEMAS !== '1') {
|
|
334
|
+
if (prismaSchemaCreated) {
|
|
335
|
+
await pool.query(
|
|
336
|
+
`DROP SCHEMA IF EXISTS ${quote(prismaSchema)} CASCADE`
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (drizzleSchemaCreated) {
|
|
341
|
+
await pool.query(
|
|
342
|
+
`DROP SCHEMA IF EXISTS ${quote(drizzleSchema)} CASCADE`
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
console.log(
|
|
347
|
+
'Temporary database schemas cleaned up.'
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
} finally {
|
|
351
|
+
try {
|
|
352
|
+
await pool.end();
|
|
353
|
+
} finally {
|
|
354
|
+
cleanupTemporaryDirectory();
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
await verify();
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const { spawnSync } = require('node:child_process');
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
|
|
5
|
+
const root = path.resolve(__dirname, '..');
|
|
6
|
+
const migrationsDir = path.join(root, 'test', 'fixtures', 'pg-matrix', 'migrations');
|
|
7
|
+
const expected = ['001_add_phone.sql', '002_add_email_index.sql'];
|
|
8
|
+
const actual = fs.readdirSync(migrationsDir).filter(name => name.endsWith('.sql')).sort();
|
|
9
|
+
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
|
|
10
|
+
console.error('Matrix fixtures changed. Review the safe migration allowlist:', actual);
|
|
11
|
+
process.exit(1);
|
|
12
|
+
}
|
|
13
|
+
const versions = ['14', '15', '16', '17', '18'];
|
|
14
|
+
let failed = false;
|
|
15
|
+
for (const version of versions) {
|
|
16
|
+
console.log(`\n--- PostgreSQL ${version} ---`);
|
|
17
|
+
const args = [
|
|
18
|
+
path.join(root, 'bin', 'cli.js'), '--assess',
|
|
19
|
+
'--migrations-dir', migrationsDir,
|
|
20
|
+
'--baseline', path.join(root, 'examples', 'baseline.sql'),
|
|
21
|
+
'--verify-sql', path.join(root, 'examples', 'verify.sql'),
|
|
22
|
+
'--postgres-version', version
|
|
23
|
+
];
|
|
24
|
+
const r = spawnSync(process.execPath, args, { cwd: root, stdio: 'inherit', timeout: 180000 });
|
|
25
|
+
if (r.status !== 0) {
|
|
26
|
+
failed = true;
|
|
27
|
+
console.error(`PostgreSQL ${version} failed: ${r.error?.message ?? r.status}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
process.exitCode = failed ? 1 : 0;
|
package/src/analysis.js
CHANGED
|
@@ -3,6 +3,9 @@ import { parseSqlFile } from './parser.js';
|
|
|
3
3
|
import { lintStatements } from './engine.js';
|
|
4
4
|
import { advise } from './advisor.js';
|
|
5
5
|
|
|
6
|
+
import { lockFor } from './locks.js';
|
|
7
|
+
import { migrationPlan } from './plans.js';
|
|
8
|
+
|
|
6
9
|
const ADVISORY_RULES = new Set(['PG015', 'PG016', 'PG017']);
|
|
7
10
|
|
|
8
11
|
export function position(sql, offset = 0) {
|
|
@@ -144,9 +147,7 @@ export async function analyzeFiles(entries, config = {}, options = {}) {
|
|
|
144
147
|
const seen = new Map();
|
|
145
148
|
const version = config.postgresVersion ?? null;
|
|
146
149
|
|
|
147
|
-
const files = [...entries].sort((a, b) =>
|
|
148
|
-
a.file.localeCompare(b.file)
|
|
149
|
-
);
|
|
150
|
+
const files = [...entries].sort((a, b) => a.file.localeCompare(b.file));
|
|
150
151
|
|
|
151
152
|
for (const { file, sql } of files) {
|
|
152
153
|
const parsed = await parseSqlFile(sql, { details: true });
|
|
@@ -178,7 +179,7 @@ export async function analyzeFiles(entries, config = {}, options = {}) {
|
|
|
178
179
|
if (framework === 'prisma' && concurrently(stmt)) {
|
|
179
180
|
issues.push({
|
|
180
181
|
ruleId: 'PG015',
|
|
181
|
-
message: '
|
|
182
|
+
message: 'Prisma: use a standalone migration for CONCURRENTLY; combined SQL statements can fail in a transaction context.',
|
|
182
183
|
fix: 'Review the generated migration and execution strategy; PostgreSQL forbids CONCURRENTLY inside a transaction.'
|
|
183
184
|
});
|
|
184
185
|
}
|
|
@@ -186,8 +187,8 @@ export async function analyzeFiles(entries, config = {}, options = {}) {
|
|
|
186
187
|
if (framework === 'drizzle' && concurrently(stmt)) {
|
|
187
188
|
issues.push({
|
|
188
189
|
ruleId: 'PG016',
|
|
189
|
-
message: '
|
|
190
|
-
fix: '
|
|
190
|
+
message: 'Drizzle node-postgres migrator uses a transaction in the tested version; CONCURRENTLY fails with PostgreSQL 25001.',
|
|
191
|
+
fix: 'Execute the concurrent index through a separately managed non-transactional path; do not use the standard transactional migrator.'
|
|
191
192
|
});
|
|
192
193
|
}
|
|
193
194
|
|
|
@@ -240,6 +241,7 @@ export async function analyzeFiles(entries, config = {}, options = {}) {
|
|
|
240
241
|
line: loc.line,
|
|
241
242
|
column: loc.column,
|
|
242
243
|
framework,
|
|
244
|
+
lock: lockFor(stmt),
|
|
243
245
|
...(options.advisor
|
|
244
246
|
? { advisor: advise(issue, framework) }
|
|
245
247
|
: {})
|
package/src/combined.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { analyzeFiles } from './analysis.js';
|
|
4
|
+
import { simulateSqlFile } from './simulator.js';
|
|
5
|
+
import { summarizeRisk } from './risk.js';
|
|
6
|
+
import { parseSqlFile } from './parser.js';
|
|
7
|
+
import { lockFor } from './locks.js';
|
|
8
|
+
|
|
9
|
+
export function simulationEntries({ file, migrationsDir }) {
|
|
10
|
+
if (Boolean(file) === Boolean(migrationsDir)) throw new Error('Provide exactly one migration file or --migrations-dir');
|
|
11
|
+
const paths = migrationsDir
|
|
12
|
+
? fs.readdirSync(migrationsDir, { withFileTypes: true }).filter(x => x.isFile() && x.name.toLowerCase().endsWith('.sql')).map(x => path.join(migrationsDir, x.name)).sort()
|
|
13
|
+
: [file];
|
|
14
|
+
if (!paths.length || paths.length > 100) throw new Error('Expected 1-100 migration SQL files');
|
|
15
|
+
return paths.map(p => ({ file: path.resolve(p), sql: fs.readFileSync(p, 'utf8') }));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function combinedAssessment({ file, migrationsDir, baseline, postgresVersion = '16', config = {}, run, verifySql }) {
|
|
19
|
+
const entries = simulationEntries({ file, migrationsDir });
|
|
20
|
+
const findings = await analyzeFiles(entries, { ...config, postgresVersion: Number(postgresVersion) }, { advisor: true });
|
|
21
|
+
// Inventory every statement, including operations that do not trigger a lint rule.
|
|
22
|
+
// A zero-findings result must never be mistaken for a zero-lock result.
|
|
23
|
+
const operations = [];
|
|
24
|
+
const indexNames = new Map();
|
|
25
|
+
for (const entry of entries) {
|
|
26
|
+
const statements = await parseSqlFile(entry.sql, { details: true });
|
|
27
|
+
for (const { stmt } of statements) {
|
|
28
|
+
const type = Object.keys(stmt)[0] ?? 'Unknown';
|
|
29
|
+
const lock = lockFor(stmt);
|
|
30
|
+
operations.push({ file: entry.file, type, lock });
|
|
31
|
+
const name = stmt.IndexStmt?.idxname;
|
|
32
|
+
if (name) {
|
|
33
|
+
if (indexNames.has(name)) findings.push({
|
|
34
|
+
ruleId: 'PG018', severity: 'error', file: entry.file, line: 1, column: 1,
|
|
35
|
+
message: `Duplicate CREATE INDEX name ${name}; previously defined in ${indexNames.get(name)}.`,
|
|
36
|
+
fix: 'Give indexes unique names or remove the duplicate migration.',
|
|
37
|
+
lock, framework: 'sql'
|
|
38
|
+
});
|
|
39
|
+
else indexNames.set(name, entry.file);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// Do not start Docker when the migration set is internally inconsistent.
|
|
44
|
+
const duplicate = findings.some(f => f.ruleId === 'PG018');
|
|
45
|
+
const simulation = duplicate
|
|
46
|
+
? { passed: false, skipped: true, reason: 'Duplicate index definitions detected before simulation', steps: [] }
|
|
47
|
+
: simulateSqlFile(file, { migrationsDir, baseline, postgresVersion, run, verifySql });
|
|
48
|
+
const risk = summarizeRisk(findings);
|
|
49
|
+
return {
|
|
50
|
+
schemaVersion: 1, postgresVersion: Number(postgresVersion),
|
|
51
|
+
execution: simulation, lint: { findings, count: findings.length, risk }, operations,
|
|
52
|
+
safetyNote: 'No lint findings does not mean no locks or downtime risk; review operations and production workload.',
|
|
53
|
+
recommendation: !simulation.passed ? 'Migration execution or verification failed; do not deploy.'
|
|
54
|
+
: findings.some(f => f.severity === 'error') ? 'Execution succeeded but static analysis found errors; review before deployment.'
|
|
55
|
+
: findings.length ? 'Execution succeeded with advisories; review locks and production workload.'
|
|
56
|
+
: 'Execution succeeded with no configured findings; this is not a downtime guarantee.',
|
|
57
|
+
passed: simulation.passed && !findings.some(f => f.severity === 'error'),
|
|
58
|
+
confidence: 'limited: disposable database and heuristic linting cannot establish production safety'
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Read-only catalog snapshot. Never executes user-supplied SQL or changes session state. */
|
|
2
|
+
export async function inspectDatabase(query, { limit = 50 } = {}) {
|
|
3
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new Error('limit must be between 1 and 200');
|
|
4
|
+
const version = await query('SHOW server_version_num');
|
|
5
|
+
const versionNum = Number(version.rows?.[0]?.server_version_num);
|
|
6
|
+
if (!Number.isInteger(versionNum) || versionNum < 100000) throw new Error('Unable to determine PostgreSQL server version');
|
|
7
|
+
const tables = await query(`SELECT n.nspname AS schema_name, c.relname AS table_name,
|
|
8
|
+
c.reltuples::bigint AS estimated_rows, pg_total_relation_size(c.oid) AS bytes
|
|
9
|
+
FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
10
|
+
WHERE c.relkind IN ('r','p') AND n.nspname NOT IN ('pg_catalog','information_schema')
|
|
11
|
+
AND n.nspname NOT LIKE 'pg_toast%' ORDER BY pg_total_relation_size(c.oid) DESC LIMIT $1`, [limit]);
|
|
12
|
+
return { postgresVersion: Math.floor(versionNum / 10000), source: 'read-only PostgreSQL catalog', confidence: 'estimates', tables: tables.rows.map(r => ({ schema: r.schema_name, table: r.table_name, estimatedRows: Number(r.estimated_rows), bytes: Number(r.bytes) })) };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function inspectDatabaseUrl(url, options) {
|
|
16
|
+
if (!url) throw new Error('Database URL is required');
|
|
17
|
+
let pg;
|
|
18
|
+
try { pg = await import('pg'); }
|
|
19
|
+
catch { throw new Error('Database inspection requires the optional pg package: npm install pg'); }
|
|
20
|
+
const client = new pg.default.Client({ connectionString: url, connectionTimeoutMillis: 5000, query_timeout: 5000, statement_timeout: 5000, application_name: 'pg-safe-migrate-inspect' });
|
|
21
|
+
try {
|
|
22
|
+
await client.connect();
|
|
23
|
+
// Read-only transaction protects against accidental writes; query budget is bounded.
|
|
24
|
+
await client.query('BEGIN READ ONLY');
|
|
25
|
+
await client.query("SET LOCAL statement_timeout = '5s'");
|
|
26
|
+
const result = await inspectDatabase((sql, params) => client.query(sql, params), options);
|
|
27
|
+
await client.query('ROLLBACK');
|
|
28
|
+
return result;
|
|
29
|
+
} finally { await client.end(); }
|
|
30
|
+
}
|
package/src/github.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
function escapeCommand(s) {
|
|
2
|
+
return String(s).replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');
|
|
3
|
+
}
|
|
4
|
+
function escapeProperty(s) {
|
|
5
|
+
return escapeCommand(s).replaceAll(':', '%3A').replaceAll(',', '%2C');
|
|
6
|
+
}
|
|
7
|
+
export function toGitHubAnnotations(findings) {
|
|
8
|
+
return findings.map(f => `::${f.severity === 'error' ? 'error' : 'warning'} file=${escapeProperty(f.file)},line=${Math.max(1, f.line || 1)},col=${Math.max(1, f.column || 1)},title=${escapeProperty(f.ruleId)}::${escapeCommand(f.message)} Fix: ${escapeCommand(f.fix)}`).join('\n') + (findings.length ? '\n' : '');
|
|
9
|
+
}
|
|
10
|
+
export function toMarkdownSummary(findings, filesChecked) {
|
|
11
|
+
const errors = findings.filter(f => f.severity === 'error').length;
|
|
12
|
+
const warnings = findings.length - errors;
|
|
13
|
+
const lines = ['## PostgreSQL migration safety', '', `Checked ${filesChecked} file(s): **${errors} error(s)**, **${warnings} warning(s)**.`, '', '| Rule | Severity | Location | Finding |', '|---|---|---|---|'];
|
|
14
|
+
for (const f of findings) lines.push(`| ${f.ruleId} | ${f.severity} | \`${String(f.file).replaceAll('|', '\\|')}:${f.line}\` | ${f.message.replaceAll('|', '\\|').replaceAll('\n', ' ')} |`);
|
|
15
|
+
lines.push('', '> Static heuristic analysis, not a guarantee of zero downtime.', '');
|
|
16
|
+
return lines.join('\n');
|
|
17
|
+
}
|
package/src/locks.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Conservative, statement-type classification. Does not model lock duration or contention.
|
|
2
|
+
export function lockFor(stmt) {
|
|
3
|
+
if (stmt.AlterTableStmt || stmt.DropStmt?.removeType === 'OBJECT_TABLE' || stmt.RenameStmt) return { mode: 'ACCESS EXCLUSIVE', confidence: 'heuristic', note: 'May block readers/writers; exact mode varies by subcommand.' };
|
|
4
|
+
if (stmt.IndexStmt) return stmt.IndexStmt.concurrent
|
|
5
|
+
? { mode: 'SHARE UPDATE EXCLUSIVE', confidence: 'heuristic', note: 'Concurrent index builds still acquire locks and can wait.' }
|
|
6
|
+
: { mode: 'SHARE', confidence: 'heuristic', note: 'Ordinary index creation can block writes.' };
|
|
7
|
+
return { mode: 'unknown', confidence: 'unknown', note: 'Not classified.' };
|
|
8
|
+
}
|
package/src/plans.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function migrationPlan(finding) {
|
|
2
|
+
const plans = {
|
|
3
|
+
PG001: ['Add a replacement column.', 'Backfill in small batches.', 'Deploy application dual-read/dual-write or compatibility logic.', 'Switch reads and writes.', 'Remove the old column in a later release.'],
|
|
4
|
+
PG013: ['Add an equivalent NOT VALID CHECK constraint.', 'Validate the constraint in a separate deployment.', 'Apply SET NOT NULL only after validating compatibility and lock behavior.'],
|
|
5
|
+
PG015: ['Create the table or column in an earlier migration.', 'Create the concurrent index in a standalone migration.', 'Verify runner transaction behavior on disposable PostgreSQL.'],
|
|
6
|
+
PG016: ['Apply ordinary schema changes with Drizzle migrator.', 'Run CREATE INDEX CONCURRENTLY separately outside a transaction.', 'Record the operation in deployment runbooks and verify the index.']
|
|
7
|
+
};
|
|
8
|
+
return { ruleId: finding.ruleId, steps: plans[finding.ruleId] || ['Review lock impact.', 'Test on a disposable copy.', 'Plan rollback and application compatibility.'], automated: false, reviewRequired: true };
|
|
9
|
+
}
|
package/src/presets.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export function getPreset(name) {
|
|
2
|
+
if (name === 'recommended') return { severity: 'error', rules: {} };
|
|
3
|
+
if (name === 'strict') return { severity: 'error', rules: { PG015: 'error', PG016: 'error', PG017: 'error' } };
|
|
4
|
+
throw new Error('preset must be recommended or strict');
|
|
5
|
+
}
|
package/src/risk.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const weights = { error: 20, warning: 5 };
|
|
2
|
+
export function summarizeRisk(findings) {
|
|
3
|
+
const score = Math.min(100, findings.reduce((sum, f) => sum + (weights[f.severity] || 0), 0));
|
|
4
|
+
return { score, band: score >= 60 ? 'high' : score >= 20 ? 'moderate' : 'low', confidence: 'low', basis: 'Heuristic severity counts only; no database statistics or production workload context.' };
|
|
5
|
+
}
|