loadwise 0.6.2 → 0.8.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/README.md +175 -115
- package/dist/bin/loadwise.js +132 -67
- package/dist/lib/accessibility/analyze.js +5 -3
- package/dist/lib/accessibility/angular-inline.js +9 -11
- package/dist/lib/accessibility/angular-literal.js +39 -0
- package/dist/lib/accessibility/form-context.js +36 -0
- package/dist/lib/accessibility/frame-head.js +92 -0
- package/dist/lib/accessibility/frame-viewport.js +149 -0
- package/dist/lib/accessibility/frontend-detect.js +6 -5
- package/dist/lib/accessibility/jsx-elements.js +13 -3
- package/dist/lib/accessibility/markup-files.js +7 -2
- package/dist/lib/accessibility/rule-ids.js +3 -0
- package/dist/lib/accessibility/rules.js +128 -41
- package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
- package/dist/lib/accessibility/template-attributes.js +5 -3
- package/dist/lib/accessibility/template-elements.js +25 -6
- package/dist/lib/accessibility/template-file.js +40 -25
- package/dist/lib/accessibility/usage.js +10 -2
- package/dist/lib/editor/accessibility-examples.js +6 -1
- package/dist/lib/editor/actions.js +46 -7
- package/dist/lib/editor/apply-fix.js +69 -4
- package/dist/lib/editor/configured-setup.js +63 -0
- package/dist/lib/editor/diagnostics.js +206 -17
- package/dist/lib/editor/dismissals.js +85 -26
- package/dist/lib/editor/editor-document.js +5 -2
- package/dist/lib/editor/editor-launcher.js +170 -0
- package/dist/lib/editor/fix-edits.js +19 -0
- package/dist/lib/editor/jetbrains-setup.js +53 -0
- package/dist/lib/editor/language-server.js +80 -24
- package/dist/lib/editor/managed-config.js +37 -0
- package/dist/lib/editor/native-setup.js +86 -0
- package/dist/lib/editor/perf-watch.js +8 -6
- package/dist/lib/editor/release-vsix.js +61 -0
- package/dist/lib/editor/reliability-examples.js +15 -0
- package/dist/lib/editor/scan-session.js +29 -8
- package/dist/lib/editor/server-commands.js +38 -9
- package/dist/lib/editor/setup-server.js +87 -0
- package/dist/lib/editor/setup-vim.js +63 -0
- package/dist/lib/editor/setup.js +131 -0
- package/dist/lib/editor/stdio-setup.js +6 -0
- package/dist/lib/editor/workspace-files.js +61 -7
- package/dist/lib/editor/workspace-paths.js +41 -1
- package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
- package/dist/lib/maintainability/architecture/architecture.js +4 -4
- package/dist/lib/maintainability/cli/changed-lines.js +20 -2
- package/dist/lib/maintainability/cli/inputs.js +12 -3
- package/dist/lib/maintainability/cli.js +18 -5
- package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
- package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
- package/dist/lib/maintainability/examples.js +4 -0
- package/dist/lib/maintainability/quality/functions.js +9 -6
- package/dist/lib/maintainability/quality/limits.js +19 -0
- package/dist/lib/maintainability/quality/size-limits.js +8 -2
- package/dist/lib/maintainability/quality/stray-console.js +62 -1
- package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
- package/dist/lib/maintainability/rule-ids.js +3 -0
- package/dist/lib/maintainability/scan-changed.js +4 -1
- package/dist/lib/maintainability/scan-worker.js +6 -2
- package/dist/lib/maintainability/scan.js +21 -8
- package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
- package/dist/lib/maintainability/unused/module-usage.js +43 -21
- package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
- package/dist/lib/maintainability/unused/unused-modules.js +5 -10
- package/dist/lib/performance/analysis/source-inputs.js +7 -2
- package/dist/lib/performance/analysis/source-options.js +7 -6
- package/dist/lib/performance/analyze.js +16 -3
- package/dist/lib/performance/cli/changed-lines.js +8 -1
- package/dist/lib/performance/cli/cli-arguments.js +19 -8
- package/dist/lib/performance/cli/cli-output.js +4 -0
- package/dist/lib/performance/cli/cli-scan.js +21 -2
- package/dist/lib/performance/cli.js +16 -7
- package/dist/lib/performance/collections/memory-growth.js +55 -12
- package/dist/lib/performance/contracts/openapi.js +13 -4
- package/dist/lib/performance/datastores/pg-integrity.js +68 -22
- package/dist/lib/performance/datastores/pg-session-release.js +114 -0
- package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
- package/dist/lib/performance/datastores/pooling.js +62 -3
- package/dist/lib/performance/datastores/redis.js +94 -18
- package/dist/lib/performance/datastores/session-store.js +2 -1
- package/dist/lib/performance/db/checks.js +19 -8
- package/dist/lib/performance/db/gateway.js +3 -1
- package/dist/lib/performance/db/plan-estimates.js +4 -4
- package/dist/lib/performance/engine/native-syntax.js +3 -0
- package/dist/lib/performance/engine/native.js +11 -7
- package/dist/lib/performance/evidence/plans.js +7 -5
- package/dist/lib/performance/evidence/traces.js +21 -1
- package/dist/lib/performance/frontend/angular-teardown.js +96 -0
- package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
- package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
- package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
- package/dist/lib/performance/frontend/frontend-perf.js +149 -74
- package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
- package/dist/lib/performance/migrations/extract-code.js +13 -5
- package/dist/lib/performance/migrations/extract-sql.js +82 -38
- package/dist/lib/performance/migrations/operations.js +56 -13
- package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
- package/dist/lib/performance/migrations/postgres-registry.js +127 -26
- package/dist/lib/performance/migrations/postgres-settings.js +78 -0
- package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
- package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
- package/dist/lib/performance/migrations/rules-postgres.js +88 -39
- package/dist/lib/performance/orm/offset-pagination.js +6 -4
- package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
- package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
- package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
- package/dist/lib/performance/polyglot.js +111 -14
- package/dist/lib/performance/projects.js +3 -3
- package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
- package/dist/lib/performance/request/backend-mastery.js +151 -42
- package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
- package/dist/lib/performance/request/fastify-receivers.js +93 -0
- package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
- package/dist/lib/performance/request/mongoose-lean.js +298 -46
- package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
- package/dist/lib/performance/request/phase5-ast.js +6 -7
- package/dist/lib/performance/request/phase5-rules.js +204 -23
- package/dist/lib/performance/request/request-handlers.js +120 -23
- package/dist/lib/performance/request/sql-select-star.js +150 -0
- package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
- package/dist/lib/performance/request/upload-limits.js +5 -1
- package/dist/lib/performance/site-fix.js +4 -4
- package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
- package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
- package/dist/lib/performance/site-fixes/collections.js +1 -2
- package/dist/lib/performance/site-fixes/frontend-fixes.js +358 -14
- package/dist/lib/performance/site-fixes/helpers.js +3 -4
- package/dist/lib/performance/site-fixes/integrity.js +2 -4
- package/dist/lib/performance/site-fixes/migration-context.js +8 -1
- package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
- package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
- package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
- package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
- package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
- package/dist/lib/performance/sql/mysql-tokens.js +38 -12
- package/dist/lib/reliability/boundary-access.js +114 -57
- package/dist/lib/reliability/react-bugs.js +29 -7
- package/dist/lib/reliability/resource-leak-intervals.js +258 -0
- package/dist/lib/reliability/resource-leaks.js +209 -195
- package/dist/lib/reliability/rule-ids.js +10 -1
- package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
- package/dist/lib/reliability/swallowed-errors.js +107 -21
- package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
- package/dist/lib/reliability/usage.js +16 -5
- package/dist/lib/reliability/walk.js +3 -2
- package/dist/lib/security/auth-crypto/hashing.js +24 -8
- package/dist/lib/security/auth-crypto/jwt.js +21 -6
- package/dist/lib/security/auth-crypto/secrets.js +44 -1
- package/dist/lib/security/auth-crypto/shared.js +3 -1
- package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
- package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
- package/dist/lib/security/cli.js +21 -6
- package/dist/lib/security/cookie-credentials.js +115 -0
- package/dist/lib/security/cookie-csrf.js +241 -0
- package/dist/lib/security/deps/advisory.js +50 -109
- package/dist/lib/security/deps/cli.js +1 -1
- package/dist/lib/security/deps/cvss-score.js +14 -0
- package/dist/lib/security/deps/fixed-version.js +97 -0
- package/dist/lib/security/deps/lockfiles.js +135 -74
- package/dist/lib/security/deps/osv.js +11 -3
- package/dist/lib/security/deps/scan.js +47 -20
- package/dist/lib/security/deps/yarn-lock.js +158 -0
- package/dist/lib/security/examples/injection.cjs +4 -0
- package/dist/lib/security/exposure/cookies.js +17 -2
- package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
- package/dist/lib/security/exposure/frontend-security.js +21 -14
- package/dist/lib/security/exposure/jsx-url.js +18 -33
- package/dist/lib/security/exposure/logging.js +49 -10
- package/dist/lib/security/exposure/prototype-pollution.js +126 -56
- package/dist/lib/security/exposure/react-html.js +26 -0
- package/dist/lib/security/exposure/reflected-xss.js +34 -5
- package/dist/lib/security/files/compose.js +126 -1
- package/dist/lib/security/files/dockerfile.js +62 -4
- package/dist/lib/security/files/index.js +1 -1
- package/dist/lib/security/injection/command.js +46 -18
- package/dist/lib/security/injection/index.js +2 -0
- package/dist/lib/security/injection/ldap.js +86 -0
- package/dist/lib/security/injection/nosql.js +28 -4
- package/dist/lib/security/injection/redos.js +1 -1
- package/dist/lib/security/injection/rule-ids.js +1 -0
- package/dist/lib/security/injection/shared.js +5 -1
- package/dist/lib/security/injection/sql.js +28 -13
- package/dist/lib/security/lexical-declaration.js +113 -0
- package/dist/lib/security/pg-dynamic-query.js +28 -1
- package/dist/lib/security/pg-identifier-guards.js +107 -3
- package/dist/lib/security/phase5-rules.js +26 -135
- package/dist/lib/security/polyglot.js +2 -2
- package/dist/lib/security/redirect-settings.js +98 -0
- package/dist/lib/security/request-forgery/open-redirect.js +18 -5
- package/dist/lib/security/request-forgery/path-traversal.js +84 -6
- package/dist/lib/security/request-forgery/shared.js +1 -7
- package/dist/lib/security/request-forgery/ssrf.js +176 -14
- package/dist/lib/security/rule-descriptions.js +5 -1
- package/dist/lib/security/rule-ids.js +7 -0
- package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
- package/dist/lib/security/site-fixes/exposure.js +21 -3
- package/dist/lib/security/site-fixes/files.js +11 -13
- package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
- package/dist/lib/security/site-fixes/injection.js +17 -4
- package/dist/lib/security/site-fixes/jwt.js +1 -20
- package/dist/lib/security/site-fixes/request-forgery.js +37 -29
- package/dist/lib/security/taint/binding-inputs.js +236 -0
- package/dist/lib/security/taint/filename-guard.js +45 -45
- package/dist/lib/security/taint/guards.js +14 -8
- package/dist/lib/security/taint/index.js +126 -154
- package/dist/lib/security/taint/propagate.js +43 -9
- package/dist/lib/security/taint/record-writes.js +161 -0
- package/dist/lib/security/taint/resolution-cache.js +13 -7
- package/dist/lib/security/taint/sanitizers.js +89 -5
- package/dist/lib/security/taint/trace-nodes.js +61 -0
- package/dist/lib/security/taint/validators.js +89 -9
- package/dist/lib/shared/agent/agent-init.js +28 -5
- package/dist/lib/shared/agent/agent-prompt.js +74 -0
- package/dist/lib/shared/agent/agent-session.js +6 -1
- package/dist/lib/shared/agent/agent-verify.js +58 -11
- package/dist/lib/shared/agent/git-hook.js +17 -6
- package/dist/lib/shared/agent/review-delivery.js +1 -1
- package/dist/lib/shared/agent/review-mcp.js +8 -2
- package/dist/lib/shared/analysis/ast-semantics.js +2 -2
- package/dist/lib/shared/analysis/scan-cache.js +99 -14
- package/dist/lib/shared/check.js +172 -20
- package/dist/lib/shared/cli-dispatch.js +17 -0
- package/dist/lib/shared/config.js +27 -10
- package/dist/lib/shared/explain.js +1 -1
- package/dist/lib/shared/fix/fix-convergence.js +19 -31
- package/dist/lib/shared/fix/fix-handoff.js +16 -11
- package/dist/lib/shared/fix/fix-imports.js +4 -162
- package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
- package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
- package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
- package/dist/lib/shared/fix/fix-presentation.js +9 -6
- package/dist/lib/shared/fix/fix-safety.js +32 -1
- package/dist/lib/shared/fix/fix-scope.js +82 -0
- package/dist/lib/shared/fix/fix-terminal.js +28 -1
- package/dist/lib/shared/fix/fix-typecheck.js +8 -4
- package/dist/lib/shared/fix/import-text-edits.js +148 -0
- package/dist/lib/shared/fix/project-file-access.js +17 -26
- package/dist/lib/shared/fix/read-fix-text.js +20 -0
- package/dist/lib/shared/fix.js +241 -104
- package/dist/lib/shared/formats/finding-location.js +4 -1
- package/dist/lib/shared/formats/github.js +3 -3
- package/dist/lib/shared/formats/sarif.js +9 -3
- package/dist/lib/shared/report-fp.js +97 -0
- package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
- package/dist/lib/shared/reporting/baseline.js +7 -5
- package/dist/lib/shared/reporting/check-text.js +50 -0
- package/dist/lib/shared/reporting/pillars.js +54 -19
- package/dist/lib/shared/reporting/source-report.js +3 -0
- package/dist/lib/shared/system/atomic-write.js +5 -2
- package/dist/lib/shared/system/glob.js +34 -8
- package/dist/lib/shared/system/sentry.js +222 -0
- package/dist/lib/shared/system/shell-argument.js +5 -1
- package/dist/lib/shared/system/terminal-safe.js +3 -2
- package/dist/lib/shared/system/terminal-style.js +131 -0
- package/dist/lib/shared/workspaces.js +15 -3
- package/docs/assets/cli-workflow.gif +0 -0
- package/integrations/sublime/plugin.py +22 -0
- package/integrations/zed/Cargo.lock +845 -0
- package/integrations/zed/Cargo.toml +11 -0
- package/integrations/zed/extension.toml +11 -0
- package/integrations/zed/src/lib.rs +25 -0
- package/package.json +15 -3
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/commands/loadwise.md +11 -6
- package/plugin/hooks/check-edited-file.mjs +27 -5
- package/polyglot/performance/rules/csharp.yml +34 -5
- package/polyglot/performance/rules/java.yml +24 -1
- package/polyglot/performance/rules/python.yml +74 -2
- package/polyglot/performance/sgconfig.yml +1 -0
- package/polyglot/reliability/rules/csharp.yml +12 -6
- package/polyglot/reliability/rules/go.yml +86 -6
- package/polyglot/reliability/rules/java.yml +22 -1
- package/polyglot/reliability/sgconfig.yml +1 -0
- package/polyglot/security/rules/go.yml +100 -22
- package/polyglot/security/rules/python.yml +74 -6
- package/polyglot/security/rules/rust.yml +65 -0
- package/polyglot/security/sgconfig.yml +1 -0
- package/schema/loadwise.config.schema.json +556 -76
- /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const MILLISECONDS_PER_UNIT = {
|
|
2
|
+
us: 0.001,
|
|
3
|
+
ms: 1,
|
|
4
|
+
s: 1000,
|
|
5
|
+
min: 60000,
|
|
6
|
+
h: 3600000,
|
|
7
|
+
d: 86400000,
|
|
8
|
+
};
|
|
9
|
+
const NEXT_SMALLER_UNIT_MS = {
|
|
10
|
+
ms: MILLISECONDS_PER_UNIT.us,
|
|
11
|
+
s: MILLISECONDS_PER_UNIT.ms,
|
|
12
|
+
min: MILLISECONDS_PER_UNIT.s,
|
|
13
|
+
h: MILLISECONDS_PER_UNIT.min,
|
|
14
|
+
d: MILLISECONDS_PER_UNIT.h,
|
|
15
|
+
};
|
|
16
|
+
const MAX_POSTGRES_INTEGER = 2_147_483_647;
|
|
17
|
+
function roundToEven(value) {
|
|
18
|
+
const floor = Math.floor(value);
|
|
19
|
+
return value - floor === 0.5 && floor % 2 === 0 ? floor : Math.round(value);
|
|
20
|
+
}
|
|
21
|
+
function timeoutValue(node) {
|
|
22
|
+
const constant = node?.A_Const;
|
|
23
|
+
const value = constant?.sval?.sval ?? constant?.fval?.fval ?? (constant?.ival ? String(constant.ival.ival ?? 0) : '');
|
|
24
|
+
const duration = /^\s*([+-]?\d+(?:\.\d+)?)\s*(us|ms|s|min|h|d)?\s*$/.exec(value);
|
|
25
|
+
if (!duration)
|
|
26
|
+
return 'unknown';
|
|
27
|
+
const unit = duration[2];
|
|
28
|
+
const milliseconds = Number(duration[1]) * MILLISECONDS_PER_UNIT[unit ?? 'ms'];
|
|
29
|
+
const smallerUnit = unit && NEXT_SMALLER_UNIT_MS[unit];
|
|
30
|
+
const converted = smallerUnit ? roundToEven(milliseconds / smallerUnit) * smallerUnit : milliseconds;
|
|
31
|
+
const timeout = roundToEven(converted);
|
|
32
|
+
if (timeout === 0)
|
|
33
|
+
return 'disabled';
|
|
34
|
+
return timeout > 0 && timeout <= MAX_POSTGRES_INTEGER ? 'enabled' : 'unknown';
|
|
35
|
+
}
|
|
36
|
+
export function variableSettings(statement) {
|
|
37
|
+
const changesSearchPath = statement.name === 'search_path' || statement.name === 'role' || statement.kind === 'VAR_RESET_ALL';
|
|
38
|
+
if (statement.name !== 'lock_timeout' && statement.kind !== 'VAR_RESET_ALL')
|
|
39
|
+
return { changesSearchPath };
|
|
40
|
+
const argument = statement.args?.[0];
|
|
41
|
+
return {
|
|
42
|
+
changesSearchPath,
|
|
43
|
+
lockTimeout: {
|
|
44
|
+
value: statement.kind === 'VAR_SET_VALUE' ? timeoutValue(argument) : 'unknown',
|
|
45
|
+
scope: statement.is_local ? 'local' : 'session',
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function directSetConfig(target) {
|
|
50
|
+
const expression = target.ResTarget?.val;
|
|
51
|
+
const call = expression?.FuncCall;
|
|
52
|
+
const parts = call?.funcname;
|
|
53
|
+
const names = parts?.map((name) => name.String?.sval).join('.');
|
|
54
|
+
if (names === 'set_config' || names === 'pg_catalog.set_config')
|
|
55
|
+
return call?.args;
|
|
56
|
+
}
|
|
57
|
+
export function selectedSettings(statement) {
|
|
58
|
+
const targets = statement.targetList ?? [];
|
|
59
|
+
const calls = targets.map(directSetConfig);
|
|
60
|
+
const setting = calls.find((args) => args?.[0]?.A_Const?.sval?.sval === 'lock_timeout');
|
|
61
|
+
const changesSearchPath = calls.some((args) => args?.[0]?.A_Const?.sval?.sval === 'search_path');
|
|
62
|
+
if (!setting)
|
|
63
|
+
return { changesSearchPath };
|
|
64
|
+
const local = setting[2]?.A_Const?.boolval;
|
|
65
|
+
const unconditional = targets.length === 1 &&
|
|
66
|
+
!statement.fromClause &&
|
|
67
|
+
!statement.whereClause &&
|
|
68
|
+
!statement.withClause &&
|
|
69
|
+
!statement.limitCount &&
|
|
70
|
+
!statement.limitOffset;
|
|
71
|
+
return {
|
|
72
|
+
changesSearchPath,
|
|
73
|
+
lockTimeout: {
|
|
74
|
+
value: unconditional ? timeoutValue(setting[1]) : 'unknown',
|
|
75
|
+
scope: local ? (local.boolval ? 'local' : 'session') : 'unknown',
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// PostgreSQL migration rules for ADD COLUMN: NOT NULL without a default and volatile defaults.
|
|
2
2
|
import { containsPlaceholder, createFinding } from './operations.js';
|
|
3
|
-
import { display, displaySql, holdsRows } from './rules-postgres-shared.js';
|
|
3
|
+
import { display, displaySql, displayTable, holdsRows } from './rules-postgres-shared.js';
|
|
4
4
|
// Functions whose value is fixed for the statement, so PostgreSQL 11+ stores the default without a
|
|
5
5
|
// rewrite.
|
|
6
6
|
const NON_VOLATILE_FUNCTIONS = new Set([
|
|
@@ -101,7 +101,7 @@ export function notNullWithoutDefault(operation, unit) {
|
|
|
101
101
|
const column = display(operation.columnName);
|
|
102
102
|
const fix = builderFix(NULLABLE_FIX, unit.framework, operation);
|
|
103
103
|
return createFinding(operation, 'migration-not-null-without-default', {
|
|
104
|
-
message: `\`ADD COLUMN ${column} ... NOT NULL\` has no default, so it fails on \`${
|
|
104
|
+
message: `\`ADD COLUMN ${column} ... NOT NULL\` has no default, so it fails on \`${displayTable(operation)}\` once the table has rows, and app versions still running that insert without \`${operation.columnName}\` fail too. ${fix}, backfill in batches, then enforce (see \`migration-set-not-null-scan\`). An empty table accepts it, but production tables rarely stay empty.`,
|
|
105
105
|
suggestion: `${fix}, backfill in batches, then enforce.`,
|
|
106
106
|
example: {
|
|
107
107
|
before: displaySql(operation.sql),
|
|
@@ -129,7 +129,7 @@ export function volatileDefault(operation) {
|
|
|
129
129
|
const volatile = volatileDefaultReason(operation);
|
|
130
130
|
if (!volatile)
|
|
131
131
|
return null;
|
|
132
|
-
const table =
|
|
132
|
+
const table = displayTable(operation);
|
|
133
133
|
const column = display(operation.columnName);
|
|
134
134
|
const setDefault = volatile.call
|
|
135
135
|
? `then \`ALTER TABLE ${table} ALTER COLUMN ${column} SET DEFAULT ${volatile.call};\` so only new rows get it, and backfill existing rows in batches`
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Display helpers and table-existence checks shared by the PostgreSQL migration rule modules.
|
|
2
2
|
import { DYNAMIC_PLACEHOLDER_PREFIX, compactSql, containsPlaceholder, quoteIdentifier } from './operations.js';
|
|
3
|
+
import { quoteIdent } from '../db/pg-catalog.js';
|
|
3
4
|
const PLACEHOLDER_PATTERN = new RegExp(DYNAMIC_PLACEHOLDER_PREFIX + '\\d+', 'g');
|
|
4
5
|
export function display(name, dialect = 'postgres') {
|
|
5
6
|
if (!name)
|
|
@@ -9,6 +10,14 @@ export function display(name, dialect = 'postgres') {
|
|
|
9
10
|
export function displaySql(text) {
|
|
10
11
|
return compactSql(text).replaceAll(PLACEHOLDER_PATTERN, '${...}');
|
|
11
12
|
}
|
|
13
|
+
export function displayTable(operation, dialect = 'postgres') {
|
|
14
|
+
return displayRelation(operation.table, operation.tableSchema, dialect);
|
|
15
|
+
}
|
|
16
|
+
export function displayRelation(name, schema, dialect) {
|
|
17
|
+
if (dialect === 'postgres' && name && schema)
|
|
18
|
+
return `${quoteIdent(schema)}.${quoteIdent(name)}`.replaceAll(PLACEHOLDER_PATTERN, '${...}');
|
|
19
|
+
return display(name, dialect);
|
|
20
|
+
}
|
|
12
21
|
// Lock, rewrite and constraint rules apply only to tables that existed before this migration.
|
|
13
22
|
export function isExistingTable(operation) {
|
|
14
23
|
return (Boolean(operation.table) &&
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// PostgreSQL >= 12 migration rules. Each finding reads: observation, fix (snippets in backticks),
|
|
2
2
|
// caveat.
|
|
3
3
|
import { containsPlaceholder, createFinding } from './operations.js';
|
|
4
|
-
import {
|
|
4
|
+
import { operationsWithoutLockTimeout } from './postgres-lock-timeout.js';
|
|
5
|
+
import { createPostgresRegistry, hasValidatedNotNullCheck, postgresTableIdentity, resolveDroppedIndexTable, recordOperation, } from './postgres-registry.js';
|
|
5
6
|
import { notNullWithoutDefault, volatileDefault } from './rules-postgres-add-column.js';
|
|
6
|
-
import { display, displaySql, holdsRows, isExistingTable } from './rules-postgres-shared.js';
|
|
7
|
+
import { display, displaySql, displayTable, holdsRows, isExistingTable } from './rules-postgres-shared.js';
|
|
7
8
|
const LOCK_TIMEOUT_STATEMENT = "SET lock_timeout = '5s';";
|
|
8
9
|
const NON_TRANSACTIONAL_HOW = {
|
|
9
10
|
prisma: 'in a migration file containing only this statement, because Prisma runs a multi-statement file in one transaction',
|
|
@@ -50,7 +51,12 @@ function concurrentIndexSql(operation) {
|
|
|
50
51
|
}
|
|
51
52
|
// DROP INDEX names no table; it is only known when an earlier scanned migration created the index.
|
|
52
53
|
function isDropOfUnknownIndex(operation) {
|
|
53
|
-
return operation.kind === 'drop-index' &&
|
|
54
|
+
return (operation.kind === 'drop-index' &&
|
|
55
|
+
!operation.table &&
|
|
56
|
+
!operation.concurrent &&
|
|
57
|
+
Boolean(operation.index) &&
|
|
58
|
+
!operation.createdInSameUnit &&
|
|
59
|
+
!operation.emptiedInSameUnit);
|
|
54
60
|
}
|
|
55
61
|
function indexNotConcurrent(operation, unit) {
|
|
56
62
|
if (operation.kind === 'drop-index')
|
|
@@ -59,7 +65,7 @@ function indexNotConcurrent(operation, unit) {
|
|
|
59
65
|
return null;
|
|
60
66
|
if (!holdsRows(operation))
|
|
61
67
|
return null;
|
|
62
|
-
const table =
|
|
68
|
+
const table = displayTable(operation);
|
|
63
69
|
const label = '`' + (operation.builder ? displaySql(operation.sql) : displaySql(operation.sql).split(/\s+ON\s+/i)[0]) + '`';
|
|
64
70
|
const fixedSql = concurrentIndexSql(operation);
|
|
65
71
|
const fix = operation.builder
|
|
@@ -79,22 +85,36 @@ function dropIndexNotConcurrent(operation, unit) {
|
|
|
79
85
|
return null;
|
|
80
86
|
if (!isDropOfUnknownIndex(operation) && !holdsRows(operation))
|
|
81
87
|
return null;
|
|
82
|
-
const
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
88
|
+
const multiple = (operation.dropIndexes?.length ?? 0) > 1;
|
|
89
|
+
const subject = operation.table
|
|
90
|
+
? `existing table \`${displayTable(operation)}\``
|
|
91
|
+
: multiple
|
|
92
|
+
? 'the affected tables'
|
|
93
|
+
: 'its table';
|
|
94
|
+
const original = operation.sql?.trim().replace(/;$/, '') ?? '';
|
|
95
|
+
const fixedSql = concurrentDropSql(operation, original);
|
|
87
96
|
const where = operation.inTransaction
|
|
88
97
|
? NON_TRANSACTIONAL_HOW[frameworkKey(unit.framework)]
|
|
89
98
|
: 'in this migration, which already runs outside a transaction';
|
|
99
|
+
const fix = dropIndexAdvice(operation, unit.framework, fixedSql, where);
|
|
90
100
|
return createFinding(operation, 'migration-index-not-concurrent', {
|
|
91
|
-
message: `\`${
|
|
92
|
-
suggestion: `${fix}
|
|
93
|
-
example: { before:
|
|
101
|
+
message: `\`${original}\` takes an ACCESS EXCLUSIVE lock on ${subject}, blocking reads and writes while it waits for running queries and while it drops. ${fix}. \`DROP INDEX CONCURRENTLY\` drops one index per statement and does not support \`CASCADE\`.`,
|
|
102
|
+
suggestion: `${fix}.`,
|
|
103
|
+
example: { before: original, after: fixedSql ?? fix },
|
|
94
104
|
});
|
|
95
105
|
}
|
|
96
|
-
function concurrentDropSql(operation) {
|
|
97
|
-
|
|
106
|
+
function concurrentDropSql(operation, sql) {
|
|
107
|
+
if (operation.builder || operation.dropCascade || operation.dropIndexes?.length !== 1)
|
|
108
|
+
return null;
|
|
109
|
+
const fixed = sql.replace(/^(DROP\s+INDEX)\s+/i, '$1 CONCURRENTLY ');
|
|
110
|
+
return fixed === sql ? null : fixed;
|
|
111
|
+
}
|
|
112
|
+
function dropIndexAdvice(operation, framework, fixedSql, where) {
|
|
113
|
+
if (operation.builder)
|
|
114
|
+
return builderConcurrentDropFix(framework, operation) + ' ' + where;
|
|
115
|
+
if (fixedSql)
|
|
116
|
+
return 'Use `' + fixedSql + '` ' + where;
|
|
117
|
+
return 'Review the affected indexes and plan the drop in a maintenance window';
|
|
98
118
|
}
|
|
99
119
|
function builderConcurrentDropFix(framework, operation) {
|
|
100
120
|
if (framework === 'sequelize')
|
|
@@ -102,7 +122,7 @@ function builderConcurrentDropFix(framework, operation) {
|
|
|
102
122
|
return 'Use a raw `DROP INDEX CONCURRENTLY ...` query';
|
|
103
123
|
}
|
|
104
124
|
function builderConcurrentFix(framework, operation) {
|
|
105
|
-
const table =
|
|
125
|
+
const table = displayTable(operation);
|
|
106
126
|
if (framework === 'sequelize')
|
|
107
127
|
return "Pass `{ concurrently: true }` to `queryInterface.addIndex('" + operation.table + "', ...)`";
|
|
108
128
|
if (framework === 'knex')
|
|
@@ -156,29 +176,27 @@ function tableRewriteCommand(operation) {
|
|
|
156
176
|
}
|
|
157
177
|
function lockTimeoutFix(framework) {
|
|
158
178
|
if (framework === 'typeorm')
|
|
159
|
-
return `
|
|
179
|
+
return `Before the affected DDL, run \`await queryRunner.query("${LOCK_TIMEOUT_STATEMENT}")\``;
|
|
160
180
|
if (framework === 'knex')
|
|
161
|
-
return `
|
|
181
|
+
return `Before the affected DDL, run \`await knex.raw("${LOCK_TIMEOUT_STATEMENT}")\``;
|
|
162
182
|
if (framework === 'mikro-orm')
|
|
163
|
-
return `
|
|
183
|
+
return `Before the affected DDL, run \`this.addSql("${LOCK_TIMEOUT_STATEMENT}")\``;
|
|
164
184
|
if (framework === 'sequelize')
|
|
165
|
-
return `
|
|
166
|
-
return `
|
|
185
|
+
return `Before the affected DDL, run \`await queryInterface.sequelize.query("${LOCK_TIMEOUT_STATEMENT}")\``;
|
|
186
|
+
return `Before the affected DDL, run \`${LOCK_TIMEOUT_STATEMENT}\``;
|
|
167
187
|
}
|
|
168
188
|
// Once per file: the first statement that queues for a lock on an existing table with no
|
|
169
189
|
// lock_timeout set before it.
|
|
170
190
|
function missingLockTimeout(operations, unit) {
|
|
171
|
-
for (const operation of operations) {
|
|
172
|
-
if (operation.kind === 'set-lock-timeout')
|
|
173
|
-
return null;
|
|
191
|
+
for (const operation of operationsWithoutLockTimeout(operations)) {
|
|
174
192
|
if (!LOCK_TAKING_KINDS.has(operation.kind) || operation.concurrent)
|
|
175
193
|
continue;
|
|
176
194
|
if (!holdsRows(operation) && !isDropOfUnknownIndex(operation))
|
|
177
195
|
continue;
|
|
178
196
|
const fix = lockTimeoutFix(unit.framework);
|
|
179
|
-
const lockTarget = operation.table ? `\`${
|
|
197
|
+
const lockTarget = operation.table ? `\`${displayTable(operation)}\`` : 'its table';
|
|
180
198
|
return createFinding(operation, 'migration-missing-lock-timeout', {
|
|
181
|
-
message: `\`${displaySql(operation.sql)}\` waits for a lock on ${lockTarget}
|
|
199
|
+
message: `\`${displaySql(operation.sql)}\` waits for a lock on ${lockTarget} without a known positive \`lock_timeout\`, and every later query on that table queues behind the wait. ${fix} so a blocked DDL fails fast instead of queueing every query behind it, then retry. Verify the effective timeout on the connection that runs the DDL.`,
|
|
182
200
|
suggestion: fix + '.',
|
|
183
201
|
example: { before: displaySql(operation.sql), after: `${LOCK_TIMEOUT_STATEMENT} ${displaySql(operation.sql)}` },
|
|
184
202
|
});
|
|
@@ -237,12 +255,12 @@ function columnTypeRewrite(operation, unit, registry) {
|
|
|
237
255
|
return null;
|
|
238
256
|
if (containsPlaceholder(operation.columnName) || containsPlaceholder(JSON.stringify(operation.type ?? null)))
|
|
239
257
|
return null;
|
|
240
|
-
const
|
|
241
|
-
|
|
258
|
+
const tableIdentity = postgresTableIdentity(operation);
|
|
259
|
+
const previous = (tableIdentity === null ? undefined : registry.columnTypes.get(tableIdentity))?.get(operation.columnName) ?? null;
|
|
242
260
|
const next = operation.type;
|
|
243
261
|
if (previous && next && !operation.hasUsing && isSafeTypeChange(previous, next))
|
|
244
262
|
return null;
|
|
245
|
-
const table =
|
|
263
|
+
const table = displayTable(operation);
|
|
246
264
|
const column = display(operation.columnName);
|
|
247
265
|
const change = previous && next ? ` from \`${typeText(previous)}\` to \`${typeText(next)}\`` : '';
|
|
248
266
|
const label = operation.builder
|
|
@@ -268,9 +286,9 @@ function setNotNullScan(operation, unit, registry) {
|
|
|
268
286
|
return null;
|
|
269
287
|
if (containsPlaceholder(operation.columnName))
|
|
270
288
|
return null;
|
|
271
|
-
if (hasValidatedNotNullCheck(registry, operation
|
|
289
|
+
if (hasValidatedNotNullCheck(registry, operation))
|
|
272
290
|
return null;
|
|
273
|
-
const table =
|
|
291
|
+
const table = displayTable(operation);
|
|
274
292
|
const column = display(operation.columnName);
|
|
275
293
|
const constraint = display(`${operation.table}_${operation.columnName}_not_null`);
|
|
276
294
|
const steps = `\`ALTER TABLE ${table} ADD CONSTRAINT ${constraint} CHECK (${column} IS NOT NULL) NOT VALID;\`, then in a later migration \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${constraint};\` and \`SET NOT NULL\``;
|
|
@@ -294,17 +312,23 @@ function constraintLabel(operation) {
|
|
|
294
312
|
return ('`ADD CONSTRAINT' + (operation.constraintName ? ' ' + display(operation.constraintName) : '') + ' ' + kind + '`');
|
|
295
313
|
}
|
|
296
314
|
function addedWithoutNotValid(operation) {
|
|
297
|
-
const table =
|
|
315
|
+
const table = displayTable(operation);
|
|
298
316
|
const name = display(operation.constraintName ?? `${operation.table}_constraint`);
|
|
299
|
-
const
|
|
300
|
-
|
|
301
|
-
|
|
317
|
+
const inline = operation.kind === 'add-column';
|
|
318
|
+
const locks = inline && operation.constraintType === 'foreign'
|
|
319
|
+
? 'an ACCESS EXCLUSIVE lock on it (from `ADD COLUMN`) and a SHARE ROW EXCLUSIVE lock on the referenced table'
|
|
320
|
+
: CONSTRAINT_LOCKS[operation.constraintType ?? ''];
|
|
321
|
+
const fix = inline
|
|
322
|
+
? `Drop the inline constraint from \`ADD COLUMN\`, add it with \`ALTER TABLE ${table} ADD CONSTRAINT ${name} ... NOT VALID;\` (a column definition cannot carry \`NOT VALID\`), then run \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${name};\` in a later migration`
|
|
323
|
+
: operation.builder
|
|
324
|
+
? `Add it with a raw query ending in \`NOT VALID\`, then run \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${name};\` in a later migration`
|
|
325
|
+
: `Add \`NOT VALID\`, then run \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${name};\` in a later migration`;
|
|
302
326
|
return createFinding(operation, 'migration-constraint-not-valid', {
|
|
303
|
-
message: `${constraintLabel(operation)} on existing table \`${table}\` checks every row while holding ${
|
|
327
|
+
message: `${constraintLabel(operation)} on existing table \`${table}\` checks every row while holding ${locks}. ${fix}; validation takes a lock that allows reads and writes. New and updated rows are checked as soon as the \`NOT VALID\` constraint exists.`,
|
|
304
328
|
suggestion: fix + '.',
|
|
305
329
|
example: {
|
|
306
330
|
before: displaySql(operation.sql),
|
|
307
|
-
after: operation.builder
|
|
331
|
+
after: operation.builder || inline
|
|
308
332
|
? `ALTER TABLE ${table} ADD CONSTRAINT ${name} ... NOT VALID; -- later: VALIDATE CONSTRAINT ${name}`
|
|
309
333
|
: `${displaySql(operation.sql)} NOT VALID; -- later: ALTER TABLE ${table} VALIDATE CONSTRAINT ${name}`,
|
|
310
334
|
},
|
|
@@ -332,9 +356,34 @@ function validatedInSameTransaction(operation, unit) {
|
|
|
332
356
|
},
|
|
333
357
|
});
|
|
334
358
|
}
|
|
359
|
+
function hasNonNullDefaultOrComputed(operation) {
|
|
360
|
+
if (operation.identity || operation.generatedStored)
|
|
361
|
+
return true;
|
|
362
|
+
if (!operation.hasDefault)
|
|
363
|
+
return false;
|
|
364
|
+
const raw = operation.defaultExpression;
|
|
365
|
+
const aConst = raw && typeof raw === 'object' && 'A_Const' in raw ? raw.A_Const : undefined;
|
|
366
|
+
return !(aConst && typeof aConst === 'object' && 'isnull' in aConst && aConst.isnull === true);
|
|
367
|
+
}
|
|
335
368
|
function constraintNotValid(operation, unit) {
|
|
336
369
|
if (operation.kind === 'validate-constraint')
|
|
337
370
|
return validatedInSameTransaction(operation, unit);
|
|
371
|
+
if (operation.kind === 'add-column' && holdsRows(operation) && operation.inlineConstraints?.length) {
|
|
372
|
+
for (const inline of operation.inlineConstraints) {
|
|
373
|
+
if (inline.notValid)
|
|
374
|
+
continue;
|
|
375
|
+
if (inline.constraintType === 'foreign' && !hasNonNullDefaultOrComputed(operation))
|
|
376
|
+
continue;
|
|
377
|
+
if (CONSTRAINT_LOCKS[inline.constraintType]) {
|
|
378
|
+
return addedWithoutNotValid({
|
|
379
|
+
...operation,
|
|
380
|
+
constraintType: inline.constraintType,
|
|
381
|
+
constraintName: inline.constraintName,
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return null;
|
|
386
|
+
}
|
|
338
387
|
if (operation.kind !== 'add-constraint' || operation.notValid || !holdsRows(operation))
|
|
339
388
|
return null;
|
|
340
389
|
if (!CONSTRAINT_LOCKS[operation.constraintType ?? ''])
|
|
@@ -346,7 +395,7 @@ function constraintWithoutIndex(operation) {
|
|
|
346
395
|
return null;
|
|
347
396
|
if (!operation.constraintType || !['unique', 'primary'].includes(operation.constraintType))
|
|
348
397
|
return null;
|
|
349
|
-
const table =
|
|
398
|
+
const table = displayTable(operation);
|
|
350
399
|
const kind = operation.constraintType === 'primary' ? 'PRIMARY KEY' : 'UNIQUE';
|
|
351
400
|
const index = display(operation.constraintName ?? `${operation.table}_${operation.constraintType === 'primary' ? 'pkey' : 'key'}`);
|
|
352
401
|
const unique = `\`CREATE UNIQUE INDEX CONCURRENTLY ${index} ON ${table} (...);\``;
|
|
@@ -364,7 +413,7 @@ function constraintWithoutIndex(operation) {
|
|
|
364
413
|
});
|
|
365
414
|
}
|
|
366
415
|
function dropTarget(operation, dialect) {
|
|
367
|
-
const table =
|
|
416
|
+
const table = displayTable(operation, dialect);
|
|
368
417
|
if (operation.kind === 'drop-table')
|
|
369
418
|
return { label: `DROP TABLE ${table}`, subject: `\`${table}\`` };
|
|
370
419
|
const column = display(operation.columnName, dialect);
|
|
@@ -392,7 +441,7 @@ function breakingRename(operation, unit) {
|
|
|
392
441
|
if (operation.nameRecreatedInSameUnit)
|
|
393
442
|
return null;
|
|
394
443
|
const dialect = unit.dialect;
|
|
395
|
-
const table =
|
|
444
|
+
const table = displayTable(operation, dialect);
|
|
396
445
|
const isColumn = operation.kind === 'rename-column';
|
|
397
446
|
const from = isColumn ? display(operation.columnName, dialect) : table;
|
|
398
447
|
const to = display(operation.newName, dialect);
|
|
@@ -83,8 +83,8 @@ const SKIPPED_ROWS = 'the database reads and discards every skipped row, so deep
|
|
|
83
83
|
function inputMessage(label) {
|
|
84
84
|
return `${label} comes from request input with no upper bound, so ${SKIPPED_ROWS}`;
|
|
85
85
|
}
|
|
86
|
-
function literalMessage(label, offset) {
|
|
87
|
-
return `${label} is ${offset}, above ${
|
|
86
|
+
function literalMessage(label, offset, maxOffset) {
|
|
87
|
+
return `${label} is ${offset}, above ${maxOffset}, so ${SKIPPED_ROWS}`;
|
|
88
88
|
}
|
|
89
89
|
function offsetLabel(access) {
|
|
90
90
|
return `The offset of ${access.name.text}()`;
|
|
@@ -156,8 +156,10 @@ function check(call, context) {
|
|
|
156
156
|
return handler && checkOneHop(call, handler, context);
|
|
157
157
|
const offset = literalOffset(value);
|
|
158
158
|
if (offset !== undefined) {
|
|
159
|
-
|
|
160
|
-
|
|
159
|
+
const configuredMax = context.ruleOptions?.(RULE_ID)?.maxOffset;
|
|
160
|
+
const maxOffset = typeof configuredMax === 'number' ? configuredMax : MAX_LITERAL_OFFSET;
|
|
161
|
+
if (offset > maxOffset)
|
|
162
|
+
context.report(access.name, RULE_ID, literalMessage(offsetLabel(access), offset, maxOffset));
|
|
161
163
|
return;
|
|
162
164
|
}
|
|
163
165
|
if (handler)
|
|
@@ -6,7 +6,6 @@ import { prismaModelName } from './prisma.js';
|
|
|
6
6
|
import { findProjectRoot } from '../schema/context.js';
|
|
7
7
|
const SCHEMA_LOCATIONS = [path.join('prisma', 'schema.prisma'), 'schema.prisma'];
|
|
8
8
|
const NATIVE_DISTINCT_FEATURE = /previewFeatures\s*=\s*\[[^\]]*["']nativeDistinct["']/;
|
|
9
|
-
const schemaEnablesNativeDistinct = new Map();
|
|
10
9
|
function propertyKey(property) {
|
|
11
10
|
if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property))
|
|
12
11
|
return;
|
|
@@ -30,10 +29,64 @@ function distinctFields(property) {
|
|
|
30
29
|
return;
|
|
31
30
|
return literals.map((element) => element.text);
|
|
32
31
|
}
|
|
33
|
-
|
|
32
|
+
// Comments are dropped and string literals emptied so attributes inside them never count as keys.
|
|
33
|
+
const COMMENT_OR_STRING = /"(?:\\.|[^"\\\n])*"|\/\/[^\n]*/g;
|
|
34
|
+
function parsePrismaSchema(rawContent) {
|
|
35
|
+
const nativeDistinct = NATIVE_DISTINCT_FEATURE.test(rawContent);
|
|
36
|
+
const content = rawContent.replaceAll(COMMENT_OR_STRING, (token) => (token.startsWith('"') ? '""' : ''));
|
|
37
|
+
const primaryKeys = new Map();
|
|
38
|
+
const modelPattern = /\bmodel\s+([A-Za-z_]\w*)\s*\{([^}]*)\}/g;
|
|
39
|
+
for (const match of content.matchAll(modelPattern)) {
|
|
40
|
+
const [, modelName, body] = match;
|
|
41
|
+
const keys = compoundPrimaryKey(body) ?? singlePrimaryKey(body);
|
|
42
|
+
if (keys)
|
|
43
|
+
primaryKeys.set(modelName, keys);
|
|
44
|
+
}
|
|
45
|
+
return { nativeDistinct, primaryKeys };
|
|
46
|
+
}
|
|
47
|
+
// Commas inside `field(length: 10, sort: Desc)` arguments do not separate fields.
|
|
48
|
+
function splitTopLevel(list) {
|
|
49
|
+
const parts = [];
|
|
50
|
+
let depth = 0;
|
|
51
|
+
let start = 0;
|
|
52
|
+
for (let index = 0; index < list.length; index++) {
|
|
53
|
+
if (list[index] === '(')
|
|
54
|
+
depth++;
|
|
55
|
+
else if (list[index] === ')')
|
|
56
|
+
depth--;
|
|
57
|
+
else if (list[index] === ',' && depth === 0) {
|
|
58
|
+
parts.push(list.slice(start, index));
|
|
59
|
+
start = index + 1;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
parts.push(list.slice(start));
|
|
63
|
+
return parts;
|
|
64
|
+
}
|
|
65
|
+
function compoundPrimaryKey(modelBody) {
|
|
66
|
+
const compoundMatch = /@@id\(\s*\[([^\]]+)\]/.exec(modelBody);
|
|
67
|
+
if (!compoundMatch)
|
|
68
|
+
return;
|
|
69
|
+
const keys = splitTopLevel(compoundMatch[1])
|
|
70
|
+
.map((part) => part.trim().replace(/\(.*/, ''))
|
|
71
|
+
.filter(Boolean);
|
|
72
|
+
return keys.length ? keys : undefined;
|
|
73
|
+
}
|
|
74
|
+
function singlePrimaryKey(modelBody) {
|
|
75
|
+
for (const line of modelBody.split(/\r?\n/)) {
|
|
76
|
+
const trimmed = line.trim();
|
|
77
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('@@'))
|
|
78
|
+
continue;
|
|
79
|
+
if (!/@id(?:\s*\(|\s|$)/.test(trimmed))
|
|
80
|
+
continue;
|
|
81
|
+
const fieldMatch = /^([A-Za-z_]\w*)\b/.exec(trimmed);
|
|
82
|
+
if (fieldMatch)
|
|
83
|
+
return [fieldMatch[1]];
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function readSchemaInfo(projectRoot) {
|
|
34
87
|
for (const location of SCHEMA_LOCATIONS) {
|
|
35
88
|
try {
|
|
36
|
-
return
|
|
89
|
+
return parsePrismaSchema(fs.readFileSync(path.join(projectRoot, location), 'utf8'));
|
|
37
90
|
}
|
|
38
91
|
catch (error) {
|
|
39
92
|
// Try the next conventional location; only a schema that exists but cannot be read is worth
|
|
@@ -46,30 +99,28 @@ function readNativeDistinctFlag(projectRoot) {
|
|
|
46
99
|
});
|
|
47
100
|
}
|
|
48
101
|
}
|
|
49
|
-
return false;
|
|
102
|
+
return { nativeDistinct: false, primaryKeys: new Map() };
|
|
50
103
|
}
|
|
51
|
-
// The nearest project's schema decides, as `prisma generate` would.
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (enabled === undefined) {
|
|
56
|
-
enabled = readNativeDistinctFlag(projectRoot);
|
|
57
|
-
schemaEnablesNativeDistinct.set(projectRoot, enabled);
|
|
58
|
-
}
|
|
59
|
-
return enabled;
|
|
104
|
+
// The nearest project's schema decides, as `prisma generate` would. Read on each use (only calls
|
|
105
|
+
// with `distinct`) so a schema edit in a long-lived watch session is never served stale.
|
|
106
|
+
function prismaSchemaInfo(sourceFile) {
|
|
107
|
+
return readSchemaInfo(findProjectRoot(path.dirname(sourceFile.fileName)));
|
|
60
108
|
}
|
|
61
109
|
function checkDistinct(call, access, options, context) {
|
|
62
110
|
const distinctProperty = optionProperty(options, 'distinct');
|
|
63
111
|
const fields = distinctProperty && distinctFields(distinctProperty);
|
|
64
|
-
|
|
65
|
-
// drop.
|
|
66
|
-
if (!fields || fields.includes('id'))
|
|
67
|
-
return;
|
|
68
|
-
if (nativeDistinctEnabled(call.getSourceFile()))
|
|
112
|
+
if (!fields)
|
|
69
113
|
return;
|
|
70
114
|
const model = prismaModelName(access.name, context.checker);
|
|
71
115
|
if (!model)
|
|
72
116
|
return;
|
|
117
|
+
const schemaInfo = prismaSchemaInfo(call.getSourceFile());
|
|
118
|
+
if (schemaInfo.nativeDistinct)
|
|
119
|
+
return;
|
|
120
|
+
const primaryKey = schemaInfo.primaryKeys.get(model);
|
|
121
|
+
// Rows already differ on the resolved primary key (or conventional `id` when schema is absent).
|
|
122
|
+
if (primaryKey?.length ? primaryKey.every((key) => fields.includes(key)) : fields.includes('id'))
|
|
123
|
+
return;
|
|
73
124
|
const list = fields.join(', ');
|
|
74
125
|
context.report(access.name, 'prisma-distinct-in-memory', `${model}.findMany({ distinct: [${list}] }) reads every matching row and removes duplicates inside Prisma's query engine, not with SQL DISTINCT, so the database still returns all duplicates. Use \`groupBy({ by: [${list}], where })\` when only those fields are selected, or a raw \`SELECT DISTINCT\`/\`DISTINCT ON\` query otherwise. Ignore this if the schema enables the nativeDistinct preview feature.`);
|
|
75
126
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { ts } from '../engine/compiler.js';
|
|
2
|
+
import { propertyName } from '../schema/ts-helpers.js';
|
|
3
|
+
// Query steps that keep a Mongoose find() a list of documents; `limit` among them bounds it.
|
|
4
|
+
export const MONGOOSE_CHAIN_STEPS = new Set([
|
|
5
|
+
'sort',
|
|
6
|
+
'select',
|
|
7
|
+
'lean',
|
|
8
|
+
'populate',
|
|
9
|
+
'skip',
|
|
10
|
+
'limit',
|
|
11
|
+
'exec',
|
|
12
|
+
'where',
|
|
13
|
+
'session',
|
|
14
|
+
'collation',
|
|
15
|
+
'hint',
|
|
16
|
+
'maxTimeMS',
|
|
17
|
+
'read',
|
|
18
|
+
'batchSize',
|
|
19
|
+
'setOptions',
|
|
20
|
+
]);
|
|
21
|
+
const ID_LIST_OPERATORS = new Set(['in', '$in']);
|
|
22
|
+
export function isIdListOperator(property) {
|
|
23
|
+
if (!ts.isPropertyAssignment(property))
|
|
24
|
+
return false;
|
|
25
|
+
const name = propertyName(property);
|
|
26
|
+
if (name)
|
|
27
|
+
return ID_LIST_OPERATORS.has(name);
|
|
28
|
+
return ts.isComputedPropertyName(property.name) && property.name.expression.getText().endsWith('.in');
|
|
29
|
+
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { ts } from '../engine/compiler.js';
|
|
4
4
|
import { unwrapExpression as unwrap } from '../../shared/analysis/ast-semantics.js';
|
|
5
5
|
import { prismaModelName } from './prisma.js';
|
|
6
|
+
import { MONGOOSE_CHAIN_STEPS, isIdListOperator } from './unbounded-list-chain.js';
|
|
6
7
|
import { querySite } from '../schema/query-sites.js';
|
|
7
8
|
import { declaredInPackage, propertyName, objectProperty } from '../schema/ts-helpers.js';
|
|
8
9
|
import { drizzleColumn } from '../schema/drizzle-schema.js';
|
|
@@ -14,8 +15,6 @@ const PG_RECEIVERS = ['Pool', 'Client', 'ClientBase', 'PoolClient'];
|
|
|
14
15
|
const TYPEORM_LIST_METHODS = new Set(['find', 'findBy']);
|
|
15
16
|
const SEQUELIZE_PACKAGES = ['sequelize', 'sequelize-typescript'];
|
|
16
17
|
const SEQUELIZE_LIST_METHODS = new Set(['findAll', 'findAndCountAll']);
|
|
17
|
-
// Query steps that keep a Mongoose find() a list of documents; `limit` among them bounds it.
|
|
18
|
-
const MONGOOSE_CHAIN_STEPS = new Set(['sort', 'select', 'lean', 'populate', 'skip', 'limit', 'exec']);
|
|
19
18
|
const BUILDER_LIMITS = new Set(['take', 'limit']);
|
|
20
19
|
const DRIZZLE_SELECTS = new Set(['select', 'selectDistinct']);
|
|
21
20
|
const DRIZZLE_CHAIN_STEPS = new Set([
|
|
@@ -41,7 +40,6 @@ const SQL_PINNED_ROW = /\bwhere\s+(?:\w+\.)?id\s*=\s*(?:\$\d+|\?)/i;
|
|
|
41
40
|
const SERVICE_QUERY_REASON = 'The query is in a service method a handler returns, so how large the table is and whether paging is applied upstream could not be checked.';
|
|
42
41
|
const PAGING_PARAMETER = /pagin|page|take|limit|first|cursor|offset|skip|size/i;
|
|
43
42
|
const SQL_ID_ANY = /\b(?:\w+\.)?_?id\s*=\s*any\s*\(\s*\$(\d+)\s*\)/i;
|
|
44
|
-
const ID_LIST_OPERATORS = new Set(['in', '$in']);
|
|
45
43
|
const ID_LIST_REASON = 'The id list comes from request input and no size cap on it was found; a cap applied by the caller or a validation layer could not be ruled out.';
|
|
46
44
|
const BUILDER_PINNED_ROW = /(?:^|\.)id\s*=\s*:/i;
|
|
47
45
|
function isUniqueColumn(table, name) {
|
|
@@ -69,14 +67,6 @@ function isBoundedValue(value) {
|
|
|
69
67
|
}
|
|
70
68
|
return true;
|
|
71
69
|
}
|
|
72
|
-
function isIdListOperator(property) {
|
|
73
|
-
if (!ts.isPropertyAssignment(property))
|
|
74
|
-
return false;
|
|
75
|
-
const name = propertyName(property);
|
|
76
|
-
if (name)
|
|
77
|
-
return ID_LIST_OPERATORS.has(name);
|
|
78
|
-
return ts.isComputedPropertyName(property.name) && property.name.expression.getText().endsWith('.in');
|
|
79
|
-
}
|
|
80
70
|
// `id: { in: ids }`, `_id: { $in: ids }`, `id: { [Op.in]: ids }` and `id: In(ids)`: the list a
|
|
81
71
|
// unique column is matched against. Such a query returns at most as many rows as the list holds.
|
|
82
72
|
function idListOf(filter, table) {
|
|
@@ -180,15 +170,30 @@ const mongooseList = (call, access, context) => {
|
|
|
180
170
|
if (!lacksLimit(options, 'limit') || pinsDocumentId(filter))
|
|
181
171
|
return;
|
|
182
172
|
let top = call;
|
|
173
|
+
let chainedIdList;
|
|
183
174
|
while (ts.isPropertyAccessExpression(top.parent) &&
|
|
184
175
|
top.parent.expression === top &&
|
|
185
176
|
ts.isCallExpression(top.parent.parent) &&
|
|
186
177
|
MONGOOSE_CHAIN_STEPS.has(top.parent.name.text)) {
|
|
187
|
-
|
|
178
|
+
const step = top.parent.name.text;
|
|
179
|
+
const [stepArgument] = top.parent.parent.arguments;
|
|
180
|
+
if (step === 'limit')
|
|
181
|
+
return;
|
|
182
|
+
// Bounds supplied through chained modifiers: `.where({ _id })` and `.setOptions({ limit })`.
|
|
183
|
+
if (step === 'where' && pinsDocumentId(stepArgument))
|
|
184
|
+
return;
|
|
185
|
+
if (step === 'where') {
|
|
186
|
+
const stepIdList = idListOf(stepArgument, undefined);
|
|
187
|
+
// A repeated id-list predicate replaces the earlier one in Mongoose; the effective list is unclear, so stay silent.
|
|
188
|
+
if (stepIdList && (chainedIdList || idListOf(filter, undefined)))
|
|
189
|
+
return;
|
|
190
|
+
chainedIdList ??= stepIdList;
|
|
191
|
+
}
|
|
192
|
+
if (step === 'setOptions' && !lacksLimit(stepArgument, 'limit'))
|
|
188
193
|
return;
|
|
189
194
|
top = top.parent.parent;
|
|
190
195
|
}
|
|
191
|
-
return { label: 'find()', top, reportNode: access.name, idList: idListOf(filter, undefined) };
|
|
196
|
+
return { label: 'find()', top, reportNode: access.name, idList: idListOf(filter, undefined) ?? chainedIdList };
|
|
192
197
|
};
|
|
193
198
|
function chainSteps(expression) {
|
|
194
199
|
const methods = new Set();
|