@subodh001/pg-safe-migrate 2.5.0 → 2.6.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/CHANGELOG.md ADDED
@@ -0,0 +1,43 @@
1
+ # Changelog
2
+
3
+ ## [2.6.0]
4
+
5
+ - Unicode-aware SQL positions, leading comment handling and transaction tracking for savepoints and chained transactions.
6
+ - Optimized statement position tracking.
7
+ - Corrected rule catalog coverage and default severity metadata (no enforcement changes).
8
+
9
+ ## [2.5.0] - 2026-11-20
10
+
11
+
12
+
13
+ ### Added
14
+
15
+ - Configurable CI migration safety gates.
16
+
17
+ - Reviewed migration risk baselines to distinguish new, existing, and resolved findings.
18
+
19
+ - Production-aware migration recommendations using optional workload and table-size estimates.
20
+
21
+ - GitHub Actions pull-request safety reporting.
22
+
23
+ - Improved onboarding, examples, and adoption documentation.
24
+
25
+
26
+
27
+ ### Improved
28
+
29
+ - JSON reporting for risk baselines, production context, and policy decisions.
30
+
31
+ - Migration safety guidance for deployment planning.
32
+
33
+ - Release-readiness verification and regression coverage.
34
+
35
+
36
+
37
+ ### Notes
38
+
39
+ - Production context uses supplied estimates, not live database measurements.
40
+
41
+ - Static analysis does not guarantee zero downtime.
42
+
43
+ - Existing migration safety rules remain available.
@@ -0,0 +1,3 @@
1
+ # Contributing
2
+
3
+ Fork the repository and create a focused branch. Install dependencies with `npm ci`. Add regression tests for rule changes and preserve stable diagnostic IDs. Run `npm run test:release` and `git diff --check`. For extension changes run `npm run build:standalone` and `npm run verify:standalone` in `vscode-extension`. Document limitations and include sanitized SQL reproductions. Do not commit secrets, generated VSIX files or local logs. Open a pull request describing the change and test results. Security reports should follow SECURITY.md.
package/README.md CHANGED
@@ -1,14 +1,14 @@
1
- > **Published npm CLI: v2.4.0.** **VS Code extension: v0.5.0.** Week 3 CI gate is a development candidate and is not published yet. Migration analysis does not guarantee zero downtime.
1
+ > **CLI documentation: v2.6.0.** **VS Code extension documentation: v0.7.0.** Check npm and the Marketplace for available versions. Migration analysis does not guarantee zero downtime.
2
2
 
3
3
  # pg-safe-migrate
4
4
 
5
5
  **Catch risky PostgreSQL migrations before they reach production.**
6
6
 
7
- An open-source, AST-based PostgreSQL migration risk linter for **Prisma, Drizzle, and raw SQL**.
7
+ An open-source, AST-based PostgreSQL migration risk linter for **Prisma, Drizzle, Flyway, and raw SQL**.
8
8
 
9
9
  Detect risky PostgreSQL DDL patterns and provide additional framework-specific migration advisories.
10
10
 
11
- **Features:** PostgreSQL AST parsing · PG001–PG017 identifiers (see rule coverage below) · Git-diff mode · JSON/SARIF · configurable severity · optional advisor · GitHub Actions
11
+ **Features:** PostgreSQL AST parsing · migration risk diagnostics (see rule coverage below) · Git-diff mode · JSON/SARIF · configurable severity · optional advisor · GitHub Actions
12
12
 
13
13
  > **Important:** This tool identifies configured migration risks. It does not guarantee zero downtime.
14
14
 
@@ -16,7 +16,7 @@ Detect risky PostgreSQL DDL patterns and provide additional framework-specific m
16
16
 
17
17
  See how `pg-safe-migrate` catches an unsafe PostgreSQL migration and suggests a safer alternative.
18
18
 
19
- ![pg-safe-migrate CLI demonstration](assets/pg-safe-migrate-demo.gif)
19
+ ![pg-safe-migrate CLI demonstration](https://raw.githubusercontent.com/subodhsingh001/pg-safe-migrate/main/assets/pg-safe-migrate-demo.gif)
20
20
 
21
21
  ### Example
22
22
 
@@ -45,7 +45,7 @@ CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
45
45
  `CREATE INDEX CONCURRENTLY` must run outside a transaction block.
46
46
 
47
47
 
48
- ## Week 3 preview: opt-in CI policy gate (unreleased)
48
+ ## Week 3: opt-in CI policy gate
49
49
 
50
50
  Run a deterministic, policy-driven static lint check in CI:
51
51
 
@@ -53,17 +53,17 @@ Run a deterministic, policy-driven static lint check in CI:
53
53
  node bin/cli.js db/migrations --gate-policy examples/week3-gate-policy.json --fail-on none
54
54
  ```
55
55
 
56
- The gate can block selected `PGxxx` rules, excessive warnings, and heuristic risk scores. It reports a block to stderr and exits with code `1`; malformed configuration exits `2`. This is a **development-only preview**, not available in the published v2.4.0 package. See [Week 3 implementation notes](WEEK3-DAY1-IMPLEMENTED.md).
56
+ The gate can block selected `PGxxx` rules, excessive warnings, and heuristic risk scores. It reports a block to stderr and exits with code `1`; malformed configuration exits `2`. This feature was introduced in CLI v2.5.0. See [Week 3 implementation notes](WEEK3-DAY1-IMPLEMENTED.md).
57
57
 
58
58
  [Install from npm](https://www.npmjs.com/package/@subodh001/pg-safe-migrate) · [Install the VS Code extension](https://marketplace.visualstudio.com/items?itemName=sukoaa.pg-safe-migrate-vscode) · [Report an issue](https://github.com/subodhsingh001/pg-safe-migrate/issues)
59
59
 
60
- ## Adoption and developer resources (Week 3 candidate)
60
+ ## Adoption and developer resources
61
61
 
62
62
  - [Safe onboarding and CI troubleshooting](docs/ADOPTION-GUIDE.md)
63
63
  - [Short demonstration recording script](docs/DEMO-SCRIPT.md)
64
64
  - [Proposed npm and VS Code Marketplace copy](docs/MARKETPLACE-COPY.md)
65
65
 
66
- **Release distinction:** The Week 3 policy, baseline, production-context, and PR reporting features are currently source-checkout development features, not part of published npm v2.4.0. Review the policy and baseline before enabling blocking checks; passing a static gate is not a downtime guarantee.
66
+ **Release note:** The Week 3 policy, baseline, production-context, and PR reporting features were introduced in npm v2.5.0. Review the policy and baseline before enabling blocking checks; passing a static gate is not a downtime guarantee.
67
67
 
68
68
  ## Installation
69
69
 
@@ -76,7 +76,7 @@ npm install --save-dev @subodh001/pg-safe-migrate
76
76
  Or execute the published package without installing it in your project:
77
77
 
78
78
  ```bash
79
- npx --yes --package=@subodh001/pg-safe-migrate@2.4.0 pg-safe-migrate --help
79
+ npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate --help
80
80
  ```
81
81
 
82
82
  ## Quick start
@@ -93,6 +93,9 @@ The CLI searches these directories:
93
93
  - `drizzle`
94
94
  - `migrations`
95
95
  - `db/migrations`
96
+ - `db/migration`
97
+ - `sql/migrations`
98
+ - `sql`
96
99
 
97
100
  ### Prisma
98
101
 
@@ -130,31 +133,37 @@ For pull requests, fetch the base branch first. Use `fetch-depth: 0` in GitHub A
130
133
 
131
134
  ## PostgreSQL migration rules
132
135
 
133
- | Rule | Detected pattern | Potential risk |
134
- |---|---|---|
135
- | **PG001** | CREATE INDEX without CONCURRENTLY | Blocks writes during index creation |
136
- | **PG002** | DROP COLUMN | Breaks older application versions |
137
- | **PG003** | ALTER COLUMN TYPE | Strong locks and possible table rewrites |
138
- | **PG004** | ADD COLUMN NOT NULL without DEFAULT | Backfill and compatibility risks |
139
- | **PG005** | ADD FOREIGN KEY without NOT VALID | Validation may block writes |
140
- | **PG006** | RENAME | Breaks applications expecting old names |
141
-
142
- Additional rule IDs in v2.0.0:
143
-
144
- | Rule | Detected pattern | Interpretation |
145
- |---|---|---|
146
- | **PG007** | DROP INDEX without CONCURRENTLY | Potential blocking |
147
- | **PG008** | CONCURRENTLY inside an explicit SQL transaction | PostgreSQL rejects this operation |
148
- | **PG010** | ADD UNIQUE constraint | Potential blocking index build |
149
- | **PG011** | DROP TABLE | Destructive change |
150
- | **PG012** | Validated CHECK constraint | May scan existing rows |
151
- | **PG013** | SET NOT NULL | Strong lock and potential scan |
152
- | **PG014** | ADD COLUMN with DEFAULT on PostgreSQL 10 | Version-specific rewrite risk |
153
- | **PG015** | Prisma CONCURRENTLY | Advisory: use a standalone migration; verified with Prisma 6.19.x `migrate deploy` |
154
- | **PG016** | Drizzle CONCURRENTLY | Advisory: tested Drizzle 0.44.x node-postgres migrator wraps migrations in a transaction, preventing this operation |
155
- | **PG017** | Cross-file rename/drop dependency | Heuristic advisory |
156
-
157
- PG009 is not implemented; rule identifiers are not contiguous. PG015–PG017 default to warnings, including when the standard global severity is `error`. Override an individual advisory with `rules.PG015`, `rules.PG016`, or `rules.PG017` in the configuration. `--fail-on error` only determines the CLI exit threshold, not rule classification.
136
+ The following rule identifiers are documented for CLI v2.6.0.
137
+
138
+ 23 catalog identifiers, including legacy PG013; PG009 and PG018 are unused. PG013 is suppressed when PG025 is emitted. PG019 and PG020 are triggered for a configured target version below 15; PG014 targets PostgreSQL 10. Defaults below describe CLI reporting, not raw engine metadata.
139
+
140
+ | ID | Diagnostic | Default | Guidance |
141
+ |---|---|---|---|
142
+ | PG001 | Non-concurrent index creation | error | Use CREATE INDEX CONCURRENTLY outside a transaction. |
143
+ | PG002 | Dropping a column | error | Deprecate consumers before removing the column. |
144
+ | PG003 | Changing a column type | error | Check binary compatibility; consider expand/backfill/contract. |
145
+ | PG004 | Adding NOT NULL column without default | error | Add nullable, backfill, then enforce NOT NULL. |
146
+ | PG005 | Adding validated foreign key | error | Add NOT VALID then VALIDATE CONSTRAINT separately. |
147
+ | PG006 | Renaming an object | error | Use an expand/contract deployment. |
148
+ | PG007 | Dropping index without CONCURRENTLY | error | Use DROP INDEX CONCURRENTLY where supported. |
149
+ | PG008 | Concurrent index operation inside transaction | error | Run outside BEGIN/COMMIT. |
150
+ | PG010 | Adding UNIQUE constraint | error | Consider a concurrent unique index and attach it where applicable. |
151
+ | PG011 | Dropping a table | error | Verify retention and application dependencies. |
152
+ | PG012 | Adding validated CHECK constraint | error | Add NOT VALID and validate separately. |
153
+ | PG013 | Legacy SET NOT NULL diagnostic (superseded by PG025) | error | Validate an equivalent CHECK constraint first. |
154
+ | PG014 | Adding column with default on PostgreSQL 10 | error | Use controlled backfill or evaluate upgrading PostgreSQL. |
155
+ | PG015 | Prisma concurrent index migration | warning | Use a separately managed nontransactional migration. |
156
+ | PG016 | Drizzle concurrent index migration | warning | Use a separately managed nontransactional migration. |
157
+ | PG017 | Potential cross-file dependency or Flyway transaction advisory | warning | Review migration order; this is a heuristic. |
158
+ | PG019 | MERGE requires PostgreSQL 15+ | error | Use a compatible INSERT ... ON CONFLICT pattern where applicable. |
159
+ | PG020 | UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+ | error | Use a version-compatible uniqueness strategy. |
160
+ | PG021 | Volatile default may rewrite table | error | Add column, backfill in batches, then set default. |
161
+ | PG022 | SET LOGGED rewrites table | error | Schedule controlled maintenance and evaluate alternatives. |
162
+ | PG023 | TRUNCATE removes table rows | error | Confirm retention, backups and downstream dependencies. |
163
+ | PG024 | Dropping a constraint | error | Review dependent queries and data-integrity requirements. |
164
+ | PG025 | SET NOT NULL may scan table | error | Backfill and validate a CHECK constraint first where appropriate. |
165
+
166
+ PG017 also covers Flyway nontransactional execution advice. Rules are configurable using `rules` with `off`, `warning`, or `error`. Static findings are not a downtime guarantee.
158
167
 
159
168
  Example configuration (`pg-safe-migrate.config.json`):
160
169
 
@@ -167,7 +176,7 @@ Example configuration (`pg-safe-migrate.config.json`):
167
176
  }
168
177
  ```
169
178
 
170
- Report options: `--format text|json|sarif`, `--output <file>`, `--advisor`, `--postgres-version <major>`, and `--fail-on warning|error|none`.
179
+ Report options: `--format text|json|sarif|markdown`, `--output <file>`, `--advisor`, `--postgres-version <major>`, and `--fail-on warning|error|none`.
171
180
 
172
181
  Each finding includes a description of the risk and a suggested safer migration approach.
173
182
 
@@ -187,12 +196,12 @@ The workflow checks changed SQL migrations so teams can adopt the linter without
187
196
 
188
197
  For reproducible builds, pin the package to a reviewed version and upgrade deliberately.
189
198
 
190
- ## Verify the published CLI
199
+ ## Verify CLI v2.6.0 after publication
191
200
 
192
201
  From a clean directory, run:
193
202
 
194
203
  ```bash
195
- npx --yes --package=@subodh001/pg-safe-migrate@2.4.0 pg-safe-migrate --help
204
+ npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate --help
196
205
  ```
197
206
 
198
207
  Create a file named `unsafe.sql`:
@@ -204,7 +213,7 @@ CREATE INDEX idx_users_email ON users(email);
204
213
  Then execute:
205
214
 
206
215
  ```bash
207
- npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate unsafe.sql
216
+ npx --yes --package=@subodh001/pg-safe-migrate@2.6.0 pg-safe-migrate unsafe.sql
208
217
  ```
209
218
 
210
219
  Expected behavior: PG001 is reported and the CLI exits with code `1`.
@@ -235,7 +244,7 @@ npm test
235
244
  Test the rule engine:
236
245
 
237
246
  ```bash
238
- node bin/cli.js test/unsafe_migration.sql
247
+ node bin/cli.js examples/unsafe.sql
239
248
  ```
240
249
 
241
250
  Check the npm package:
@@ -244,9 +253,9 @@ Check the npm package:
244
253
  npm pack --dry-run
245
254
  ```
246
255
 
247
- ## Current release
256
+ ## CLI v2.6.0
248
257
 
249
- **v2.0.0**
258
+ Version v2.6.0 adds improved SQL positions, transaction tracking and rule catalog metadata. See [CHANGELOG.md](CHANGELOG.md).
250
259
 
251
260
  - Expanded PostgreSQL migration risk checks and framework advisories
252
261
  - PostgreSQL AST-based parsing
@@ -261,20 +270,42 @@ npm pack --dry-run
261
270
 
262
271
  ## Limitations
263
272
 
264
- `pg-safe-migrate` is a static AST-based linter, not a migration execution simulator.
273
+ `pg-safe-migrate` is a static AST-based PostgreSQL migration linter. Static linting is not a migration execution simulator.
265
274
 
266
- It does not:
275
+ ### Parser and diagnostic capabilities
267
276
 
268
- - Connect to your production database
269
- - Estimate actual lock waiting times
270
- - Validate rollback procedures
271
- - Inspect live database schemas
272
- - Guarantee zero downtime
273
- - Analyze SQL embedded inside changed JavaScript or TypeScript files
277
+ Version v2.6.0 includes:
278
+
279
+ - Unicode-aware diagnostic positions with UTF-16 editor coordinates.
280
+ - Windows CRLF and Unix LF compatibility.
281
+ - Single-line and nested block comment handling.
282
+ - Dollar-quoted and escaped string handling.
283
+ - Explicit transaction tracking, including savepoints and chained transactions.
284
+ - PostgreSQL syntax error detection.
285
+
286
+ These parser improvements are included in v2.6.0. Large SQL inputs can consume substantial memory; static analysis has no hard process memory cap.
287
+
288
+ ### Static analysis boundaries
289
+
290
+ Static linting does not:
291
+
292
+ - Connect to your production database.
293
+ - Estimate actual lock waiting times.
294
+ - Validate rollback procedures.
295
+ - Inspect live database schemas.
296
+ - Comprehensively analyze SQL inside PL/pgSQL functions, stored procedures or anonymous DO blocks.
297
+ - Resolve dynamically generated SQL.
298
+ - Analyze SQL embedded inside JavaScript or TypeScript files.
299
+ - Detect every application-managed or ORM-managed transaction.
300
+ - Guarantee zero downtime or production migration safety.
274
301
 
275
302
  Some flagged operations may be acceptable under controlled conditions. Some unflagged operations may still cause downtime.
276
303
 
277
- Always consider PostgreSQL version, table size, transaction behavior, lock timeouts, long-running transactions, and application deployment sequencing.
304
+ Optional database inspection and disposable PostgreSQL simulation are separate capabilities with their own limitations.
305
+
306
+ Always consider PostgreSQL version, table size, transaction behavior, lock timeouts, long-running transactions and application deployment sequencing.
307
+
308
+ Validate migrations against a representative PostgreSQL environment before production deployment.
278
309
 
279
310
  ## Validation and real ORM runners
280
311
 
@@ -356,7 +387,7 @@ The directory mode processes only top-level `.sql` files (maximum 100); nested O
356
387
 
357
388
  ## Consolidated experimental development capabilities
358
389
 
359
- See [ALL-MILESTONES-TESTING.md](ALL-MILESTONES-TESTING.md) for exact commands and verification limitations. `--assess` combines lint findings, lock classifications, heuristic risk score, deployment advice, Docker execution, optional `--verify-sql` assertions, and optional `--team-policy` checks. The Docker matrix script covers PostgreSQL 14–18 when Docker is available. `vscode-extension/` is a local VS Code extension prototype; team policy is a local JSON configuration, **not** a hosted team management service.
390
+ See [ALL-MILESTONES-TESTING.md](ALL-MILESTONES-TESTING.md) for exact commands and verification limitations. `--assess` combines lint findings, lock classifications, heuristic risk score, deployment advice, Docker execution, optional `--verify-sql` assertions, and optional `--team-policy` checks. The Docker matrix script covers PostgreSQL 14–18 when Docker is available. `vscode-extension/` provides a standalone VS Code extension; team policy is a local JSON configuration, **not** a hosted team management service.
360
391
 
361
392
  ## Markdown migration report (Week 2 Day 6)
362
393
 
package/SECURITY.md ADDED
@@ -0,0 +1,13 @@
1
+ # Security policy
2
+
3
+ ## Reporting
4
+
5
+ Use the repository [private vulnerability reporting page](https://github.com/subodhsingh001/pg-safe-migrate/security/advisories/new) if enabled. If unavailable, request a private reporting channel through a public issue without disclosing exploit details, credentials or customer SQL. Include affected version, environment and a minimal sanitized reproduction.
6
+
7
+ ## Safety boundaries
8
+
9
+ Static linting does not execute migrations or guarantee downtime avoidance. Optional Docker simulation executes trusted SQL in disposable containers and is not a hostile-code sandbox. Database inspection requires least-privilege credentials. Do not submit secrets or production data. The extension file size and output limits are not hard process memory limits.
10
+
11
+ ## Support
12
+
13
+ No formal support lifetime or response SLA is promised. Use the latest reviewed release and report reproducible security issues.
package/docs/RULES.md ADDED
@@ -0,0 +1,31 @@
1
+ # Rule reference (development branch)
2
+
3
+ 23 catalog identifiers, including legacy PG013; PG009 and PG018 are unused. PG013 is suppressed when PG025 is emitted. PG019 and PG020 require a target version below 15; PG014 targets PostgreSQL 10. Defaults below describe CLI reporting, not raw engine metadata. Catalog `defaultSeverity` preserves raw rule metadata; `defaultCliSeverity` describes default CLI reporting. PG024 and PG025 are raw warnings but CLI errors by default.
4
+
5
+ | ID | Diagnostic | Default | Guidance |
6
+ |---|---|---|---|
7
+ | PG001 | Non-concurrent index creation | error | Use CREATE INDEX CONCURRENTLY outside a transaction. |
8
+ | PG002 | Dropping a column | error | Deprecate consumers before removing the column. |
9
+ | PG003 | Changing a column type | error | Check binary compatibility; consider expand/backfill/contract. |
10
+ | PG004 | Adding NOT NULL column without default | error | Add nullable, backfill, then enforce NOT NULL. |
11
+ | PG005 | Adding validated foreign key | error | Add NOT VALID then VALIDATE CONSTRAINT separately. |
12
+ | PG006 | Renaming an object | error | Use an expand/contract deployment. |
13
+ | PG007 | Dropping index without CONCURRENTLY | error | Use DROP INDEX CONCURRENTLY where supported. |
14
+ | PG008 | Concurrent index operation inside transaction | error | Run outside BEGIN/COMMIT. |
15
+ | PG010 | Adding UNIQUE constraint | error | Consider a concurrent unique index and attach it where applicable. |
16
+ | PG011 | Dropping a table | error | Verify retention and application dependencies. |
17
+ | PG012 | Adding validated CHECK constraint | error | Add NOT VALID and validate separately. |
18
+ | PG013 | Legacy SET NOT NULL diagnostic (superseded by PG025) | error | Validate an equivalent CHECK constraint first. |
19
+ | PG014 | Adding column with default on PostgreSQL 10 | error | Use controlled backfill or evaluate upgrading PostgreSQL. |
20
+ | PG015 | Prisma concurrent index migration | warning | Use a separately managed nontransactional migration. |
21
+ | PG016 | Drizzle concurrent index migration | warning | Use a separately managed nontransactional migration. |
22
+ | PG017 | Potential cross-file dependency or Flyway transaction advisory | warning | Review migration order; this is a heuristic. |
23
+ | PG019 | MERGE requires PostgreSQL 15+ | error | Use a compatible INSERT ... ON CONFLICT pattern where applicable. |
24
+ | PG020 | UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+ | error | Use a version-compatible uniqueness strategy. |
25
+ | PG021 | Volatile default may rewrite table | error | Add column, backfill in batches, then set default. |
26
+ | PG022 | SET LOGGED rewrites table | error | Schedule controlled maintenance and evaluate alternatives. |
27
+ | PG023 | TRUNCATE removes table rows | error | Confirm retention, backups and downstream dependencies. |
28
+ | PG024 | Dropping a constraint | error | Review dependent queries and data-integrity requirements. |
29
+ | PG025 | SET NOT NULL may scan table | error | Backfill and validate a CHECK constraint first where appropriate. |
30
+
31
+ PG017 also covers Flyway nontransactional execution advice. Rules are configurable using `rules` with `off`, `warning`, or `error`. Static findings are not a downtime guarantee.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@subodh001/pg-safe-migrate",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "description": "Detect risky PostgreSQL schema migrations before deployment: SQL linting, lock analysis, risk scoring and CI reports for Prisma, Drizzle and Flyway",
5
5
  "type": "module",
6
6
  "bin": {
@@ -52,7 +52,11 @@
52
52
  "scripts/orm-runner/package.json",
53
53
  "scripts/orm-runner/package-lock.json",
54
54
  "scripts/orm-runner/README.md",
55
- "ALL-MILESTONES-TESTING.md"
55
+ "ALL-MILESTONES-TESTING.md",
56
+ "CHANGELOG.md",
57
+ "SECURITY.md",
58
+ "CONTRIBUTING.md",
59
+ "docs/RULES.md"
56
60
  ],
57
61
  "repository": {
58
62
  "type": "git",
package/src/analysis.js CHANGED
@@ -1,4 +1,3 @@
1
-
2
1
  import { parseSqlFile } from './parser.js';
3
2
  import { lintStatements } from './engine.js';
4
3
  import { advise } from './advisor.js';
@@ -26,6 +25,46 @@ export function position(sql, offset = 0) {
26
25
  };
27
26
  }
28
27
 
28
+
29
+ function createPositionTracker(sql) {
30
+ const source = String(sql ?? '');
31
+
32
+ let cursor = 0;
33
+ let line = 1;
34
+ let lineStart = 0;
35
+
36
+ return function locate(offset = 0) {
37
+ const numericOffset = Number(offset);
38
+
39
+ const safeOffset = Number.isFinite(numericOffset)
40
+ ? Math.min(
41
+ source.length,
42
+ Math.max(0, Math.floor(numericOffset))
43
+ )
44
+ : 0;
45
+
46
+ // Preserve correctness if offsets arrive out of order.
47
+ if (safeOffset < cursor) {
48
+ return position(source, safeOffset);
49
+ }
50
+
51
+ while (cursor < safeOffset) {
52
+ if (source.charCodeAt(cursor) === 10) {
53
+ line++;
54
+ lineStart = cursor + 1;
55
+ }
56
+
57
+ cursor++;
58
+ }
59
+
60
+ return {
61
+ line,
62
+ column: safeOffset - lineStart + 1
63
+ };
64
+ };
65
+ }
66
+
67
+
29
68
  export function frameworkFor(file) {
30
69
  const p = file.replaceAll('\\', '/').toLowerCase();
31
70
 
@@ -57,7 +96,6 @@ function txType(stmt) {
57
96
  if ([
58
97
  'TRANS_STMT_COMMIT',
59
98
  'TRANS_STMT_ROLLBACK',
60
- 'TRANS_STMT_ROLLBACK_TO',
61
99
  'TRANS_STMT_PREPARE'
62
100
  ].includes(kind)) {
63
101
  return 'end';
@@ -185,11 +223,12 @@ export async function analyzeFiles(
185
223
  });
186
224
 
187
225
  const framework = frameworkFor(file);
226
+ const locate = createPositionTracker(sql);
188
227
 
189
228
  let inTransaction = false;
190
229
 
191
230
  for (const { stmt, offset } of parsed) {
192
- const loc = position(sql, offset);
231
+ const loc = locate(offset);
193
232
  const transaction = txType(stmt);
194
233
 
195
234
  // Track explicit transaction boundaries.
@@ -339,7 +378,7 @@ export async function analyzeFiles(
339
378
 
340
379
  // Close the explicit transaction after processing.
341
380
  if (transaction === 'end') {
342
- inTransaction = false;
381
+ inTransaction = Boolean(stmt.TransactionStmt?.chain);
343
382
  }
344
383
  }
345
384
  }
package/src/locks.js CHANGED
@@ -1,18 +1,134 @@
1
- // Conservative PostgreSQL table-lock inventory. These are planning hints, not
2
- // predictions of wait time, lock duration, or production downtime.
1
+
2
+ // PostgreSQL table-lock planning hints.
3
+ // These are not predictions of wait time, duration, or downtime.
4
+
3
5
  function assessment(mode, impact, note, confidence = 'heuristic') {
4
6
  return { mode, confidence, impact, note };
5
7
  }
6
8
 
9
+ function alterTableLock(alter) {
10
+ const commands = (alter.cmds || [])
11
+ .map(wrapper => wrapper.AlterTableCmd)
12
+ .filter(Boolean);
13
+
14
+ // A statement may contain multiple subcommands.
15
+ // Do not classify a mixed statement using only its weakest lock.
16
+ if (commands.length === 0) {
17
+ return assessment(
18
+ 'ACCESS EXCLUSIVE',
19
+ 'reads-and-writes',
20
+ 'ALTER TABLE lock requirements depend on its subcommands.'
21
+ );
22
+ }
23
+
24
+ const modes = commands.map(cmd => {
25
+ if (
26
+ cmd.subtype === 'AT_AddConstraint' &&
27
+ cmd.def?.Constraint?.contype === 'CONSTR_FOREIGN'
28
+ ) {
29
+ return 'SHARE ROW EXCLUSIVE';
30
+ }
31
+
32
+ if (cmd.subtype === 'AT_ValidateConstraint') {
33
+ return 'SHARE UPDATE EXCLUSIVE';
34
+ }
35
+
36
+ return 'ACCESS EXCLUSIVE';
37
+ });
38
+
39
+ if (modes.every(mode => mode === 'SHARE ROW EXCLUSIVE')) {
40
+ return assessment(
41
+ 'SHARE ROW EXCLUSIVE',
42
+ 'writes',
43
+ 'ADD FOREIGN KEY acquires SHARE ROW EXCLUSIVE on both referencing and referenced tables. NOT VALID avoids the initial scan but not the lock.',
44
+ 'documented'
45
+ );
46
+ }
47
+
48
+ if (modes.every(mode => mode === 'SHARE UPDATE EXCLUSIVE')) {
49
+ return assessment(
50
+ 'SHARE UPDATE EXCLUSIVE',
51
+ 'ddl-and-maintenance',
52
+ 'VALIDATE CONSTRAINT generally uses SHARE UPDATE EXCLUSIVE on the altered table. Foreign-key validation can also lock the referenced table.',
53
+ 'documented'
54
+ );
55
+ }
56
+
57
+ return assessment(
58
+ 'ACCESS EXCLUSIVE',
59
+ 'reads-and-writes',
60
+ 'ALTER TABLE contains a subcommand requiring ACCESS EXCLUSIVE, or a subcommand whose lock has not been specifically classified.'
61
+ );
62
+ }
63
+
7
64
  export function lockFor(stmt) {
8
- if (stmt.TruncateStmt) return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'TRUNCATE acquires ACCESS EXCLUSIVE on affected tables and can block readers and writers.', 'documented');
9
- if (stmt.AlterTableStmt) return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'ALTER TABLE generally acquires ACCESS EXCLUSIVE; some subcommands use weaker locks. Check the specific operation.');
10
- if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'DROP TABLE requires ACCESS EXCLUSIVE on the target table.', 'documented');
11
- if (stmt.RenameStmt) return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'Rename operations can require strong locks; verify the specific object and operation.');
12
- if (stmt.IndexStmt) return stmt.IndexStmt.concurrent
13
- ? assessment('SHARE UPDATE EXCLUSIVE', 'ddl-and-maintenance', 'CREATE INDEX CONCURRENTLY permits ordinary writes but can wait for transactions and conflicts with some maintenance.', 'documented')
14
- : assessment('SHARE', 'writes', 'CREATE INDEX without CONCURRENTLY can block writes while the index is built.', 'documented');
15
- if (stmt.VacuumStmt) return assessment('SHARE UPDATE EXCLUSIVE', 'ddl-and-maintenance', 'Ordinary VACUUM uses SHARE UPDATE EXCLUSIVE; VACUUM FULL uses ACCESS EXCLUSIVE. Verify the options.');
16
- if (stmt.UpdateStmt || stmt.DeleteStmt || stmt.InsertStmt) return assessment('ROW EXCLUSIVE', 'conflicting-writers-and-ddl', 'DML acquires ROW EXCLUSIVE table locks; row-level contention and execution time are not assessed.', 'documented');
17
- return assessment('unknown', 'unknown', 'Lock mode not classified; do not assume this operation is lock-free.', 'unknown');
65
+ if (stmt.TruncateStmt) {
66
+ return assessment(
67
+ 'ACCESS EXCLUSIVE',
68
+ 'reads-and-writes',
69
+ 'TRUNCATE acquires ACCESS EXCLUSIVE on affected tables and can block readers and writers.',
70
+ 'documented'
71
+ );
72
+ }
73
+
74
+ if (stmt.AlterTableStmt) {
75
+ return alterTableLock(stmt.AlterTableStmt);
76
+ }
77
+
78
+ if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') {
79
+ return assessment(
80
+ 'ACCESS EXCLUSIVE',
81
+ 'reads-and-writes',
82
+ 'DROP TABLE requires ACCESS EXCLUSIVE on the target table.',
83
+ 'documented'
84
+ );
85
+ }
86
+
87
+ if (stmt.RenameStmt) {
88
+ return assessment(
89
+ 'ACCESS EXCLUSIVE',
90
+ 'reads-and-writes',
91
+ 'Rename operations can require strong locks; verify the specific object and operation.'
92
+ );
93
+ }
94
+
95
+ if (stmt.IndexStmt) {
96
+ return stmt.IndexStmt.concurrent
97
+ ? assessment(
98
+ 'SHARE UPDATE EXCLUSIVE',
99
+ 'ddl-and-maintenance',
100
+ 'CREATE INDEX CONCURRENTLY permits ordinary writes but can wait for transactions and conflict with some maintenance.',
101
+ 'documented'
102
+ )
103
+ : assessment(
104
+ 'SHARE',
105
+ 'writes',
106
+ 'CREATE INDEX without CONCURRENTLY can block writes while the index is built.',
107
+ 'documented'
108
+ );
109
+ }
110
+
111
+ if (stmt.VacuumStmt) {
112
+ return assessment(
113
+ 'SHARE UPDATE EXCLUSIVE',
114
+ 'ddl-and-maintenance',
115
+ 'Ordinary VACUUM uses SHARE UPDATE EXCLUSIVE; VACUUM FULL uses ACCESS EXCLUSIVE. Verify the options.'
116
+ );
117
+ }
118
+
119
+ if (stmt.UpdateStmt || stmt.DeleteStmt || stmt.InsertStmt) {
120
+ return assessment(
121
+ 'ROW EXCLUSIVE',
122
+ 'conflicting-writers-and-ddl',
123
+ 'DML acquires ROW EXCLUSIVE table locks; row-level contention and execution time are not assessed.',
124
+ 'documented'
125
+ );
126
+ }
127
+
128
+ return assessment(
129
+ 'unknown',
130
+ 'unknown',
131
+ 'Lock mode not classified; do not assume this operation is lock-free.',
132
+ 'unknown'
133
+ );
18
134
  }
package/src/parser.js CHANGED
@@ -1,4 +1,3 @@
1
-
2
1
  import pgQuery from 'libpg-query';
3
2
 
4
3
  export async function parseSqlFile(sqlContent, options = {}) {
@@ -16,6 +15,22 @@ export async function parseSqlFile(sqlContent, options = {}) {
16
15
 
17
16
  const source = String(sqlContent);
18
17
 
18
+ // Convert ordered PostgreSQL UTF-8 byte locations to UTF-16 offsets.
19
+ const byteLength = Buffer.byteLength(source);
20
+ let byteCursor = 0;
21
+ let charCursor = 0;
22
+ function locateByte(target) {
23
+ if (target < byteCursor) { byteCursor = 0; charCursor = 0; }
24
+ while (byteCursor < target && charCursor < source.length) {
25
+ const cp = source.codePointAt(charCursor);
26
+ const width = cp <= 0x7f ? 1 : cp <= 0x7ff ? 2 : cp <= 0xffff ? 3 : 4;
27
+ if (byteCursor + width > target) break;
28
+ byteCursor += width;
29
+ charCursor += cp > 0xffff ? 2 : 1;
30
+ }
31
+ return charCursor;
32
+ }
33
+
19
34
  return statements.map(s => {
20
35
  let offset =
21
36
  typeof s.stmt_location === 'number'
@@ -24,17 +39,38 @@ export async function parseSqlFile(sqlContent, options = {}) {
24
39
 
25
40
  offset = Math.max(
26
41
  0,
27
- Math.min(offset, source.length)
42
+ Math.min(offset, byteLength)
28
43
  );
29
44
 
30
- // PostgreSQL may report the beginning of the
31
- // statement span before leading whitespace.
32
- // Advance to the first non-whitespace character.
33
- while (
34
- offset < source.length &&
35
- /\s/.test(source[offset])
36
- ) {
37
- offset++;
45
+ offset = locateByte(offset);
46
+
47
+ // Skip only leading SQL trivia, never statement contents.
48
+ while (offset < source.length) {
49
+ if (/[ \t\r\n\f\v]/.test(source[offset])) {
50
+ offset++;
51
+ } else if (source.startsWith('--', offset)) {
52
+ offset += 2;
53
+ while (offset < source.length &&
54
+ source[offset] !== '\n' && source[offset] !== '\r') {
55
+ offset++;
56
+ }
57
+ } else if (source.startsWith('/*', offset)) {
58
+ offset += 2;
59
+ let depth = 1;
60
+ while (offset < source.length && depth > 0) {
61
+ if (source.startsWith('/*', offset)) {
62
+ depth++;
63
+ offset += 2;
64
+ } else if (source.startsWith('*/', offset)) {
65
+ depth--;
66
+ offset += 2;
67
+ } else {
68
+ offset++;
69
+ }
70
+ }
71
+ } else {
72
+ break;
73
+ }
38
74
  }
39
75
 
40
76
  return {
@@ -8,10 +8,14 @@ const definitions = [
8
8
  ['PG006','Renaming an object','compatibility','ERROR',null,'Use an expand/contract deployment.'],
9
9
  ['PG007','Dropping index without CONCURRENTLY','locking','ERROR',null,'Use DROP INDEX CONCURRENTLY where supported.'],
10
10
  ['PG008','Concurrent index operation inside transaction','compatibility','ERROR',null,'Run outside BEGIN/COMMIT.'],
11
+ ['PG010','Adding UNIQUE constraint','locking','ERROR',null,'Consider a concurrent unique index and attach it where applicable.'],
11
12
  ['PG011','Dropping a table','data-loss','ERROR',null,'Verify retention and application dependencies.'],
13
+ ['PG012','Adding validated CHECK constraint','constraint','ERROR',null,'Add NOT VALID and validate separately.'],
14
+ ['PG013','Legacy SET NOT NULL diagnostic (superseded by PG025)','constraint','ERROR',null,'Validate an equivalent CHECK constraint first.'],
15
+ ['PG014','Adding column with default on PostgreSQL 10','rewrite','ERROR',null,'Use controlled backfill or evaluate upgrading PostgreSQL.'],
12
16
  ['PG015','Prisma concurrent index migration','integration','WARNING',null,'Use a separately managed nontransactional migration.'],
13
17
  ['PG016','Drizzle concurrent index migration','integration','WARNING',null,'Use a separately managed nontransactional migration.'],
14
- ['PG017','Potential cross-file dependency','dependency','WARNING',null,'Review migration order; this is a heuristic.'],
18
+ ['PG017','Potential cross-file dependency or Flyway transaction advisory','dependency','WARNING',null,'Review migration order; this is a heuristic.'],
15
19
  ['PG019','MERGE requires PostgreSQL 15+','version','ERROR',15,'Use a compatible INSERT ... ON CONFLICT pattern where applicable.'],
16
20
  ['PG020','UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+','version','ERROR',15,'Use a version-compatible uniqueness strategy.'],
17
21
  ['PG021','Volatile default may rewrite table','rewrite','ERROR',null,'Add column, backfill in batches, then set default.'],
@@ -21,7 +25,7 @@ const definitions = [
21
25
  ['PG025','SET NOT NULL may scan table','constraint','WARNING',null,'Backfill and validate a CHECK constraint first where appropriate.']
22
26
  ];
23
27
 
24
- export const RULE_CATALOG = Object.freeze(definitions.map(([id,title,category,defaultSeverity,minPostgresVersion,recommendation]) => Object.freeze({id,title,category,defaultSeverity,minPostgresVersion,recommendation})));
28
+ export const RULE_CATALOG = Object.freeze(definitions.map(([id,title,category,defaultSeverity,minPostgresVersion,recommendation]) => Object.freeze({id,title,category,defaultSeverity,defaultCliSeverity: ['PG024','PG025'].includes(id) ? 'ERROR' : defaultSeverity,minPostgresVersion,recommendation})));
25
29
 
26
30
  export function getRule(id) {
27
31
  return RULE_CATALOG.find(rule => rule.id === String(id).toUpperCase()) ?? null;