@subodh001/pg-safe-migrate 1.1.2 → 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 +303 -29
- package/bin/cli.js +83 -54
- 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 +13 -4
- 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/advisor.js +22 -0
- package/src/analysis.js +258 -0
- package/src/combined.js +60 -0
- package/src/config.js +27 -0
- package/src/db-inspect.js +30 -0
- package/src/engine.js +3 -1
- package/src/github.js +17 -0
- package/src/locks.js +8 -0
- package/src/parser.js +5 -5
- package/src/plans.js +9 -0
- package/src/presets.js +5 -0
- package/src/reports.js +5 -0
- package/src/risk.js +5 -0
- package/src/rules/additionalRules.js +9 -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/advisor.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const plans = {
|
|
2
|
+
PG001:['Confirm the runner is non-transactional.','Create the index CONCURRENTLY.','Monitor and clean up invalid indexes after failure.'],
|
|
3
|
+
PG002:['Deploy code that no longer reads or writes the old column.','Verify all old application instances are retired.','Drop the column in a later deployment.'],
|
|
4
|
+
PG003:['Assess type conversion and rewrite requirements.','Consider a replacement column with batched backfill.','Switch readers and writers before retiring the old column.'],
|
|
5
|
+
PG004:['Add a nullable column first.','Backfill in batches.','Validate before applying NOT NULL.'],
|
|
6
|
+
PG005:['Add the foreign key NOT VALID.','Validate in a separate migration.','Monitor lock duration.'],
|
|
7
|
+
PG006:['Introduce a compatible replacement.','Deploy applications supporting both names.','Remove the old name after a compatibility window.'],
|
|
8
|
+
PG007:['Verify index usage and dependencies.','Use DROP INDEX CONCURRENTLY outside transactions if appropriate.','Confirm the operation is supported without CASCADE.'],
|
|
9
|
+
PG008:['Split transactional and non-transactional migrations.','Run concurrent index DDL outside explicit transactions.','Verify migration runner behavior.'],
|
|
10
|
+
PG010:['Consider CREATE UNIQUE INDEX CONCURRENTLY.','Attach the index to the constraint if supported.','Validate uniqueness and existing duplicates.'],
|
|
11
|
+
PG011:['Check all application dependencies.','Archive required data.','Remove the table only after compatible code is deployed.'],
|
|
12
|
+
PG012:['Consider adding the CHECK constraint NOT VALID.','Validate it separately.','Monitor scan and lock impact.'],
|
|
13
|
+
PG013:['Review PostgreSQL version and proof of existing non-null values.','Consider a validated CHECK constraint strategy.','Apply SET NOT NULL during a controlled deployment.'],
|
|
14
|
+
PG014:['Avoid adding a default in the same step on PostgreSQL 10.','Backfill gradually.','Apply defaults and constraints in later migrations.'],
|
|
15
|
+
PG015:['Check the Prisma migration runner transaction strategy.','Execute CONCURRENTLY outside a transaction.','Verify the deployed migration in staging.'],
|
|
16
|
+
PG016:['Check Drizzle runner transaction wrapping.','Execute CONCURRENTLY outside a transaction.','Verify the deployed migration in staging.'],
|
|
17
|
+
PG017:['Inspect the earlier migration and dependency graph.','Confirm the final schema and deployment order.','Test the ordered migrations on staging.']
|
|
18
|
+
};
|
|
19
|
+
export function advise(issue,framework='sql') {
|
|
20
|
+
const context = framework==='prisma' ? 'Prisma migration: review migration.sql and the deployment runner.' : framework==='drizzle' ? 'Drizzle migration: review generated SQL and runner transaction behavior.' : 'Raw SQL: verify the execution transaction policy.';
|
|
21
|
+
return {ruleId:issue.ruleId,steps:plans[issue.ruleId] || ['Review SQL dependencies.','Test on staging.','Deploy with lock and statement timeouts.'],note:`${context} Guidance only; not validated against a live database.`};
|
|
22
|
+
}
|
package/src/analysis.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
|
|
2
|
+
import { parseSqlFile } from './parser.js';
|
|
3
|
+
import { lintStatements } from './engine.js';
|
|
4
|
+
import { advise } from './advisor.js';
|
|
5
|
+
|
|
6
|
+
import { lockFor } from './locks.js';
|
|
7
|
+
import { migrationPlan } from './plans.js';
|
|
8
|
+
|
|
9
|
+
const ADVISORY_RULES = new Set(['PG015', 'PG016', 'PG017']);
|
|
10
|
+
|
|
11
|
+
export function position(sql, offset = 0) {
|
|
12
|
+
const prefix = sql.slice(0, Math.max(0, offset));
|
|
13
|
+
const lines = prefix.split('\n');
|
|
14
|
+
|
|
15
|
+
return {
|
|
16
|
+
line: lines.length,
|
|
17
|
+
column: lines.at(-1).length + 1
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function frameworkFor(file) {
|
|
22
|
+
const p = file.replaceAll('\\', '/');
|
|
23
|
+
|
|
24
|
+
if (/(^|\/)prisma\/migrations\//.test(p)) return 'prisma';
|
|
25
|
+
if (/(^|\/)drizzle\//.test(p)) return 'drizzle';
|
|
26
|
+
|
|
27
|
+
return 'sql';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function txType(stmt) {
|
|
31
|
+
const kind = stmt.TransactionStmt?.kind;
|
|
32
|
+
|
|
33
|
+
if (kind === 'TRANS_STMT_BEGIN' || kind === 'TRANS_STMT_START') {
|
|
34
|
+
return 'begin';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if ([
|
|
38
|
+
'TRANS_STMT_COMMIT',
|
|
39
|
+
'TRANS_STMT_ROLLBACK',
|
|
40
|
+
'TRANS_STMT_ROLLBACK_TO',
|
|
41
|
+
'TRANS_STMT_PREPARE'
|
|
42
|
+
].includes(kind)) {
|
|
43
|
+
return 'end';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function concurrently(stmt) {
|
|
50
|
+
return Boolean(
|
|
51
|
+
stmt.IndexStmt?.concurrent ||
|
|
52
|
+
(
|
|
53
|
+
stmt.DropStmt?.removeType === 'OBJECT_INDEX' &&
|
|
54
|
+
stmt.DropStmt.concurrent
|
|
55
|
+
)
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function ddlTarget(stmt) {
|
|
60
|
+
if (stmt.AlterTableStmt) {
|
|
61
|
+
return stmt.AlterTableStmt.relation?.relname;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (stmt.RenameStmt) {
|
|
65
|
+
return stmt.RenameStmt.relation?.relname;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') {
|
|
69
|
+
return stmt.DropStmt.objects?.[0]?.List?.items
|
|
70
|
+
?.map(x => x.String?.sval)
|
|
71
|
+
.join('.');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function extras(stmt, postgresVersion) {
|
|
78
|
+
const issues = [];
|
|
79
|
+
|
|
80
|
+
const add = (ruleId, message, fix) => {
|
|
81
|
+
issues.push({ ruleId, message, fix });
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
if (!stmt.AlterTableStmt) return issues;
|
|
85
|
+
|
|
86
|
+
for (const wrapper of stmt.AlterTableStmt.cmds || []) {
|
|
87
|
+
const cmd = wrapper.AlterTableCmd;
|
|
88
|
+
if (!cmd) continue;
|
|
89
|
+
|
|
90
|
+
if (cmd.subtype === 'AT_SetNotNull') {
|
|
91
|
+
add(
|
|
92
|
+
'PG013',
|
|
93
|
+
'SET NOT NULL may scan a large table and requires a strong lock.',
|
|
94
|
+
'Validate an equivalent CHECK constraint first where supported; test on your PostgreSQL version.'
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (
|
|
99
|
+
cmd.subtype === 'AT_AddConstraint' &&
|
|
100
|
+
cmd.def?.Constraint?.contype === 'CONSTR_CHECK' &&
|
|
101
|
+
!cmd.def.Constraint.skip_validation
|
|
102
|
+
) {
|
|
103
|
+
add(
|
|
104
|
+
'PG012',
|
|
105
|
+
'Adding a validated CHECK constraint may scan existing rows.',
|
|
106
|
+
'Consider NOT VALID followed by a separately scheduled VALIDATE CONSTRAINT.'
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (
|
|
111
|
+
cmd.subtype === 'AT_AddConstraint' &&
|
|
112
|
+
cmd.def?.Constraint?.contype === 'CONSTR_UNIQUE'
|
|
113
|
+
) {
|
|
114
|
+
add(
|
|
115
|
+
'PG010',
|
|
116
|
+
'Adding a UNIQUE constraint can require a blocking index build.',
|
|
117
|
+
'Consider CREATE UNIQUE INDEX CONCURRENTLY then attach the index using a constraint, where applicable.'
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (
|
|
122
|
+
cmd.subtype === 'AT_AddColumn' &&
|
|
123
|
+
postgresVersion != null &&
|
|
124
|
+
Number(postgresVersion) < 11
|
|
125
|
+
) {
|
|
126
|
+
const def = cmd.def?.ColumnDef;
|
|
127
|
+
|
|
128
|
+
if (
|
|
129
|
+
def?.constraints?.some(
|
|
130
|
+
x => x.Constraint?.contype === 'CONSTR_DEFAULT'
|
|
131
|
+
)
|
|
132
|
+
) {
|
|
133
|
+
add(
|
|
134
|
+
'PG014',
|
|
135
|
+
'On PostgreSQL 10, adding a column with a default may rewrite the table.',
|
|
136
|
+
'Use a nullable column and controlled backfill, or evaluate upgrading PostgreSQL.'
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return issues;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function analyzeFiles(entries, config = {}, options = {}) {
|
|
146
|
+
const findings = [];
|
|
147
|
+
const seen = new Map();
|
|
148
|
+
const version = config.postgresVersion ?? null;
|
|
149
|
+
|
|
150
|
+
const files = [...entries].sort((a, b) => a.file.localeCompare(b.file));
|
|
151
|
+
|
|
152
|
+
for (const { file, sql } of files) {
|
|
153
|
+
const parsed = await parseSqlFile(sql, { details: true });
|
|
154
|
+
const framework = frameworkFor(file);
|
|
155
|
+
|
|
156
|
+
let inTransaction = false;
|
|
157
|
+
|
|
158
|
+
for (const { stmt, offset } of parsed) {
|
|
159
|
+
const loc = position(sql, offset);
|
|
160
|
+
const transaction = txType(stmt);
|
|
161
|
+
|
|
162
|
+
if (transaction === 'begin') {
|
|
163
|
+
inTransaction = true;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const issues = [
|
|
167
|
+
...lintStatements([stmt]),
|
|
168
|
+
...extras(stmt, version)
|
|
169
|
+
];
|
|
170
|
+
|
|
171
|
+
if (inTransaction && concurrently(stmt)) {
|
|
172
|
+
issues.push({
|
|
173
|
+
ruleId: 'PG008',
|
|
174
|
+
message: 'CONCURRENTLY cannot execute inside an explicit transaction block.',
|
|
175
|
+
fix: 'Run concurrent index operations outside BEGIN/COMMIT.'
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (framework === 'prisma' && concurrently(stmt)) {
|
|
180
|
+
issues.push({
|
|
181
|
+
ruleId: 'PG015',
|
|
182
|
+
message: 'Prisma: use a standalone migration for CONCURRENTLY; combined SQL statements can fail in a transaction context.',
|
|
183
|
+
fix: 'Review the generated migration and execution strategy; PostgreSQL forbids CONCURRENTLY inside a transaction.'
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (framework === 'drizzle' && concurrently(stmt)) {
|
|
188
|
+
issues.push({
|
|
189
|
+
ruleId: 'PG016',
|
|
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.'
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const target = ddlTarget(stmt);
|
|
196
|
+
|
|
197
|
+
if (
|
|
198
|
+
target &&
|
|
199
|
+
seen.has(target) &&
|
|
200
|
+
(
|
|
201
|
+
stmt.RenameStmt ||
|
|
202
|
+
stmt.DropStmt?.removeType === 'OBJECT_TABLE'
|
|
203
|
+
)
|
|
204
|
+
) {
|
|
205
|
+
const previous = seen.get(target);
|
|
206
|
+
|
|
207
|
+
if (previous.file !== file) {
|
|
208
|
+
issues.push({
|
|
209
|
+
ruleId: 'PG017',
|
|
210
|
+
message: `Potential cross-file dependency: ${target} was modified earlier in ${previous.file}.`,
|
|
211
|
+
fix: 'Review migration order and deployed application compatibility; this is a heuristic, not proof of a conflict.'
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (target) {
|
|
217
|
+
seen.set(target, { file });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
for (const issue of issues) {
|
|
221
|
+
|
|
222
|
+
const isAdvisory = ADVISORY_RULES.has(issue.ruleId);
|
|
223
|
+
|
|
224
|
+
const defaultSeverity = isAdvisory
|
|
225
|
+
? 'warning'
|
|
226
|
+
: 'error';
|
|
227
|
+
|
|
228
|
+
const severity =
|
|
229
|
+
config.rules?.[issue.ruleId] ??
|
|
230
|
+
(isAdvisory
|
|
231
|
+
? 'warning'
|
|
232
|
+
: (config.severity ?? defaultSeverity));
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
if (severity === 'off') continue;
|
|
236
|
+
|
|
237
|
+
findings.push({
|
|
238
|
+
...issue,
|
|
239
|
+
severity,
|
|
240
|
+
file,
|
|
241
|
+
line: loc.line,
|
|
242
|
+
column: loc.column,
|
|
243
|
+
framework,
|
|
244
|
+
lock: lockFor(stmt),
|
|
245
|
+
...(options.advisor
|
|
246
|
+
? { advisor: advise(issue, framework) }
|
|
247
|
+
: {})
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (transaction === 'end') {
|
|
252
|
+
inTransaction = false;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return findings;
|
|
258
|
+
}
|