@pgsql/lint 18.1.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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -0
  3. package/cli.d.ts +12 -0
  4. package/cli.js +130 -0
  5. package/engine.d.ts +30 -0
  6. package/engine.js +66 -0
  7. package/esm/cli.js +125 -0
  8. package/esm/engine.js +62 -0
  9. package/esm/file-runner.js +221 -0
  10. package/esm/index.js +19 -0
  11. package/esm/linter.js +36 -0
  12. package/esm/parse-unit.js +170 -0
  13. package/esm/rules/index.js +14 -0
  14. package/esm/rules/no-dynamic-sql.js +26 -0
  15. package/esm/rules/no-set-search-path.js +64 -0
  16. package/esm/rules/no-variable-conflict.js +36 -0
  17. package/esm/rules/require-qualified-refs.js +68 -0
  18. package/esm/suppressions.js +131 -0
  19. package/esm/types.js +23 -0
  20. package/esm/util.js +9 -0
  21. package/esm/walk.js +14 -0
  22. package/file-runner.d.ts +68 -0
  23. package/file-runner.js +263 -0
  24. package/index.d.ts +22 -0
  25. package/index.js +43 -0
  26. package/linter.d.ts +51 -0
  27. package/linter.js +41 -0
  28. package/package.json +60 -0
  29. package/parse-unit.d.ts +17 -0
  30. package/parse-unit.js +173 -0
  31. package/rules/index.d.ts +10 -0
  32. package/rules/index.js +20 -0
  33. package/rules/no-dynamic-sql.d.ts +13 -0
  34. package/rules/no-dynamic-sql.js +29 -0
  35. package/rules/no-set-search-path.d.ts +12 -0
  36. package/rules/no-set-search-path.js +67 -0
  37. package/rules/no-variable-conflict.d.ts +12 -0
  38. package/rules/no-variable-conflict.js +39 -0
  39. package/rules/require-qualified-refs.d.ts +16 -0
  40. package/rules/require-qualified-refs.js +71 -0
  41. package/suppressions.d.ts +49 -0
  42. package/suppressions.js +135 -0
  43. package/types.d.ts +142 -0
  44. package/types.js +26 -0
  45. package/util.d.ts +2 -0
  46. package/util.js +12 -0
  47. package/walk.d.ts +5 -0
  48. package/walk.js +17 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Dan Lynch <pyramation@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,150 @@
1
+ # @pgsql/lint
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/pgsql-parser/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/pgsql-parser/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/pgsql-parser/blob/main/LICENSE-MIT"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/@pgsql/lint"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/pgsql-parser?filename=packages%2Flint%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ A source-level SQL / PL/pgSQL **convention linter**. It reasons about the *text*
16
+ of a `CREATE FUNCTION` definition — from its AST — and carries **no `pg` /
17
+ catalog dependency**, so the exact same engine runs over a definition in a
18
+ migration, an editor buffer, a pre-commit hook, or one read from a live catalog
19
+ via `pg_get_functiondef`.
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install @pgsql/lint
25
+ ```
26
+
27
+ ## Rules
28
+
29
+ | Code | Id | Flags |
30
+ |------|----|-------|
31
+ | `C1` | `no-set-search-path` | `SET search_path` clause, or `set_config('search_path', …)` |
32
+ | `C2` | `no-variable-conflict` | a PL/pgSQL `#variable_conflict` directive |
33
+ | `C3` | `require-qualified-refs` | an unqualified relation reference (`FROM users` → `FROM app_public.users`) |
34
+ | `C4` | `no-dynamic-sql` | `EXECUTE`, `EXECUTE … USING`, `FOR … IN EXECUTE` |
35
+
36
+ The rules encode a single discipline: never depend on `search_path` — fully
37
+ qualify everything (`C1` + `C3`) — don't paper over ambiguity (`C2`), and treat
38
+ dynamic SQL as opaque and exceptional (`C4`).
39
+
40
+ ## CLI
41
+
42
+ ```bash
43
+ pgsql-lint path/to/migrations # a directory (scanned recursively for .sql)
44
+ pgsql-lint schema.sql other.sql # explicit files
45
+ pgsql-lint . --rules no-dynamic-sql # only some rules
46
+ pgsql-lint . --warn require-qualified-refs # downgrade to a warning (won't fail)
47
+ pgsql-lint . --off C2 # disable a rule (by id or code)
48
+ pgsql-lint . --json # machine-readable
49
+ ```
50
+
51
+ Exit code is `1` when any **error**-severity (and non-waived) finding remains,
52
+ `0` otherwise — drop it straight into CI. `--warn` findings print but don't fail.
53
+
54
+ ## Suppressions
55
+
56
+ ESLint / Prettier-style comments, authored in the function body (they survive
57
+ `pg_get_functiondef`). The keyword is `pgsql-lint` (`safegres` is also accepted):
58
+
59
+ ```sql
60
+ -- pgsql-lint-disable-next-line no-dynamic-sql -- lookup-only: building an IN-list of ints
61
+ EXECUTE format('SELECT … WHERE id = ANY(%L)', ids);
62
+ ```
63
+
64
+ Forms: `disable-next-line`, `disable-line`, `disable` … `enable` (a range), and
65
+ `disable-file`. A directive with no rule listed applies to every rule; a reason
66
+ follows a second `--` or a `:`.
67
+
68
+ `no-dynamic-sql` **requires** a reason: a reasonless waiver does not silence it,
69
+ so an approved use always documents *why* (`lookup-only` / `codegen`). Suppressed
70
+ findings are reported as *acknowledged* accepted-risk, never dropped.
71
+
72
+ ## Programmatic API
73
+
74
+ ```ts
75
+ import { lintDefinition, lintFiles, lintSqlText } from '@pgsql/lint';
76
+
77
+ // one definition (e.g. from pg_get_functiondef)
78
+ const { problems, suppressed } = await lintDefinition(defText, 'plpgsql');
79
+
80
+ // a SQL source string with many statements
81
+ const report = await lintSqlText(migrationSql);
82
+
83
+ // files / directories on disk
84
+ const reports = await lintFiles(['./migrations']);
85
+ ```
86
+
87
+ ## Custom rules & severity (building an ecosystem)
88
+
89
+ Rules are **injected as values** — never discovered by a magic npm package name.
90
+ A rule is a plain object; publish it, `import` it, and pass it to `createLinter`.
91
+ Severity is *configuration* (ESLint-style `off` / `warn` / `error`), keyed by
92
+ rule id or code, so a consumer stays in full control of how loud each rule is:
93
+
94
+ ```ts
95
+ import { createLinter, defineRule, LINT_RULES } from '@pgsql/lint';
96
+
97
+ const noWritesInView = defineRule({
98
+ id: 'no-writes-in-view',
99
+ code: 'X1',
100
+ title: 'views must be read-only',
101
+ reasonRequired: false,
102
+ run: (unit) => [/* … inspect unit.fragments / unit.dynamicSql … */]
103
+ });
104
+
105
+ const linter = createLinter({
106
+ rules: [...LINT_RULES, noWritesInView],
107
+ severity: { 'require-qualified-refs': 'warn', C2: 'off' }
108
+ });
109
+
110
+ await linter.lintFiles(['./migrations']); // also lintDefinition / lintSqlText / lintSource
111
+ ```
112
+
113
+ ### Source adapters
114
+
115
+ Rules are pure `unit → problems`; an **adapter** decides *where* the definitions
116
+ come from. `@pgsql/lint` ships `filesAdapter` and `sqlTextAdapter`; a consumer
117
+ (e.g. safegres, reading a live catalog via `pg_get_functiondef`) implements the
118
+ `SourceAdapter` interface and passes it to `linter.lintSource(adapter)`.
119
+
120
+ ```ts
121
+ interface SourceAdapter {
122
+ id: string;
123
+ definitions: () => Promise<LintDefinitionInput[]> | LintDefinitionInput[];
124
+ }
125
+ ```
126
+
127
+ ---
128
+
129
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
130
+
131
+ ## Related
132
+
133
+ * [pgpm](https://pgpm.dev): A Postgres Package Manager that brings modular development to PostgreSQL with reusable packages, deterministic migrations, recursive dependency resolution, and tag-aware versioning.
134
+ * [pgsql-test](https://www.npmjs.com/package/pgsql-test): Instant, isolated PostgreSQL databases for each test with automatic transaction rollbacks, context switching, and clean seeding for fast, reliable database testing.
135
+ * [pgsql-seed](https://www.npmjs.com/package/pgsql-seed): PostgreSQL seeding utilities for CSV, JSON, SQL data loading, and pgpm deployment.
136
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): The real PostgreSQL parser for Node.js, providing symmetric parsing and deparsing of SQL statements with actual PostgreSQL parser integration.
137
+ * [pgsql-deparser](https://www.npmjs.com/package/pgsql-deparser): A streamlined tool designed for converting PostgreSQL ASTs back into SQL queries, focusing solely on deparser functionality to complement `pgsql-parser`.
138
+ * [@pgsql/parser](https://www.npmjs.com/package/@pgsql/parser): Multi-version PostgreSQL parser with dynamic version selection at runtime, supporting PostgreSQL 15, 16, and 17 in a single package.
139
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): Offers TypeScript type definitions for PostgreSQL AST nodes, facilitating type-safe construction, analysis, and manipulation of ASTs.
140
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): Provides TypeScript enum definitions for PostgreSQL constants, enabling type-safe usage of PostgreSQL enums and constants in your applications.
141
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): A comprehensive utility library for PostgreSQL, offering type-safe AST node creation and enum value conversions, simplifying the construction and manipulation of PostgreSQL ASTs.
142
+ * [@pgsql/traverse](https://www.npmjs.com/package/@pgsql/traverse): PostgreSQL AST traversal utilities for pgsql-parser, providing a visitor pattern for traversing PostgreSQL Abstract Syntax Tree nodes, similar to Babel's traverse functionality but specifically designed for PostgreSQL AST structures.
143
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): A TypeScript tool that parses PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
144
+ * [libpg-query](https://github.com/constructive-io/libpg-query-node): The real PostgreSQL parser exposed for Node.js, used primarily in `pgsql-parser` for parsing and deparsing SQL queries.
145
+
146
+ ## Disclaimer
147
+
148
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
149
+
150
+ No developer or entity involved in creating Software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the Software code or Software CLI, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/cli.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `pgsql-lint` — lint SQL source files for the convention rules.
4
+ *
5
+ * pgsql-lint <path…> [--rules a,b] [--warn a,b] [--off a,b] [--json] [--quiet]
6
+ *
7
+ * Paths may be files or directories (directories are scanned recursively for
8
+ * `.sql`). Exit code is 1 when any *error*-severity finding remains, 0
9
+ * otherwise — so it drops straight into a pre-commit hook or CI step. Findings
10
+ * downgraded with `--warn` print but never fail the run.
11
+ */
12
+ export {};
package/cli.js ADDED
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * `pgsql-lint` — lint SQL source files for the convention rules.
5
+ *
6
+ * pgsql-lint <path…> [--rules a,b] [--warn a,b] [--off a,b] [--json] [--quiet]
7
+ *
8
+ * Paths may be files or directories (directories are scanned recursively for
9
+ * `.sql`). Exit code is 1 when any *error*-severity finding remains, 0
10
+ * otherwise — so it drops straight into a pre-commit hook or CI step. Findings
11
+ * downgraded with `--warn` print but never fail the run.
12
+ */
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ const chalk_1 = __importDefault(require("chalk"));
18
+ const minimist_1 = __importDefault(require("minimist"));
19
+ const file_runner_1 = require("./file-runner");
20
+ const rules_1 = require("./rules");
21
+ const HELP = `pgsql-lint — source-level SQL/PL/pgSQL convention linter
22
+
23
+ Usage:
24
+ pgsql-lint <path...> [options]
25
+
26
+ Arguments:
27
+ path One or more .sql files or directories (scanned recursively).
28
+
29
+ Options:
30
+ --rules <ids> Comma-separated rule ids/codes to run (default: all).
31
+ --warn <ids> Report these rules as warnings (do not fail the run).
32
+ --off <ids> Disable these rules entirely.
33
+ --keyword <kw> Suppression directive keyword (default: pgsql-lint,safegres).
34
+ --json Emit findings as JSON.
35
+ --quiet Only print active findings (hide acknowledged waivers).
36
+ -h, --help Show this help.
37
+ -v, --version Show version.
38
+
39
+ Rules:
40
+ ${rules_1.LINT_RULES.map((r) => ` ${r.code} ${r.id} — ${r.title}`).join('\n')}
41
+
42
+ Suppress inline (in the function body):
43
+ -- pgsql-lint-disable-next-line no-dynamic-sql -- lookup-only: <why>
44
+ `;
45
+ function csv(v) {
46
+ if (!v)
47
+ return undefined;
48
+ const parts = v.split(',').map((s) => s.trim()).filter(Boolean);
49
+ return parts.length > 0 ? parts : undefined;
50
+ }
51
+ async function main() {
52
+ const argv = (0, minimist_1.default)(process.argv.slice(2), {
53
+ boolean: ['json', 'quiet', 'help', 'version'],
54
+ string: ['rules', 'warn', 'off', 'keyword'],
55
+ alias: { h: 'help', v: 'version' }
56
+ });
57
+ if (argv.version) {
58
+ console.log(require('../package.json').version);
59
+ return;
60
+ }
61
+ if (argv.help || argv._.length === 0) {
62
+ console.log(HELP);
63
+ process.exit(argv._.length === 0 && !argv.help ? 1 : 0);
64
+ }
65
+ const rules = csv(argv.rules);
66
+ const keyword = csv(argv.keyword);
67
+ const severity = {};
68
+ for (const id of csv(argv.warn) ?? [])
69
+ severity[id] = 'warn';
70
+ for (const id of csv(argv.off) ?? [])
71
+ severity[id] = 'off';
72
+ const reports = await (0, file_runner_1.lintFiles)(argv._, { rules, keyword, severity });
73
+ if (argv.json) {
74
+ console.log(JSON.stringify(reports, null, 2));
75
+ }
76
+ let errors = 0;
77
+ let warnings = 0;
78
+ let acknowledged = 0;
79
+ for (const report of reports) {
80
+ if (report.parseError) {
81
+ if (!argv.json)
82
+ console.error(chalk_1.default.yellow(`⚠ ${report.file}: ${report.parseError}`));
83
+ continue;
84
+ }
85
+ const shown = report.findings.filter((f) => !f.acknowledged || !argv.quiet);
86
+ if (!argv.json && shown.length > 0) {
87
+ console.log(chalk_1.default.underline(report.file));
88
+ for (const f of shown)
89
+ console.log(formatFinding(f));
90
+ console.log('');
91
+ }
92
+ for (const f of report.findings) {
93
+ if (f.acknowledged)
94
+ acknowledged++;
95
+ else if (f.severity === 'warn')
96
+ warnings++;
97
+ else
98
+ errors++;
99
+ }
100
+ }
101
+ if (!argv.json) {
102
+ const parts = [];
103
+ parts.push(errors > 0 ? chalk_1.default.red(`${errors} error${errors === 1 ? '' : 's'}`) : chalk_1.default.green('0 errors'));
104
+ if (warnings > 0)
105
+ parts.push(chalk_1.default.yellow(`${warnings} warning${warnings === 1 ? '' : 's'}`));
106
+ if (acknowledged > 0)
107
+ parts.push(chalk_1.default.gray(`${acknowledged} acknowledged`));
108
+ console.log(parts.join(chalk_1.default.gray(', ')));
109
+ }
110
+ process.exit(errors > 0 ? 1 : 0);
111
+ }
112
+ function formatFinding(f) {
113
+ const loc = chalk_1.default.gray(`${String(f.line).padStart(4)}`);
114
+ const tag = f.acknowledged
115
+ ? chalk_1.default.gray('acknowledged')
116
+ : f.severity === 'warn'
117
+ ? chalk_1.default.yellow(`${f.code} warn`)
118
+ : chalk_1.default.red(`${f.code} error`);
119
+ const id = chalk_1.default.gray(f.ruleId);
120
+ let line = ` ${loc} ${tag} ${f.message} ${id} ${chalk_1.default.gray(f.subject)}`;
121
+ if (f.acknowledged && f.reason)
122
+ line += `\n ${chalk_1.default.gray(`↳ waived (${f.scope}): ${f.reason}`)}`;
123
+ else if (f.hint)
124
+ line += `\n ${chalk_1.default.gray(`↳ ${f.hint}`)}`;
125
+ return line;
126
+ }
127
+ main().catch((err) => {
128
+ console.error(chalk_1.default.red('Error:'), err.message || err);
129
+ process.exit(2);
130
+ });
package/engine.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The lint engine: parse a definition, run the rules, then apply suppressions.
3
+ * Pure `source → result`, with no `pg` dependency, so it can be unit-tested on
4
+ * string literals and embedded anywhere.
5
+ *
6
+ * Rules and their severities are *injected*, never discovered by name: you pass
7
+ * the rule objects in (see `createLinter`), so a third-party rule ships as an
8
+ * ordinary import, not a magic `pgsql-lint-plugin-*` package.
9
+ */
10
+ import type { LintResult, LintRule, Severity, SeverityMap } from './types';
11
+ export interface LintOptions {
12
+ /** Restrict to these rule ids/codes; omit to run every rule in the set. */
13
+ rules?: string[];
14
+ /**
15
+ * The rule set to draw from. Defaults to the built-ins. Pass your own array
16
+ * (built-ins spread in plus custom rules) to extend the linter.
17
+ */
18
+ ruleSet?: LintRule[];
19
+ /** Per-rule severity, keyed by id or code. Unmapped rules default to `error`. */
20
+ severity?: SeverityMap;
21
+ /**
22
+ * Directive keyword(s) recognised in suppression comments. Defaults to
23
+ * `['pgsql-lint', 'safegres']`.
24
+ */
25
+ keyword?: string | string[];
26
+ }
27
+ /** Resolve a rule's configured severity (id wins over code; default `error`). */
28
+ export declare function severityOf(rule: LintRule, severity?: SeverityMap): Severity;
29
+ /** Lint a single function definition. */
30
+ export declare function lintDefinition(text: string, language: string, name?: string, options?: LintOptions): Promise<LintResult>;
package/engine.js ADDED
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ /**
3
+ * The lint engine: parse a definition, run the rules, then apply suppressions.
4
+ * Pure `source → result`, with no `pg` dependency, so it can be unit-tested on
5
+ * string literals and embedded anywhere.
6
+ *
7
+ * Rules and their severities are *injected*, never discovered by name: you pass
8
+ * the rule objects in (see `createLinter`), so a third-party rule ships as an
9
+ * ordinary import, not a magic `pgsql-lint-plugin-*` package.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.severityOf = severityOf;
13
+ exports.lintDefinition = lintDefinition;
14
+ const parse_unit_1 = require("./parse-unit");
15
+ const rules_1 = require("./rules");
16
+ const suppressions_1 = require("./suppressions");
17
+ /** Resolve a rule's configured severity (id wins over code; default `error`). */
18
+ function severityOf(rule, severity = {}) {
19
+ return severity[rule.id] ?? severity[rule.code] ?? 'error';
20
+ }
21
+ /** Lint a single function definition. */
22
+ async function lintDefinition(text, language, name, options = {}) {
23
+ const active = [];
24
+ const suppressed = [];
25
+ const severity = options.severity ?? {};
26
+ let selected = options.ruleSet ?? rules_1.LINT_RULES;
27
+ if (options.rules) {
28
+ const wanted = new Set(options.rules);
29
+ selected = selected.filter((r) => wanted.has(r.id) || wanted.has(r.code));
30
+ }
31
+ // `off` rules never run.
32
+ selected = selected.filter((r) => severityOf(r, severity) !== 'off');
33
+ if (selected.length === 0)
34
+ return { problems: active, suppressed };
35
+ const unit = await (0, parse_unit_1.parseUnit)(text, language, name);
36
+ // An unparseable definition produces no lint findings — dynamic/opaque bodies
37
+ // are a downstream concern (e.g. a call-graph), not the linter's.
38
+ if (unit.parseError)
39
+ return { problems: active, suppressed };
40
+ const keywords = options.keyword
41
+ ? (Array.isArray(options.keyword) ? options.keyword : [options.keyword])
42
+ : suppressions_1.DEFAULT_KEYWORDS;
43
+ const suppressions = new suppressions_1.Suppressions(unit.lines, keywords);
44
+ for (const rule of selected) {
45
+ const sev = severityOf(rule, severity);
46
+ for (const problem of rule.run(unit)) {
47
+ const p = { ...problem, severity: sev };
48
+ const res = suppressions.resolve(p.ruleId, p.line, rule.reasonRequired);
49
+ if (res.suppressed) {
50
+ suppressed.push({ ...p, reason: res.reason ?? null, scope: res.scope });
51
+ continue;
52
+ }
53
+ if (res.invalidMissingReason) {
54
+ active.push({
55
+ ...p,
56
+ message: `${p.message} (suppression ignored: a reason is required)`,
57
+ context: { ...p.context, invalidSuppression: 'missing-reason' }
58
+ });
59
+ continue;
60
+ }
61
+ active.push(p);
62
+ }
63
+ }
64
+ active.sort((a, b) => a.line - b.line || a.ruleId.localeCompare(b.ruleId));
65
+ return { problems: active, suppressed };
66
+ }
package/esm/cli.js ADDED
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `pgsql-lint` — lint SQL source files for the convention rules.
4
+ *
5
+ * pgsql-lint <path…> [--rules a,b] [--warn a,b] [--off a,b] [--json] [--quiet]
6
+ *
7
+ * Paths may be files or directories (directories are scanned recursively for
8
+ * `.sql`). Exit code is 1 when any *error*-severity finding remains, 0
9
+ * otherwise — so it drops straight into a pre-commit hook or CI step. Findings
10
+ * downgraded with `--warn` print but never fail the run.
11
+ */
12
+ import chalk from 'chalk';
13
+ import minimist from 'minimist';
14
+ import { lintFiles } from './file-runner';
15
+ import { LINT_RULES } from './rules';
16
+ const HELP = `pgsql-lint — source-level SQL/PL/pgSQL convention linter
17
+
18
+ Usage:
19
+ pgsql-lint <path...> [options]
20
+
21
+ Arguments:
22
+ path One or more .sql files or directories (scanned recursively).
23
+
24
+ Options:
25
+ --rules <ids> Comma-separated rule ids/codes to run (default: all).
26
+ --warn <ids> Report these rules as warnings (do not fail the run).
27
+ --off <ids> Disable these rules entirely.
28
+ --keyword <kw> Suppression directive keyword (default: pgsql-lint,safegres).
29
+ --json Emit findings as JSON.
30
+ --quiet Only print active findings (hide acknowledged waivers).
31
+ -h, --help Show this help.
32
+ -v, --version Show version.
33
+
34
+ Rules:
35
+ ${LINT_RULES.map((r) => ` ${r.code} ${r.id} — ${r.title}`).join('\n')}
36
+
37
+ Suppress inline (in the function body):
38
+ -- pgsql-lint-disable-next-line no-dynamic-sql -- lookup-only: <why>
39
+ `;
40
+ function csv(v) {
41
+ if (!v)
42
+ return undefined;
43
+ const parts = v.split(',').map((s) => s.trim()).filter(Boolean);
44
+ return parts.length > 0 ? parts : undefined;
45
+ }
46
+ async function main() {
47
+ const argv = minimist(process.argv.slice(2), {
48
+ boolean: ['json', 'quiet', 'help', 'version'],
49
+ string: ['rules', 'warn', 'off', 'keyword'],
50
+ alias: { h: 'help', v: 'version' }
51
+ });
52
+ if (argv.version) {
53
+ console.log(require('../package.json').version);
54
+ return;
55
+ }
56
+ if (argv.help || argv._.length === 0) {
57
+ console.log(HELP);
58
+ process.exit(argv._.length === 0 && !argv.help ? 1 : 0);
59
+ }
60
+ const rules = csv(argv.rules);
61
+ const keyword = csv(argv.keyword);
62
+ const severity = {};
63
+ for (const id of csv(argv.warn) ?? [])
64
+ severity[id] = 'warn';
65
+ for (const id of csv(argv.off) ?? [])
66
+ severity[id] = 'off';
67
+ const reports = await lintFiles(argv._, { rules, keyword, severity });
68
+ if (argv.json) {
69
+ console.log(JSON.stringify(reports, null, 2));
70
+ }
71
+ let errors = 0;
72
+ let warnings = 0;
73
+ let acknowledged = 0;
74
+ for (const report of reports) {
75
+ if (report.parseError) {
76
+ if (!argv.json)
77
+ console.error(chalk.yellow(`⚠ ${report.file}: ${report.parseError}`));
78
+ continue;
79
+ }
80
+ const shown = report.findings.filter((f) => !f.acknowledged || !argv.quiet);
81
+ if (!argv.json && shown.length > 0) {
82
+ console.log(chalk.underline(report.file));
83
+ for (const f of shown)
84
+ console.log(formatFinding(f));
85
+ console.log('');
86
+ }
87
+ for (const f of report.findings) {
88
+ if (f.acknowledged)
89
+ acknowledged++;
90
+ else if (f.severity === 'warn')
91
+ warnings++;
92
+ else
93
+ errors++;
94
+ }
95
+ }
96
+ if (!argv.json) {
97
+ const parts = [];
98
+ parts.push(errors > 0 ? chalk.red(`${errors} error${errors === 1 ? '' : 's'}`) : chalk.green('0 errors'));
99
+ if (warnings > 0)
100
+ parts.push(chalk.yellow(`${warnings} warning${warnings === 1 ? '' : 's'}`));
101
+ if (acknowledged > 0)
102
+ parts.push(chalk.gray(`${acknowledged} acknowledged`));
103
+ console.log(parts.join(chalk.gray(', ')));
104
+ }
105
+ process.exit(errors > 0 ? 1 : 0);
106
+ }
107
+ function formatFinding(f) {
108
+ const loc = chalk.gray(`${String(f.line).padStart(4)}`);
109
+ const tag = f.acknowledged
110
+ ? chalk.gray('acknowledged')
111
+ : f.severity === 'warn'
112
+ ? chalk.yellow(`${f.code} warn`)
113
+ : chalk.red(`${f.code} error`);
114
+ const id = chalk.gray(f.ruleId);
115
+ let line = ` ${loc} ${tag} ${f.message} ${id} ${chalk.gray(f.subject)}`;
116
+ if (f.acknowledged && f.reason)
117
+ line += `\n ${chalk.gray(`↳ waived (${f.scope}): ${f.reason}`)}`;
118
+ else if (f.hint)
119
+ line += `\n ${chalk.gray(`↳ ${f.hint}`)}`;
120
+ return line;
121
+ }
122
+ main().catch((err) => {
123
+ console.error(chalk.red('Error:'), err.message || err);
124
+ process.exit(2);
125
+ });
package/esm/engine.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The lint engine: parse a definition, run the rules, then apply suppressions.
3
+ * Pure `source → result`, with no `pg` dependency, so it can be unit-tested on
4
+ * string literals and embedded anywhere.
5
+ *
6
+ * Rules and their severities are *injected*, never discovered by name: you pass
7
+ * the rule objects in (see `createLinter`), so a third-party rule ships as an
8
+ * ordinary import, not a magic `pgsql-lint-plugin-*` package.
9
+ */
10
+ import { parseUnit } from './parse-unit';
11
+ import { LINT_RULES } from './rules';
12
+ import { DEFAULT_KEYWORDS, Suppressions } from './suppressions';
13
+ /** Resolve a rule's configured severity (id wins over code; default `error`). */
14
+ export function severityOf(rule, severity = {}) {
15
+ return severity[rule.id] ?? severity[rule.code] ?? 'error';
16
+ }
17
+ /** Lint a single function definition. */
18
+ export async function lintDefinition(text, language, name, options = {}) {
19
+ const active = [];
20
+ const suppressed = [];
21
+ const severity = options.severity ?? {};
22
+ let selected = options.ruleSet ?? LINT_RULES;
23
+ if (options.rules) {
24
+ const wanted = new Set(options.rules);
25
+ selected = selected.filter((r) => wanted.has(r.id) || wanted.has(r.code));
26
+ }
27
+ // `off` rules never run.
28
+ selected = selected.filter((r) => severityOf(r, severity) !== 'off');
29
+ if (selected.length === 0)
30
+ return { problems: active, suppressed };
31
+ const unit = await parseUnit(text, language, name);
32
+ // An unparseable definition produces no lint findings — dynamic/opaque bodies
33
+ // are a downstream concern (e.g. a call-graph), not the linter's.
34
+ if (unit.parseError)
35
+ return { problems: active, suppressed };
36
+ const keywords = options.keyword
37
+ ? (Array.isArray(options.keyword) ? options.keyword : [options.keyword])
38
+ : DEFAULT_KEYWORDS;
39
+ const suppressions = new Suppressions(unit.lines, keywords);
40
+ for (const rule of selected) {
41
+ const sev = severityOf(rule, severity);
42
+ for (const problem of rule.run(unit)) {
43
+ const p = { ...problem, severity: sev };
44
+ const res = suppressions.resolve(p.ruleId, p.line, rule.reasonRequired);
45
+ if (res.suppressed) {
46
+ suppressed.push({ ...p, reason: res.reason ?? null, scope: res.scope });
47
+ continue;
48
+ }
49
+ if (res.invalidMissingReason) {
50
+ active.push({
51
+ ...p,
52
+ message: `${p.message} (suppression ignored: a reason is required)`,
53
+ context: { ...p.context, invalidSuppression: 'missing-reason' }
54
+ });
55
+ continue;
56
+ }
57
+ active.push(p);
58
+ }
59
+ }
60
+ active.sort((a, b) => a.line - b.line || a.ruleId.localeCompare(b.ruleId));
61
+ return { problems: active, suppressed };
62
+ }