pgsafe 2.7.0 → 2.7.1
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/CHANGELOG.md +88 -0
- package/CONTRIBUTING.md +3 -0
- package/README.md +255 -116
- package/SECURITY.md +13 -0
- package/bin/cli.js +120 -0
- package/docs/RULES.md +31 -0
- package/examples/baseline.sql +7 -0
- package/examples/consumer-workflow.yml +22 -0
- package/examples/migrations/001_add_phone.sql +1 -0
- package/examples/migrations/002_add_email_index.sql +1 -0
- package/examples/reviewed-risk-baseline.json +7 -0
- package/examples/safe.sql +2 -0
- package/examples/suppression-gate-policy.json +11 -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/examples/week3-gate-policy.json +6 -0
- package/examples/week3-production-context.json +8 -0
- package/package.json +73 -46
- 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 +77 -0
- package/src/analysis.js +411 -0
- package/src/combined.js +60 -0
- package/src/config.js +38 -0
- package/src/db-inspect.js +30 -0
- package/src/detector.js +25 -0
- package/src/engine.js +48 -0
- package/src/gitDiff.js +33 -0
- package/src/github.js +17 -0
- package/src/locks.js +134 -0
- package/src/parser.js +86 -0
- package/src/plans.js +9 -0
- package/src/presets.js +5 -0
- package/src/production-context.js +78 -0
- package/src/reports.js +38 -0
- package/src/risk-baseline.js +54 -0
- package/src/risk.js +29 -0
- package/src/rules/additionalRules.js +9 -0
- package/src/rules/alterTableRules.js +65 -0
- package/src/rules/concurrentIndex.js +18 -0
- package/src/rules/dataIntegrityRules.js +40 -0
- package/src/rules/dropColumn.js +12 -0
- package/src/rules/operationalRiskRules.js +57 -0
- package/src/rules/ruleCatalog.js +37 -0
- package/src/rules/versionCatalog.js +16 -0
- package/src/rules/versionRules.js +49 -0
- package/src/simulator.js +135 -0
- package/src/suppression-matcher.js +24 -0
- package/src/suppression-report.js +19 -0
- package/src/suppression.js +78 -0
- package/src/team-policy.js +84 -0
- package/bin/pgsafe.js +0 -3
|
@@ -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,77 @@
|
|
|
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
|
+
// Illustrative templates only: never execute or apply them automatically.
|
|
20
|
+
// Identifiers, constraints and data predicates must be reviewed for each schema.
|
|
21
|
+
const alternatives = {
|
|
22
|
+
PG001: {
|
|
23
|
+
title: 'Build the index without blocking ordinary writes',
|
|
24
|
+
sql: '-- Run outside a transaction block; replace identifiers.\nCREATE INDEX CONCURRENTLY idx_orders_customer_id ON orders (customer_id);',
|
|
25
|
+
caveat: 'Concurrent builds can take longer, wait for transactions, and leave an invalid index after failure. Check for an existing index first.'
|
|
26
|
+
},
|
|
27
|
+
PG003: {
|
|
28
|
+
title: 'Use expand/backfill/contract for risky type changes',
|
|
29
|
+
sql: '-- Illustrative only: adapt types, conversion and names.\nALTER TABLE orders ADD COLUMN amount_new numeric;\n-- Backfill in bounded batches, with application dual-write.\n-- Switch reads, validate, then retire the old column in a later release.',
|
|
30
|
+
caveat: 'Column copying, conversion, triggers, application compatibility and constraints require a project-specific plan.'
|
|
31
|
+
},
|
|
32
|
+
PG004: {
|
|
33
|
+
title: 'Introduce required columns in stages',
|
|
34
|
+
sql: '-- Replace table/column/type and choose a real backfill policy.\nALTER TABLE customers ADD COLUMN region text;\n-- Backfill existing rows in bounded batches.\nALTER TABLE customers ADD CONSTRAINT customers_region_nn CHECK (region IS NOT NULL) NOT VALID;\nALTER TABLE customers VALIDATE CONSTRAINT customers_region_nn;\nALTER TABLE customers ALTER COLUMN region SET NOT NULL;',
|
|
35
|
+
caveat: 'Ensure new writes populate the column before validation. Validate PostgreSQL-version behavior and lock requirements.'
|
|
36
|
+
},
|
|
37
|
+
PG005: {
|
|
38
|
+
title: 'Add and validate a foreign key separately',
|
|
39
|
+
sql: '-- Replace identifiers and verify referenced keys.\nALTER TABLE orders ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers(id) NOT VALID;\nALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;',
|
|
40
|
+
caveat: 'NOT VALID skips checking existing rows at creation, not enforcement for new rows. Validation still consumes resources and locks.'
|
|
41
|
+
},
|
|
42
|
+
PG010: {
|
|
43
|
+
title: 'Create unique index concurrently before attaching a constraint',
|
|
44
|
+
sql: '-- Check duplicates first; run outside transaction.\nCREATE UNIQUE INDEX CONCURRENTLY users_email_unique_idx ON users (email);\n-- For eligible plain-column indexes only:\nALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE USING INDEX users_email_unique_idx;',
|
|
45
|
+
caveat: 'Existing duplicates cause failure. Index eligibility, NULL semantics and transaction handling must be checked.'
|
|
46
|
+
},
|
|
47
|
+
PG012: {
|
|
48
|
+
title: 'Validate CHECK constraints in a separate step',
|
|
49
|
+
sql: '-- Replace predicate and identifiers.\nALTER TABLE orders ADD CONSTRAINT orders_total_nonnegative CHECK (total >= 0) NOT VALID;\nALTER TABLE orders VALIDATE CONSTRAINT orders_total_nonnegative;',
|
|
50
|
+
caveat: 'New or updated rows are checked immediately; validation of existing rows may fail and consumes resources.'
|
|
51
|
+
},
|
|
52
|
+
PG013: {
|
|
53
|
+
title: 'Prove non-null data before enforcing NOT NULL',
|
|
54
|
+
sql: '-- Replace identifiers. Ensure new writes cannot introduce NULLs.\nALTER TABLE users ADD CONSTRAINT users_email_nn CHECK (email IS NOT NULL) NOT VALID;\nALTER TABLE users VALIDATE CONSTRAINT users_email_nn;\nALTER TABLE users ALTER COLUMN email SET NOT NULL;',
|
|
55
|
+
caveat: 'On supported PostgreSQL versions, a validated CHECK may avoid a full scan for SET NOT NULL; lock requirements remain.'
|
|
56
|
+
},
|
|
57
|
+
PG025: {
|
|
58
|
+
title: 'Validate a non-null invariant first',
|
|
59
|
+
sql: '-- Replace identifiers. Backfill NULLs and prevent new NULLs first.\nALTER TABLE users ADD CONSTRAINT users_email_nn CHECK (email IS NOT NULL) NOT VALID;\nALTER TABLE users VALIDATE CONSTRAINT users_email_nn;\nALTER TABLE users ALTER COLUMN email SET NOT NULL;',
|
|
60
|
+
caveat: 'SET NOT NULL can still require a strong lock. Check version, traffic, existing NULLs and constraint lifecycle.'
|
|
61
|
+
},
|
|
62
|
+
PG023: {
|
|
63
|
+
title: 'Review destructive bulk removal',
|
|
64
|
+
sql: '-- No generally safe automatic rewrite for TRUNCATE.\n-- Consider retention, backup, maintenance window and bounded DELETE batches if appropriate.',
|
|
65
|
+
caveat: 'DELETE is not equivalent to TRUNCATE: triggers, identity sequences, foreign keys, MVCC and performance differ.'
|
|
66
|
+
},
|
|
67
|
+
PG024: {
|
|
68
|
+
title: 'Remove constraint dependencies in a separate deployment',
|
|
69
|
+
sql: '-- Review application and database dependencies first.\n-- Drop the constraint only after a compatible deployment and rollback plan.',
|
|
70
|
+
caveat: 'Dropping constraints can permit invalid data and requires appropriate locks. No universal safe SQL replacement exists.'
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export function advise(issue,framework='sql') {
|
|
75
|
+
const context = framework==='prisma' ? 'Prisma migration: review migration.sql and the deployment runner.' : framework==='drizzle' ? 'Drizzle migration: review generated SQL and runner transaction behavior.' : framework==='flyway' ? 'Flyway migration: verify executeInTransaction settings, naming conventions and transaction grouping.' : 'Raw SQL: verify the execution transaction policy.';
|
|
76
|
+
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.`,alternative: alternatives[issue.ruleId] ? {...alternatives[issue.ruleId], automatic: false} : null};
|
|
77
|
+
}
|