codecop 0.1.0__py3-none-any.whl
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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1728 @@
|
|
|
1
|
+
"""TypeScript and JavaScript call-site extractor (.ts .tsx .js .jsx .mjs .cjs, reported as language "typescript").
|
|
2
|
+
|
|
3
|
+
Finds where SQL reaches a driver and resolves the text statically:
|
|
4
|
+
|
|
5
|
+
* tagged templates: ``sql`...` `` (postgres.js, slonik, @vercel/postgres, Kysely, Drizzle), ``Prisma.sql`...` ``,
|
|
6
|
+
``prisma.$queryRaw`...` `` / ``$executeRaw``. A ``${value}`` in a tagged template is a bound parameter and becomes
|
|
7
|
+
«value»; a nested SQL fragment (``${Prisma.sql`AND ...`}``, ``${sql.raw("...")}``, ``${sql.ref("a.b")}``) is inlined.
|
|
8
|
+
* calls: ``pool.query(text)`` / ``client.query({text})`` (pg), ``client.query({query, query_params})`` /
|
|
9
|
+
``.command`` / ``.exec`` / ``.insert({table, values})`` (@clickhouse/client), mysql2 ``execute``, better-sqlite3
|
|
10
|
+
``prepare`` / ``exec``, ``knex.raw``, ``$queryRawUnsafe`` / ``$executeRawUnsafe``, TypeORM ``.query``,
|
|
11
|
+
Drizzle ``db.execute(sql`...`)``.
|
|
12
|
+
* the SQL argument through string and template literals, ``+`` concatenation, local variables (``const``, ``let``,
|
|
13
|
+
``q += ...``), module constants, object constants (``QUERIES.byId``), constants imported from other files
|
|
14
|
+
(relative imports, tsconfig paths, workspace packages, barrel re-exports), ``[...].join()``, and helpers that
|
|
15
|
+
return the SQL.
|
|
16
|
+
|
|
17
|
+
Functions that pass one of their own parameters (or a property of an options parameter) to a sink are found
|
|
18
|
+
automatically and treated as sinks: ``queryClickhouse({ query, params })``.
|
|
19
|
+
|
|
20
|
+
ORM query APIs are counted per library in ``summary.orm_calls``. Prisma, Kysely, Drizzle and TypeORM calls are also
|
|
21
|
+
turned into SQL sites by ``orm_ts`` (resolution "orm", coverage in ``summary.orm``); Sequelize and the Knex builder
|
|
22
|
+
are counted only.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import os
|
|
28
|
+
import re
|
|
29
|
+
from collections import Counter, defaultdict
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
import tree_sitter_typescript
|
|
33
|
+
from tree_sitter import Language, Node, Parser, Query, QueryCursor
|
|
34
|
+
|
|
35
|
+
from .base import LangRules, RawSite, is_test_path, looks_like_sql, read_text, trim
|
|
36
|
+
from .base import walk_tree
|
|
37
|
+
from .tsresolve import Resolver
|
|
38
|
+
|
|
39
|
+
LANG_TS = Language(tree_sitter_typescript.language_typescript())
|
|
40
|
+
LANG_TSX = Language(tree_sitter_typescript.language_tsx())
|
|
41
|
+
LANGUAGE = "typescript"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _setting(name: str, default: int) -> int:
|
|
45
|
+
try:
|
|
46
|
+
return int(os.environ.get(name, default))
|
|
47
|
+
except ValueError:
|
|
48
|
+
return default
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# Settings (environment variables, generous defaults). The file size limit is base.read_text's.
|
|
52
|
+
MAX_DEPTH = _setting("CODECOP_TS_RESOLVE_DEPTH", 8) # hops followed while resolving one SQL argument
|
|
53
|
+
MINIFIED_AVG_LINE = _setting("CODECOP_TS_MINIFIED_AVG_LINE", 1000) # mean line length above which a file is a bundle
|
|
54
|
+
MINIFIED_MIN_BYTES = _setting("CODECOP_TS_MINIFIED_MIN_BYTES", 20_000) # ...when it is at least this large
|
|
55
|
+
WRAPPER_ROUNDS = _setting("CODECOP_TS_WRAPPER_ROUNDS", 5) # wrapper-of-wrapper passes
|
|
56
|
+
CONST_VALUE_LIMIT = _setting("CODECOP_TS_CONST_VALUE_LIMIT", 20_000) # longest constant kept for cross-file lookup
|
|
57
|
+
MAX_ALTERNATIVES = _setting("CODECOP_TS_MAX_ALTERNATIVES", 8) # statements reported for one call (if / else, ? :)
|
|
58
|
+
|
|
59
|
+
FUNC_TYPES = ("function_declaration", "generator_function_declaration", "function_expression", "function",
|
|
60
|
+
"generator_function", "arrow_function", "method_definition")
|
|
61
|
+
INLINE_FUNCS = ("arrow_function", "function_expression", "function", "generator_function")
|
|
62
|
+
CLASS_TYPES = ("class_declaration", "class", "abstract_class_declaration")
|
|
63
|
+
LOOP_TYPES = ("for_statement", "for_in_statement", "while_statement", "do_statement")
|
|
64
|
+
LOOP_METHODS = {"map", "forEach", "flatMap", "filter", "reduce", "some", "every", "each", "eachSeries", "mapSeries",
|
|
65
|
+
"eachLimit", "mapLimit", "pMap", "pmap", "forEachAsync", "mapAsync", "find", "findIndex", "reduceRight"}
|
|
66
|
+
UNWRAP_TYPES = ("parenthesized_expression", "as_expression", "satisfies_expression", "non_null_expression",
|
|
67
|
+
"await_expression", "type_assertion", "instantiation_expression")
|
|
68
|
+
ASSIGN_TYPES = ("variable_declarator", "assignment_expression", "augmented_assignment_expression")
|
|
69
|
+
STRING_TYPES = ("string", "template_string")
|
|
70
|
+
|
|
71
|
+
SCAN_QUERY = """
|
|
72
|
+
(call_expression) @call
|
|
73
|
+
(string) @str
|
|
74
|
+
(template_string) @str
|
|
75
|
+
(import_statement) @imp
|
|
76
|
+
"""
|
|
77
|
+
SCAN = {id(LANG_TS): Query(LANG_TS, SCAN_QUERY), id(LANG_TSX): Query(LANG_TSX, SCAN_QUERY)}
|
|
78
|
+
|
|
79
|
+
CONST_NAME = re.compile(r"^_{0,2}[A-Z][A-Z0-9_]*$")
|
|
80
|
+
SQLISH_NAME = re.compile(r"(sql|query|stmt|statement|ddl)", re.I)
|
|
81
|
+
RECEIVER = re.compile(r"(client|\bch\b|conn|cursor|\bdb\b|Db\b|database|pool|session|clickhouse|prisma|knex|sql|\bpg\b|"
|
|
82
|
+
r"mysql|sqlite|\btx\b|trx|transaction|queryRunner|dataSource|manager|sequelize|kysely|drizzle)", re.I)
|
|
83
|
+
# What a string must start with to count as SQL when it is the argument of a database call.
|
|
84
|
+
STATEMENT_START = re.compile(
|
|
85
|
+
r"^\s*(?:--[^\n]*\n\s*|/\*.*?\*/\s*)*\(?\s*(?:SELECT|INSERT|UPDATE|DELETE|WITH|CREATE|DROP|ALTER|TRUNCATE|BEGIN|COMMIT|"
|
|
86
|
+
r"ROLLBACK|START\s+TRANSACTION|SAVEPOINT|RELEASE|SET|RESET|SHOW|EXPLAIN|DESCRIBE|DESC|OPTIMIZE|SYSTEM|EXISTS|GRANT|"
|
|
87
|
+
r"REVOKE|LOCK|VACUUM|ANALYZE|CALL|COPY|MERGE|REFRESH|ATTACH|DETACH|RENAME|KILL|USE|UPSERT|REPLACE|VALUES|LISTEN|"
|
|
88
|
+
r"NOTIFY|UNLISTEN|DO|REINDEX|CLUSTER|DISCARD|DEALLOCATE|PREPARE|EXECUTE|DECLARE|FETCH|COMMENT\s+ON|CHECK|EXCHANGE|"
|
|
89
|
+
r"UNDROP|PRAGMA|BACKUP|RESTORE)(?:\s+[\w(\"'`*$«@-]|\s*;|\s*$)", re.I | re.S)
|
|
90
|
+
SQL_INSIDE = re.compile(
|
|
91
|
+
r"\bSELECT\b[\s\S]+?\bFROM\b|\bINSERT\s+INTO\b|\bUPDATE\s+\S+\s+SET\b|\bDELETE\s+FROM\b|\b(?:CREATE|ALTER|DROP)\s+TABLE\b|"
|
|
92
|
+
r"\bWHERE\b|\bORDER\s+BY\b|\bGROUP\s+BY\b|\bLIMIT\b", re.I)
|
|
93
|
+
SUBQUERY_START = re.compile(r"^\s*(?:\(|(?:NOT\s+)?EXISTS\s*\()", re.I)
|
|
94
|
+
LEAD_HOLES = re.compile(r"^(?:\s*«[^»]*»)+")
|
|
95
|
+
# Files that cannot hold a call site are not parsed: nothing that reads as SQL and no database-looking call.
|
|
96
|
+
RELEVANT = re.compile(
|
|
97
|
+
rb"SELECT\b|INSERT\s+INTO\b|UPDATE\s|DELETE\s+FROM\b|\b(?:CREATE|ALTER|DROP|TRUNCATE|OPTIMIZE)\s|"
|
|
98
|
+
rb"\bselect\s[^;`'\"]{0,600}\sfrom\s|\binsert\s+into\b|\bdelete\s+from\b|\bupdate\s+[\w.\"`]+\s+set\b|"
|
|
99
|
+
rb"\b(?:create|alter|drop)\s+(?:table|index|materialized|view)\b|"
|
|
100
|
+
rb"\$queryRaw|\$executeRaw|\.(?:query|execute|raw|unsafe|command|prepare|exec)\s*[(<`]|\bsql\s*[`<(.]")
|
|
101
|
+
|
|
102
|
+
# Template tags that are not SQL, and tags that only shape a string.
|
|
103
|
+
NON_SQL_TAGS = {"gql", "graphql", "css", "html", "svg", "styled", "keyframes", "createGlobalStyle", "tw", "cva", "md",
|
|
104
|
+
"markdown", "msg", "t", "i18n", "chalk", "injectGlobal", "xml", "yaml", "json", "js", "ts", "glsl", "cypher"}
|
|
105
|
+
PASS_TAGS = {"dedent", "outdent", "stripIndent", "stripIndents", "oneLine", "oneLineTrim", "codeBlock", "trimIndent",
|
|
106
|
+
"raw", "format", "endent", "heredoc", "source", "unindent"}
|
|
107
|
+
# Calls inside a tagged template that put text, not a value, into the SQL.
|
|
108
|
+
RAW_FUNCS = {"raw", "unsafe", "literalRaw"}
|
|
109
|
+
IDENT_FUNCS = {"ref", "table", "id", "identifier", "ident", "name"}
|
|
110
|
+
JOIN_FUNCS = {"join", "csv", "and", "or", "array", "unnest", "values", "valuesList", "json", "jsonb", "lit", "val", "literal",
|
|
111
|
+
"empty", "param", "placeholder"}
|
|
112
|
+
# Properties of a compiled-query object that hold its text: `compiled.sql`, `query.text`.
|
|
113
|
+
SQL_PROPS = {"sql", "text", "query", "statement", "queryString", "rawSql"}
|
|
114
|
+
STRING_METHODS = {"trim", "trimStart", "trimEnd", "trimLeft", "trimRight", "toString", "valueOf", "normalize"}
|
|
115
|
+
REWRITE_METHODS = {"replace", "replaceAll", "format", "slice", "substring", "padEnd", "append", "setName", "concat"}
|
|
116
|
+
# A SQL literal passed to one of these is not a query: a log line, an assertion, an error.
|
|
117
|
+
NOT_A_SINK = re.compile(
|
|
118
|
+
r"^(?:console\.\w+|\w*[lL]og(?:ger)?\.\w+|expect|assert\w*|describe|it|test|debug|\w*Error|includes|startsWith|endsWith|"
|
|
119
|
+
r"indexOf|match|toBe|toEqual|toContain|toMatch\w*|toHaveBeenCalled\w*|toStrictEqual|toMatchInlineSnapshot|print\w*|"
|
|
120
|
+
r"logger|warn|info|error|trace)$|"
|
|
121
|
+
r"(?:^|\.)(?:log|debug|info|warn|error|trace|includes|startsWith|endsWith|indexOf|match|test|toBe|toEqual|toContain|"
|
|
122
|
+
r"toMatch\w*|toHaveBeenCalled\w*|toStrictEqual|toMatchInlineSnapshot|toThrow\w*|addBreadcrumb|captureMessage|"
|
|
123
|
+
r"setAttribute|setTag|span|startSpan)$")
|
|
124
|
+
NOT_WRAPPER_NAMES = {"then", "catch", "finally", "map", "forEach", "filter", "reduce", "constructor", "use", "call", "apply",
|
|
125
|
+
"bind", "push", "set", "has", "on", "emit", "log", "debug", "render", "default", "handler"}
|
|
126
|
+
RULE_OPTIONS = {"weak", "insert-table"}
|
|
127
|
+
ESCAPES = {"n": "\n", "t": "\t", "r": "\r", "\\": "\\", '"': '"', "'": "'", "`": "`", "$": "$", "\n": "", "0": "\0",
|
|
128
|
+
"b": "\b", "f": "\f", "v": "\v", "/": "/"}
|
|
129
|
+
|
|
130
|
+
TS_TEST_PATH = re.compile(
|
|
131
|
+
r"\.(?:test|spec|e2e-spec|e2e|integration-test|int-spec|stories|story|cy|bench|test-d)\.[cm]?[jt]sx?$|"
|
|
132
|
+
r"(?:^|/)(?:e2e|__mocks__|__fixtures__|cypress|playwright|test-utils|testing|mocks|__snapshots__|test-helpers)(?:/|$)")
|
|
133
|
+
# Build output, bundles and generated code: skipped by path. `list_files` already drops node_modules, dist, build, .next.
|
|
134
|
+
SKIP_PATH = re.compile(
|
|
135
|
+
r"\.d\.[cm]?ts$|\.min\.[cm]?js$|[.-]bundle\.[cm]?js$|\.generated\.[cm]?[jt]sx?$|\.gen\.[cm]?[jt]sx?$|_pb\.[jt]s$|"
|
|
136
|
+
r"(?:^|/)(?:out|coverage|\.turbo|\.output|\.nuxt|\.svelte-kit|\.vercel|\.cache|storybook-static|__generated__|"
|
|
137
|
+
r"generated|bower_components|\.yarn|\.pnp\.[cm]?js|vendor|third_party|\.docusaurus)(?:/|$)")
|
|
138
|
+
GENERATED_HEAD = re.compile(rb"@generated|DO NOT EDIT|do not edit|This file was automatically generated|"
|
|
139
|
+
rb"This file is auto-?generated|Code generated by|eslint-disable \*/\s*//\s*@ts-nocheck")
|
|
140
|
+
|
|
141
|
+
# ORM and query-builder calls: counted, never turned into SQL.
|
|
142
|
+
PRISMA_METHODS = (r"findMany|findFirst|findFirstOrThrow|findUnique|findUniqueOrThrow|create|createMany|createManyAndReturn|"
|
|
143
|
+
r"update|updateMany|updateManyAndReturn|upsert|delete|deleteMany|count|aggregate|groupBy")
|
|
144
|
+
PRISMA_GENERIC = re.compile(
|
|
145
|
+
rb"\.\s*[a-z]\w*\s*\.\s*(?:findMany|findFirstOrThrow|findUniqueOrThrow|findUnique|createManyAndReturn|deleteMany|"
|
|
146
|
+
rb"updateMany|createMany|upsert|groupBy)\s*\(")
|
|
147
|
+
ORM_PATTERNS = {
|
|
148
|
+
"typeorm": re.compile(
|
|
149
|
+
rb"\bcreateQueryBuilder\s*\(|(?:[rR]epository|[rR]epo|[mM]anager)\s*\.\s*(?:find|findOne|findOneBy|"
|
|
150
|
+
rb"findOneOrFail|findOneByOrFail|findBy|findAndCount|findAndCountBy|save|insert|update|delete|remove|softDelete|"
|
|
151
|
+
rb"softRemove|restore|count|countBy|exists|existsBy|exist|upsert|increment|decrement|sum|average|minimum|maximum)\s*\("),
|
|
152
|
+
"sequelize": re.compile(
|
|
153
|
+
rb"\.\s*(?:findAll|findByPk|findOrCreate|findAndCountAll|bulkCreate|findOne|findCreateFind|findOrBuild)\s*\("),
|
|
154
|
+
"kysely": re.compile(rb"\.\s*(?:selectFrom|insertInto|updateTable|deleteFrom|replaceInto|mergeInto)\s*\("),
|
|
155
|
+
"drizzle": re.compile(
|
|
156
|
+
rb"\.\s*(?:select|selectDistinct|selectDistinctOn)\s*\((?:[^()]|\([^()]*\))*\)\s*\.\s*from\s*\(|"
|
|
157
|
+
rb"\.\s*insert\s*\(\s*[\w.]+\s*\)\s*\.\s*values\s*\(|\.\s*update\s*\(\s*[\w.]+\s*\)\s*\.\s*set\s*\(|"
|
|
158
|
+
rb"\.\s*delete\s*\(\s*[\w.]+\s*\)|\.query\.\w+\.(?:findMany|findFirst)\s*\("),
|
|
159
|
+
"knex": re.compile(rb"(?:\bknex|Knex|\btrx|\bdb)\(\s*['\"`][\w.]+['\"`]\s*\)"),
|
|
160
|
+
"mikro-orm": re.compile(rb"(?:\bem|[rR]epository|[rR]epo)\s*\.\s*(?:find|findOne|findOneOrFail|findAll|findAndCount|"
|
|
161
|
+
rb"persistAndFlush|nativeInsert|nativeUpdate|nativeDelete|upsert|count)\s*\("),
|
|
162
|
+
}
|
|
163
|
+
ORM_PACKAGES = {"typeorm": ("typeorm", "@nestjs/typeorm"), "sequelize": ("sequelize", "sequelize-typescript"),
|
|
164
|
+
"kysely": ("kysely",), "drizzle": ("drizzle-orm",), "knex": ("knex",), "mikro-orm": ("@mikro-orm/core",),
|
|
165
|
+
"prisma": ("@prisma/client", "prisma")}
|
|
166
|
+
PRISMA_PROVIDERS = {"postgresql": "postgres", "postgres": "postgres", "cockroachdb": "postgres", "mysql": "mysql",
|
|
167
|
+
"sqlite": "sqlite", "sqlserver": "mssql"}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
from .base import READ # the run's size setting: a file over it is listed as skipped, never dropped silently
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def read_bytes(path: Path) -> bytes | None:
|
|
174
|
+
try:
|
|
175
|
+
if READ.too_large(path, path.stat().st_size):
|
|
176
|
+
return None
|
|
177
|
+
return path.read_bytes()
|
|
178
|
+
except OSError:
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def is_ts_test(rel: str) -> bool:
|
|
183
|
+
return is_test_path(rel) or bool(TS_TEST_PATH.search(rel))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def language_for(rel: str) -> Language:
|
|
187
|
+
return LANG_TS if rel.endswith((".ts", ".mts", ".cts")) else LANG_TSX
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class Res:
|
|
191
|
+
"""A resolved string: text with «expr» placeholders, and how it was reached."""
|
|
192
|
+
|
|
193
|
+
__slots__ = ("text", "dynamic", "via_name", "frag")
|
|
194
|
+
|
|
195
|
+
def __init__(self, text: str, dynamic: bool = False, via_name: bool = False, frag: bool = False):
|
|
196
|
+
self.text = text
|
|
197
|
+
self.dynamic = dynamic
|
|
198
|
+
self.via_name = via_name
|
|
199
|
+
self.frag = frag # a SQL fragment object (``sql`...` ``, ``Prisma.raw()``): inlined into a tagged template
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def resolution(self) -> str:
|
|
203
|
+
if self.dynamic:
|
|
204
|
+
return "template"
|
|
205
|
+
return "constant" if self.via_name else "literal"
|
|
206
|
+
|
|
207
|
+
def named(self) -> "Res":
|
|
208
|
+
return Res(self.text, self.dynamic, True, self.frag)
|
|
209
|
+
|
|
210
|
+
def dyn(self) -> "Res":
|
|
211
|
+
return Res(self.text, True, self.via_name, self.frag)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _raw_fragment(call: Node) -> bool:
|
|
215
|
+
"""A `x.raw(..)` call that is an argument (or an array item, or an object value) of another call: a query builder's
|
|
216
|
+
raw piece (a select column, a where clause), sent as part of the builder's statement, never on its own."""
|
|
217
|
+
p = call.parent
|
|
218
|
+
while p is not None and p.type in UNWRAP_TYPES:
|
|
219
|
+
p = p.parent
|
|
220
|
+
if p is not None and p.type == "pair":
|
|
221
|
+
p = p.parent
|
|
222
|
+
if p is not None and p.type in ("array", "object"):
|
|
223
|
+
p = p.parent
|
|
224
|
+
if p is None or p.type != "arguments" or p.parent is None:
|
|
225
|
+
return False
|
|
226
|
+
outer, _, _ = callee(p.parent.child_by_field_name("function"))
|
|
227
|
+
return outer not in ("all", "allSettled", "race", "any", "push", "then", "resolve", "map", "run", "execute", "query")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _join(parts: list[Res]) -> Res:
|
|
231
|
+
return Res("".join(p.text for p in parts), any(p.dynamic for p in parts), any(p.via_name for p in parts),
|
|
232
|
+
any(p.frag for p in parts))
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _txt(node: Node | None) -> str:
|
|
236
|
+
return node.text.decode("utf-8", "replace") if node is not None else ""
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _ph_text(text: str) -> Res:
|
|
240
|
+
# long enough that a later stage can read a short conditional arm (`c ? "INNER JOIN x USING (id)" : ""`)
|
|
241
|
+
return Res("«" + trim(text, 120).replace("»", ">") + "»", dynamic=True)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _ph(node: Node) -> Res:
|
|
245
|
+
return _ph_text(_txt(node))
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _walk(node: Node, stop: tuple[str, ...] = ()):
|
|
249
|
+
"""Depth-first over descendants, not descending into node types in `stop`."""
|
|
250
|
+
return walk_tree(node, stop)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _unescape(text: str) -> str:
|
|
254
|
+
if len(text) == 2:
|
|
255
|
+
return ESCAPES.get(text[1], text[1])
|
|
256
|
+
try:
|
|
257
|
+
if text[1] == "u":
|
|
258
|
+
return chr(int(text[2:].strip("{}"), 16))
|
|
259
|
+
if text[1] == "x":
|
|
260
|
+
return chr(int(text[2:], 16))
|
|
261
|
+
except ValueError:
|
|
262
|
+
pass
|
|
263
|
+
return text
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def decode_string(node: Node) -> str:
|
|
267
|
+
out = []
|
|
268
|
+
for c in node.children:
|
|
269
|
+
if c.type == "string_fragment":
|
|
270
|
+
out.append(_txt(c))
|
|
271
|
+
elif c.type == "escape_sequence":
|
|
272
|
+
out.append(_unescape(_txt(c)))
|
|
273
|
+
return "".join(out)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _unwrap(node: Node | None) -> Node | None:
|
|
277
|
+
while node is not None and node.type in UNWRAP_TYPES and node.named_children:
|
|
278
|
+
node = node.named_children[-1] if node.type == "type_assertion" else node.named_children[0]
|
|
279
|
+
return node
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def callee(fn: Node | None) -> tuple[str, Node | None, str]:
|
|
283
|
+
"""(name, receiver, dotted text) of what a call calls. The name is the last segment."""
|
|
284
|
+
fn = _unwrap(fn)
|
|
285
|
+
if fn is None:
|
|
286
|
+
return "", None, ""
|
|
287
|
+
if fn.type == "identifier":
|
|
288
|
+
return _txt(fn), None, _txt(fn)
|
|
289
|
+
if fn.type == "member_expression":
|
|
290
|
+
prop = fn.child_by_field_name("property")
|
|
291
|
+
return _txt(prop), fn.child_by_field_name("object"), _txt(fn) if fn.end_byte - fn.start_byte < 200 else _txt(prop)
|
|
292
|
+
if fn.type == "call_expression": # sql.type(Row)`...`, sql<Row>`...`
|
|
293
|
+
return callee(fn.child_by_field_name("function"))
|
|
294
|
+
return "", None, ""
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def call_args(call: Node) -> list[Node]:
|
|
298
|
+
args = call.child_by_field_name("arguments")
|
|
299
|
+
if args is None or args.type != "arguments":
|
|
300
|
+
return []
|
|
301
|
+
return [a for a in args.named_children if a.type != "comment"]
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def object_pairs(obj: Node) -> dict[str, Node]:
|
|
305
|
+
"""Key -> value node of an object literal. A shorthand `{ query }` maps to the identifier itself."""
|
|
306
|
+
out: dict[str, Node] = {}
|
|
307
|
+
for c in obj.named_children:
|
|
308
|
+
if c.type == "pair":
|
|
309
|
+
k, v = c.child_by_field_name("key"), c.child_by_field_name("value")
|
|
310
|
+
if k is not None and v is not None:
|
|
311
|
+
out[decode_string(k) if k.type == "string" else _txt(k)] = v
|
|
312
|
+
elif c.type == "shorthand_property_identifier":
|
|
313
|
+
out[_txt(c)] = c
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def object_spreads(obj: Node) -> list[Node]:
|
|
318
|
+
"""The identifiers spread into an object literal: `{ ...opts, format }` -> [opts]."""
|
|
319
|
+
out = []
|
|
320
|
+
for c in obj.named_children:
|
|
321
|
+
if c.type == "spread_element" and c.named_children and c.named_children[0].type == "identifier":
|
|
322
|
+
out.append(c.named_children[0])
|
|
323
|
+
return out
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def func_name(func: Node) -> str:
|
|
327
|
+
t = func.type
|
|
328
|
+
if t in ("function_declaration", "generator_function_declaration", "method_definition"):
|
|
329
|
+
return _txt(func.child_by_field_name("name"))
|
|
330
|
+
p = func.parent
|
|
331
|
+
while p is not None and p.type in UNWRAP_TYPES:
|
|
332
|
+
p = p.parent
|
|
333
|
+
if p is None:
|
|
334
|
+
return ""
|
|
335
|
+
if p.type == "variable_declarator":
|
|
336
|
+
nm = p.child_by_field_name("name")
|
|
337
|
+
return _txt(nm) if nm is not None and nm.type == "identifier" else ""
|
|
338
|
+
if p.type == "pair":
|
|
339
|
+
return _txt(p.child_by_field_name("key"))
|
|
340
|
+
if p.type == "public_field_definition":
|
|
341
|
+
return _txt(p.child_by_field_name("name"))
|
|
342
|
+
if p.type == "assignment_expression":
|
|
343
|
+
left = p.child_by_field_name("left")
|
|
344
|
+
if left is not None and left.type == "member_expression":
|
|
345
|
+
return _txt(left.child_by_field_name("property"))
|
|
346
|
+
return _txt(left) if left is not None and left.type == "identifier" else ""
|
|
347
|
+
return ""
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def params_of(func: Node) -> list[Node]:
|
|
351
|
+
params = func.child_by_field_name("parameters")
|
|
352
|
+
if params is None:
|
|
353
|
+
single = func.child_by_field_name("parameter")
|
|
354
|
+
return [single] if single is not None else []
|
|
355
|
+
out = []
|
|
356
|
+
for p in params.named_children:
|
|
357
|
+
if p.type in ("required_parameter", "optional_parameter"):
|
|
358
|
+
pat = p.child_by_field_name("pattern") or (p.named_children[0] if p.named_children else None)
|
|
359
|
+
if pat is not None and pat.type == "this":
|
|
360
|
+
continue
|
|
361
|
+
out.append(pat if pat is not None else p)
|
|
362
|
+
elif p.type != "comment":
|
|
363
|
+
out.append(p)
|
|
364
|
+
return out
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def param_index(func: Node, name: str) -> tuple[int, str] | None:
|
|
368
|
+
"""(positional index, key) when `name` is a parameter of `func`; key is set for `({ name })` destructuring."""
|
|
369
|
+
for i, p in enumerate(params_of(func)):
|
|
370
|
+
if p.type == "assignment_pattern":
|
|
371
|
+
p = p.child_by_field_name("left") or p
|
|
372
|
+
if p.type == "identifier" and _txt(p) == name:
|
|
373
|
+
return i, ""
|
|
374
|
+
if p.type == "object_pattern":
|
|
375
|
+
for c in p.named_children:
|
|
376
|
+
if c.type == "shorthand_property_identifier_pattern" and _txt(c) == name:
|
|
377
|
+
return i, name
|
|
378
|
+
if c.type == "object_assignment_pattern":
|
|
379
|
+
left = c.child_by_field_name("left")
|
|
380
|
+
if left is not None and _txt(left) == name:
|
|
381
|
+
return i, name
|
|
382
|
+
if c.type == "pair_pattern":
|
|
383
|
+
v = c.child_by_field_name("value")
|
|
384
|
+
if v is not None and v.type == "assignment_pattern":
|
|
385
|
+
v = v.child_by_field_name("left")
|
|
386
|
+
if v is not None and v.type == "identifier" and _txt(v) == name:
|
|
387
|
+
return i, _txt(c.child_by_field_name("key"))
|
|
388
|
+
return None
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def sinkish_sql(text: str, db: bool) -> bool:
|
|
392
|
+
"""Is a resolved sink argument SQL? A full statement always; a bare keyword start only in database code."""
|
|
393
|
+
if not text or len(text) < 6:
|
|
394
|
+
return False
|
|
395
|
+
if looks_like_sql(text, any_case=True):
|
|
396
|
+
return True
|
|
397
|
+
return db and bool(STATEMENT_START.match(text))
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
class Wrapper:
|
|
401
|
+
__slots__ = ("name", "index", "key", "engine", "db")
|
|
402
|
+
|
|
403
|
+
def __init__(self, name: str, index: int, key: str, engine: str, db: bool):
|
|
404
|
+
self.name, self.index, self.key, self.engine, self.db = name, index, key, engine, db
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
class Ctx:
|
|
408
|
+
"""Everything shared across files: rules, module resolution, wrappers, constants, statistics."""
|
|
409
|
+
|
|
410
|
+
def __init__(self, root: Path, files: list[str], rules: LangRules):
|
|
411
|
+
self.root = root
|
|
412
|
+
self.rules = rules
|
|
413
|
+
self.resolver = Resolver(root, files)
|
|
414
|
+
self.sources: dict[str, bytes] = {}
|
|
415
|
+
self.parsed: dict[str, "TsFile | None"] = {}
|
|
416
|
+
self.sink_rules: dict[str, tuple[str, list[int], set[str]]] = {} # callee name -> (engine, args, options)
|
|
417
|
+
self.tag_rules: dict[str, str] = {} # template tag -> engine
|
|
418
|
+
for s in rules.sinks:
|
|
419
|
+
for name in s.names:
|
|
420
|
+
if name.startswith("`"):
|
|
421
|
+
self.tag_rules[name[1:]] = s.engine
|
|
422
|
+
else:
|
|
423
|
+
self.sink_rules[name] = (s.engine, s.args, s.kwargs)
|
|
424
|
+
self.wrappers: dict[str, list[Wrapper]] = defaultdict(list)
|
|
425
|
+
self.global_consts: dict[str, set[str]] = defaultdict(set)
|
|
426
|
+
self.used_globals: set[str] = set()
|
|
427
|
+
self.fragments = 0
|
|
428
|
+
self.prisma_engine: dict[str, str] = {} # directory of a schema.prisma -> engine
|
|
429
|
+
self.prisma_models: set[str] = set()
|
|
430
|
+
self._pkg_engine: dict[tuple[str, bool], str] = {}
|
|
431
|
+
self._find_prisma()
|
|
432
|
+
|
|
433
|
+
# ---- files ------------------------------------------------------------------
|
|
434
|
+
def file(self, rel: str) -> "TsFile | None":
|
|
435
|
+
if rel not in self.parsed:
|
|
436
|
+
self.parsed[rel] = None
|
|
437
|
+
src = self.sources.get(rel)
|
|
438
|
+
if src is None:
|
|
439
|
+
src = read_bytes(self.root / rel) if rel in self.resolver.files else None
|
|
440
|
+
if src is not None:
|
|
441
|
+
try:
|
|
442
|
+
self.parsed[rel] = TsFile(rel, src, self)
|
|
443
|
+
except Exception: # one odd file must not stop the inventory
|
|
444
|
+
self.parsed[rel] = None
|
|
445
|
+
return self.parsed[rel]
|
|
446
|
+
|
|
447
|
+
# ---- engines ------------------------------------------------------------------
|
|
448
|
+
def import_engine(self, spec: str) -> str | None:
|
|
449
|
+
"""Engine of an imported module ("" for a database API that names none), or None when it is not one."""
|
|
450
|
+
imports = self.rules.imports
|
|
451
|
+
while spec:
|
|
452
|
+
if spec in imports:
|
|
453
|
+
return imports[spec]
|
|
454
|
+
spec = spec.rpartition("/")[0]
|
|
455
|
+
return None
|
|
456
|
+
|
|
457
|
+
def _find_prisma(self) -> None:
|
|
458
|
+
seen: set[str] = set()
|
|
459
|
+
for d in sorted(self.resolver.dirs):
|
|
460
|
+
pkg = self.resolver.package_json(d)
|
|
461
|
+
cands = [f"{d}/schema.prisma" if d else "schema.prisma"]
|
|
462
|
+
if pkg is not None or not d:
|
|
463
|
+
cands += [os.path.join(d, "prisma", "schema.prisma"), os.path.join(d, "prisma", "schema"),
|
|
464
|
+
os.path.join(d, "prisma")]
|
|
465
|
+
conf = (pkg or {}).get("prisma")
|
|
466
|
+
if isinstance(conf, dict) and isinstance(conf.get("schema"), str):
|
|
467
|
+
cands.append(os.path.normpath(os.path.join(d, conf["schema"])))
|
|
468
|
+
for c in cands:
|
|
469
|
+
p = self.root / c
|
|
470
|
+
paths = sorted(p.glob("**/*.prisma")) if p.is_dir() else [p] if p.is_file() else []
|
|
471
|
+
for path in paths:
|
|
472
|
+
if str(path) in seen:
|
|
473
|
+
continue
|
|
474
|
+
seen.add(str(path))
|
|
475
|
+
text = read_text(path)
|
|
476
|
+
if text is None:
|
|
477
|
+
continue
|
|
478
|
+
m = re.search(r"datasource\s+\w+\s*\{[^}]*?provider\s*=\s*\"(\w+)\"", text, re.S)
|
|
479
|
+
if m:
|
|
480
|
+
self.prisma_engine[os.path.dirname(c) if p.is_file() else c] = PRISMA_PROVIDERS.get(m.group(1), "")
|
|
481
|
+
for mm in re.finditer(r"(?m)^\s*model\s+(\w+)\s*\{", text):
|
|
482
|
+
self.prisma_models.add(mm.group(1))
|
|
483
|
+
|
|
484
|
+
def prisma_provider(self, rel: str) -> str:
|
|
485
|
+
"""Engine of the Prisma schema nearest to a file; the only one in the repo when there is one."""
|
|
486
|
+
if not self.prisma_engine:
|
|
487
|
+
return ""
|
|
488
|
+
best, best_len = "", -1
|
|
489
|
+
d = os.path.dirname(rel)
|
|
490
|
+
for sdir, engine in self.prisma_engine.items():
|
|
491
|
+
parts = sdir.split("/")
|
|
492
|
+
base = "/".join(parts[: len(parts) - 1 - parts[::-1].index("prisma")]) if "prisma" in parts else os.path.dirname(sdir)
|
|
493
|
+
if (d == base or d.startswith(base + "/") or not base) and len(base) > best_len:
|
|
494
|
+
best, best_len = engine, len(base)
|
|
495
|
+
if best_len >= 0:
|
|
496
|
+
return best
|
|
497
|
+
engines = set(self.prisma_engine.values())
|
|
498
|
+
return next(iter(engines)) if len(engines) == 1 else ""
|
|
499
|
+
|
|
500
|
+
def package_engine(self, rel: str, relational: bool = False) -> str:
|
|
501
|
+
"""The one engine the nearest package depends on, when a file's own imports name none. With
|
|
502
|
+
`relational` (the file uses TypeORM, Knex, Kysely, Drizzle or Sequelize, none of which speaks
|
|
503
|
+
ClickHouse) a ClickHouse client beside one relational driver does not make it ambiguous."""
|
|
504
|
+
near = self.resolver.nearest_package(rel)
|
|
505
|
+
if near is None:
|
|
506
|
+
return ""
|
|
507
|
+
d, pkg = near
|
|
508
|
+
got = self._pkg_engine.get((d, relational))
|
|
509
|
+
if got is None:
|
|
510
|
+
engines: set[str] = set()
|
|
511
|
+
for key in ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies"):
|
|
512
|
+
deps = pkg.get(key)
|
|
513
|
+
for dep in (deps if isinstance(deps, dict) else {}):
|
|
514
|
+
e = self.rules.imports.get(dep)
|
|
515
|
+
if e == "prisma":
|
|
516
|
+
e = self.prisma_provider(os.path.join(d, "x"))
|
|
517
|
+
if e:
|
|
518
|
+
engines.add(e)
|
|
519
|
+
if relational:
|
|
520
|
+
engines.discard("clickhouse")
|
|
521
|
+
got = next(iter(engines)) if len(engines) == 1 else ""
|
|
522
|
+
self._pkg_engine[(d, relational)] = got
|
|
523
|
+
return got
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
class TsFile:
|
|
527
|
+
def __init__(self, rel: str, src: bytes, ctx: Ctx):
|
|
528
|
+
self.rel = rel
|
|
529
|
+
self.src = src
|
|
530
|
+
self.ctx = ctx
|
|
531
|
+
self.lang = language_for(rel)
|
|
532
|
+
self.tree = Parser(self.lang).parse(src)
|
|
533
|
+
self.root = self.tree.root_node
|
|
534
|
+
self.test = is_ts_test(rel)
|
|
535
|
+
caps = QueryCursor(SCAN[id(self.lang)]).captures(self.root)
|
|
536
|
+
self.calls: list[Node] = caps.get("call", [])
|
|
537
|
+
self.strings: list[Node] = caps.get("str", [])
|
|
538
|
+
self.imports: dict[str, tuple[str, str]] = {} # local name -> (module specifier, imported name or "*" / "default")
|
|
539
|
+
self.modules: set[str] = set()
|
|
540
|
+
self.funcs: dict[str, Node] = {}
|
|
541
|
+
self.consumed: set[int] = set()
|
|
542
|
+
self._resolving: set[int] = set()
|
|
543
|
+
self._scope_cache: dict[int, dict[str, list[Node]]] = {}
|
|
544
|
+
self._funcs_done = False
|
|
545
|
+
self._engine: str | None = None
|
|
546
|
+
self.has_db = False
|
|
547
|
+
self._index(caps.get("imp", []))
|
|
548
|
+
|
|
549
|
+
# ---- indexing -------------------------------------------------------------------
|
|
550
|
+
def _index(self, import_nodes: list[Node]) -> None:
|
|
551
|
+
for n in import_nodes:
|
|
552
|
+
source = n.child_by_field_name("source")
|
|
553
|
+
if source is None:
|
|
554
|
+
continue
|
|
555
|
+
spec = decode_string(source)
|
|
556
|
+
self.modules.add(spec)
|
|
557
|
+
for c in n.named_children:
|
|
558
|
+
if c.type != "import_clause":
|
|
559
|
+
continue
|
|
560
|
+
for part in c.named_children:
|
|
561
|
+
if part.type == "identifier":
|
|
562
|
+
self.imports[_txt(part)] = (spec, "default")
|
|
563
|
+
elif part.type == "namespace_import":
|
|
564
|
+
ident = next((x for x in part.named_children if x.type == "identifier"), None)
|
|
565
|
+
if ident is not None:
|
|
566
|
+
self.imports[_txt(ident)] = (spec, "*")
|
|
567
|
+
elif part.type == "named_imports":
|
|
568
|
+
for spec_node in part.named_children:
|
|
569
|
+
if spec_node.type != "import_specifier":
|
|
570
|
+
continue
|
|
571
|
+
name = spec_node.child_by_field_name("name")
|
|
572
|
+
alias = spec_node.child_by_field_name("alias")
|
|
573
|
+
if name is not None:
|
|
574
|
+
self.imports[_txt(alias or name)] = (spec, _txt(name))
|
|
575
|
+
# const x = require("y"), const { a, b: c } = require("y")
|
|
576
|
+
for call in self.calls:
|
|
577
|
+
fn = call.child_by_field_name("function")
|
|
578
|
+
if fn is None or fn.type != "identifier" or fn.text != b"require":
|
|
579
|
+
continue
|
|
580
|
+
args = call_args(call)
|
|
581
|
+
if len(args) != 1 or args[0].type != "string":
|
|
582
|
+
continue
|
|
583
|
+
spec = decode_string(args[0])
|
|
584
|
+
self.modules.add(spec)
|
|
585
|
+
decl = call.parent
|
|
586
|
+
if decl is None or decl.type != "variable_declarator":
|
|
587
|
+
continue
|
|
588
|
+
name = decl.child_by_field_name("name")
|
|
589
|
+
if name is None:
|
|
590
|
+
continue
|
|
591
|
+
if name.type == "identifier":
|
|
592
|
+
self.imports[_txt(name)] = (spec, "*")
|
|
593
|
+
elif name.type == "object_pattern":
|
|
594
|
+
for c in name.named_children:
|
|
595
|
+
if c.type == "shorthand_property_identifier_pattern":
|
|
596
|
+
self.imports[_txt(c)] = (spec, _txt(c))
|
|
597
|
+
elif c.type == "pair_pattern":
|
|
598
|
+
v = c.child_by_field_name("value")
|
|
599
|
+
if v is not None and v.type == "identifier":
|
|
600
|
+
self.imports[_txt(v)] = (spec, _txt(c.child_by_field_name("key")))
|
|
601
|
+
engines = set()
|
|
602
|
+
self.generic_db = False
|
|
603
|
+
for spec in self.modules:
|
|
604
|
+
e = self.ctx.import_engine(spec)
|
|
605
|
+
if e is None:
|
|
606
|
+
continue
|
|
607
|
+
self.has_db = True
|
|
608
|
+
self.generic_db = self.generic_db or e == ""
|
|
609
|
+
if e == "prisma":
|
|
610
|
+
e = self.ctx.prisma_provider(self.rel)
|
|
611
|
+
if e:
|
|
612
|
+
engines.add(e)
|
|
613
|
+
self._import_engines = engines
|
|
614
|
+
|
|
615
|
+
def file_engine(self) -> str:
|
|
616
|
+
if self._engine is None:
|
|
617
|
+
engines = self._import_engines
|
|
618
|
+
self._engine = next(iter(engines)) if len(engines) == 1 else "" if engines else \
|
|
619
|
+
self.ctx.package_engine(self.rel, relational=self.generic_db)
|
|
620
|
+
return self._engine
|
|
621
|
+
|
|
622
|
+
def _index_funcs(self) -> None:
|
|
623
|
+
if self._funcs_done:
|
|
624
|
+
return
|
|
625
|
+
self._funcs_done = True
|
|
626
|
+
for n in _walk(self.root):
|
|
627
|
+
if n.type in FUNC_TYPES:
|
|
628
|
+
name = func_name(n)
|
|
629
|
+
if name:
|
|
630
|
+
self.funcs.setdefault(name, n)
|
|
631
|
+
|
|
632
|
+
def _assigns(self, scope: Node) -> dict[str, list[Node]]:
|
|
633
|
+
"""Assignments to plain names directly in a function body (or at module level), in source order."""
|
|
634
|
+
cached = self._scope_cache.get(scope.id)
|
|
635
|
+
if cached is None:
|
|
636
|
+
cached = defaultdict(list)
|
|
637
|
+
body = scope.child_by_field_name("body") or scope
|
|
638
|
+
for n in _walk(body, stop=FUNC_TYPES):
|
|
639
|
+
if n.type == "variable_declarator":
|
|
640
|
+
name = n.child_by_field_name("name")
|
|
641
|
+
if name is not None and name.type == "identifier" and n.child_by_field_name("value") is not None:
|
|
642
|
+
cached[_txt(name)].append(n)
|
|
643
|
+
elif n.type in ("assignment_expression", "augmented_assignment_expression"):
|
|
644
|
+
left = n.child_by_field_name("left")
|
|
645
|
+
if left is not None and left.type == "identifier":
|
|
646
|
+
cached[_txt(left)].append(n)
|
|
647
|
+
self._scope_cache[scope.id] = cached
|
|
648
|
+
return cached
|
|
649
|
+
|
|
650
|
+
@staticmethod
|
|
651
|
+
def _enclosing(node: Node, types: tuple[str, ...]) -> Node | None:
|
|
652
|
+
n = node.parent
|
|
653
|
+
while n is not None:
|
|
654
|
+
if n.type in types:
|
|
655
|
+
return n
|
|
656
|
+
n = n.parent
|
|
657
|
+
return None
|
|
658
|
+
|
|
659
|
+
def _scopes(self, node: Node):
|
|
660
|
+
"""Enclosing functions, innermost first."""
|
|
661
|
+
n = node.parent
|
|
662
|
+
while n is not None:
|
|
663
|
+
if n.type in FUNC_TYPES:
|
|
664
|
+
yield n
|
|
665
|
+
n = n.parent
|
|
666
|
+
|
|
667
|
+
# ---- resolution -------------------------------------------------------------------
|
|
668
|
+
def resolve(self, node: Node | None, at: Node | None, depth: int = 0) -> Res | None:
|
|
669
|
+
"""Resolve an expression to SQL text. `at` is the call it feeds, used to pick the assignments
|
|
670
|
+
that precede it. Returns None when nothing is known."""
|
|
671
|
+
node = _unwrap(node)
|
|
672
|
+
if node is None or depth > MAX_DEPTH:
|
|
673
|
+
return None
|
|
674
|
+
t = node.type
|
|
675
|
+
if t == "string":
|
|
676
|
+
return Res(decode_string(node))
|
|
677
|
+
if t == "template_string":
|
|
678
|
+
return self._template(node, at, depth, tagged=False)
|
|
679
|
+
if t == "number" and depth > 0: # `${EVENT_TYPE.pageView}` where the constant is a number
|
|
680
|
+
return Res(_txt(node))
|
|
681
|
+
if t == "binary_expression":
|
|
682
|
+
op = _txt(node.child_by_field_name("operator"))
|
|
683
|
+
left, right = node.child_by_field_name("left"), node.child_by_field_name("right")
|
|
684
|
+
if op == "+":
|
|
685
|
+
l, r = self.resolve(left, at, depth), self.resolve(right, at, depth)
|
|
686
|
+
if l is None and r is None:
|
|
687
|
+
return None
|
|
688
|
+
return _join([l or _ph(left), r or _ph(right)])
|
|
689
|
+
if op in ("||", "??"):
|
|
690
|
+
for side in (left, right):
|
|
691
|
+
r = self.resolve(side, at, depth)
|
|
692
|
+
if r is not None and len(r.text) > 8:
|
|
693
|
+
return r.dyn()
|
|
694
|
+
return None
|
|
695
|
+
if t in ("identifier", "shorthand_property_identifier"):
|
|
696
|
+
return self._name(node, at, depth)
|
|
697
|
+
if t == "member_expression":
|
|
698
|
+
return self._member(node, at, depth)
|
|
699
|
+
if t == "ternary_expression":
|
|
700
|
+
for key in ("consequence", "alternative"):
|
|
701
|
+
r = self.resolve(node.child_by_field_name(key), at, depth)
|
|
702
|
+
if r is not None and len(r.text) > 8:
|
|
703
|
+
return r.dyn()
|
|
704
|
+
return None
|
|
705
|
+
if t == "call_expression":
|
|
706
|
+
return self._call(node, at, depth)
|
|
707
|
+
return None
|
|
708
|
+
|
|
709
|
+
def _template(self, node: Node, at: Node | None, depth: int, tagged: bool) -> Res:
|
|
710
|
+
parts: list[Res] = []
|
|
711
|
+
for c in node.children:
|
|
712
|
+
if c.type == "string_fragment":
|
|
713
|
+
parts.append(Res(_txt(c)))
|
|
714
|
+
elif c.type == "escape_sequence":
|
|
715
|
+
parts.append(Res(_unescape(_txt(c))))
|
|
716
|
+
elif c.type == "template_substitution":
|
|
717
|
+
expr = _unwrap(c.named_children[0]) if c.named_children else None
|
|
718
|
+
if expr is None:
|
|
719
|
+
parts.append(_ph(c))
|
|
720
|
+
continue
|
|
721
|
+
r = None
|
|
722
|
+
# `${cond ? "AND x = 1" : ""}` stays a run-time part: which arm runs is not known here
|
|
723
|
+
if expr.type in ("identifier", "member_expression", "call_expression", "template_string", "string",
|
|
724
|
+
"binary_expression"):
|
|
725
|
+
r = self.resolve(expr, at, depth + 1)
|
|
726
|
+
if r is not None and tagged and not r.frag:
|
|
727
|
+
r = None # a value bound as a parameter, not text
|
|
728
|
+
parts.append(r.named() if r is not None and expr.type in ("identifier", "member_expression")
|
|
729
|
+
else r if r is not None else _ph(expr))
|
|
730
|
+
return _join(parts) if parts else Res("")
|
|
731
|
+
|
|
732
|
+
def _decl(self, name: str, anchor: Node | None) -> tuple[Node, list[Node], bool] | None:
|
|
733
|
+
"""(last plain assignment, the `+=` after it, branched) for a local or module-level name."""
|
|
734
|
+
scopes = list(self._scopes(anchor)) if anchor is not None else []
|
|
735
|
+
for func in scopes:
|
|
736
|
+
assigns = [a for a in self._assigns(func).get(name, ()) if a.end_byte <= anchor.start_byte]
|
|
737
|
+
if assigns:
|
|
738
|
+
last = max((i for i, a in enumerate(assigns) if a.type != "augmented_assignment_expression"), default=None)
|
|
739
|
+
if last is None:
|
|
740
|
+
return None
|
|
741
|
+
return assigns[last], assigns[last + 1:], last > 0
|
|
742
|
+
if param_index(func, name) is not None:
|
|
743
|
+
return None
|
|
744
|
+
assigns = self._assigns(self.root).get(name)
|
|
745
|
+
if assigns:
|
|
746
|
+
if anchor is not None and not scopes:
|
|
747
|
+
before = [a for a in assigns if a.end_byte <= anchor.start_byte]
|
|
748
|
+
assigns = before or assigns[:1]
|
|
749
|
+
last = max((i for i, a in enumerate(assigns) if a.type != "augmented_assignment_expression"), default=None)
|
|
750
|
+
if last is not None:
|
|
751
|
+
return assigns[last], assigns[last + 1:] if not scopes else [], last > 0
|
|
752
|
+
return None
|
|
753
|
+
|
|
754
|
+
@staticmethod
|
|
755
|
+
def _value(assign: Node) -> Node | None:
|
|
756
|
+
return assign.child_by_field_name("value" if assign.type == "variable_declarator" else "right")
|
|
757
|
+
|
|
758
|
+
def _name(self, node: Node, at: Node | None, depth: int) -> Res | None:
|
|
759
|
+
name = _txt(node)
|
|
760
|
+
anchor = at or node
|
|
761
|
+
if name == "undefined":
|
|
762
|
+
return None
|
|
763
|
+
for func in self._scopes(anchor):
|
|
764
|
+
if self._assigns(func).get(name):
|
|
765
|
+
break
|
|
766
|
+
if param_index(func, name) is not None:
|
|
767
|
+
return None
|
|
768
|
+
decl = self._decl(name, anchor)
|
|
769
|
+
if decl is not None:
|
|
770
|
+
first, later, branched = decl
|
|
771
|
+
if first.id in self._resolving:
|
|
772
|
+
return None
|
|
773
|
+
self._resolving.add(first.id)
|
|
774
|
+
try:
|
|
775
|
+
base = self.resolve(self._value(first), first, depth + 1)
|
|
776
|
+
if base is None:
|
|
777
|
+
return None
|
|
778
|
+
parts = [base]
|
|
779
|
+
for a in later:
|
|
780
|
+
if _txt(a.child_by_field_name("operator")) == "+=":
|
|
781
|
+
right = a.child_by_field_name("right")
|
|
782
|
+
parts.append(self.resolve(right, a, depth + 1) or _ph(right))
|
|
783
|
+
r = _join(parts)
|
|
784
|
+
for a in [first] + later:
|
|
785
|
+
self._consume(a)
|
|
786
|
+
return Res(r.text, r.dynamic or branched, True, r.frag)
|
|
787
|
+
finally:
|
|
788
|
+
self._resolving.discard(first.id)
|
|
789
|
+
imported = self._imported(name, depth)
|
|
790
|
+
if imported is not None:
|
|
791
|
+
return imported
|
|
792
|
+
return self._global(name)
|
|
793
|
+
|
|
794
|
+
def _imported(self, name: str, depth: int) -> Res | None:
|
|
795
|
+
imp = self.imports.get(name)
|
|
796
|
+
if imp is None or imp[1] == "*":
|
|
797
|
+
return None
|
|
798
|
+
target = self.ctx.resolver.resolve(self.rel, imp[0])
|
|
799
|
+
if target is None:
|
|
800
|
+
return None
|
|
801
|
+
r = self.ctx.exported_value(target, imp[1], depth + 1)
|
|
802
|
+
if r is not None and r.text:
|
|
803
|
+
self.ctx.used_globals.add(r.text)
|
|
804
|
+
return r.named()
|
|
805
|
+
return None
|
|
806
|
+
|
|
807
|
+
def export_value(self, name: str, depth: int) -> Res | None:
|
|
808
|
+
"""Value of a module-level name of this file, for a file that imports it."""
|
|
809
|
+
decl = self._decl(name, None)
|
|
810
|
+
if decl is None:
|
|
811
|
+
return None
|
|
812
|
+
first, later, branched = decl
|
|
813
|
+
if first.id in self._resolving or depth > MAX_DEPTH:
|
|
814
|
+
return None
|
|
815
|
+
self._resolving.add(first.id)
|
|
816
|
+
try:
|
|
817
|
+
r = self.resolve(self._value(first), first, depth + 1)
|
|
818
|
+
finally:
|
|
819
|
+
self._resolving.discard(first.id)
|
|
820
|
+
return r.dyn() if r is not None and branched else r
|
|
821
|
+
|
|
822
|
+
def _global(self, name: str) -> Res | None:
|
|
823
|
+
if not CONST_NAME.match(name):
|
|
824
|
+
return None
|
|
825
|
+
values = self.ctx.global_consts.get(name)
|
|
826
|
+
if values and len(values) == 1:
|
|
827
|
+
value = next(iter(values))
|
|
828
|
+
self.ctx.used_globals.add(value)
|
|
829
|
+
return Res(value, False, True)
|
|
830
|
+
return None
|
|
831
|
+
|
|
832
|
+
def _object_node(self, name: str, anchor: Node | None, depth: int) -> tuple["TsFile", Node] | None:
|
|
833
|
+
"""The object literal a name is bound to, here or in the file it is imported from."""
|
|
834
|
+
decl = self._decl(name, anchor)
|
|
835
|
+
if decl is not None:
|
|
836
|
+
value = _unwrap(self._value(decl[0]))
|
|
837
|
+
if value is not None and value.type == "call_expression" and len(call_args(value)) == 1 and \
|
|
838
|
+
_txt(value.child_by_field_name("function")) in ("Object.freeze", "Object.seal"):
|
|
839
|
+
value = _unwrap(call_args(value)[0]) # const STATES = Object.freeze({ active: "active" })
|
|
840
|
+
if value is not None and value.type == "object":
|
|
841
|
+
return self, value
|
|
842
|
+
return None
|
|
843
|
+
imp = self.imports.get(name)
|
|
844
|
+
if imp is None or depth > 3:
|
|
845
|
+
return None
|
|
846
|
+
if imp[1] == "*":
|
|
847
|
+
return None
|
|
848
|
+
hit = self.ctx.declaring(self.ctx.resolver.resolve(self.rel, imp[0]), imp[1])
|
|
849
|
+
other = self.ctx.file(hit[0]) if hit is not None else None
|
|
850
|
+
if other is None or other is self:
|
|
851
|
+
return None
|
|
852
|
+
return other._object_node(hit[1], None, depth + 1)
|
|
853
|
+
|
|
854
|
+
def _member(self, node: Node, at: Node | None, depth: int) -> Res | None:
|
|
855
|
+
obj = _unwrap(node.child_by_field_name("object"))
|
|
856
|
+
prop = _txt(node.child_by_field_name("property"))
|
|
857
|
+
if obj is None or not prop:
|
|
858
|
+
return None
|
|
859
|
+
if obj.type == "identifier":
|
|
860
|
+
oname = _txt(obj)
|
|
861
|
+
hit = self._object_node(oname, at or node, depth)
|
|
862
|
+
if hit is not None:
|
|
863
|
+
owner, literal = hit
|
|
864
|
+
value = object_pairs(literal).get(prop)
|
|
865
|
+
if value is not None and value.id not in owner._resolving:
|
|
866
|
+
owner._resolving.add(value.id)
|
|
867
|
+
try:
|
|
868
|
+
r = owner.resolve(value, value, depth + 1)
|
|
869
|
+
finally:
|
|
870
|
+
owner._resolving.discard(value.id)
|
|
871
|
+
if r is not None:
|
|
872
|
+
if owner is self:
|
|
873
|
+
self._consume(value)
|
|
874
|
+
elif r.text:
|
|
875
|
+
self.ctx.used_globals.add(r.text)
|
|
876
|
+
return r.named()
|
|
877
|
+
return None
|
|
878
|
+
if prop in SQL_PROPS: # const q = chSql`SELECT ...`; client.query({ query: q.sql, query_params: q.params })
|
|
879
|
+
r = self._name(obj, at, depth + 1)
|
|
880
|
+
if r is not None and (r.frag or looks_like_sql(r.text, any_case=True)):
|
|
881
|
+
return r
|
|
882
|
+
imp = self.imports.get(oname)
|
|
883
|
+
if imp is not None and imp[1] == "*": # import * as queries from "./queries"
|
|
884
|
+
target = self.ctx.resolver.resolve(self.rel, imp[0])
|
|
885
|
+
if target is not None:
|
|
886
|
+
r = self.ctx.exported_value(target, prop, depth + 1)
|
|
887
|
+
if r is not None and r.text:
|
|
888
|
+
self.ctx.used_globals.add(r.text)
|
|
889
|
+
return r.named()
|
|
890
|
+
return None
|
|
891
|
+
if obj.type == "this" or (obj.type == "identifier" and _txt(obj)[:1].isupper()):
|
|
892
|
+
cls = self._enclosing(node, CLASS_TYPES) if obj.type == "this" else self._class_named(_txt(obj))
|
|
893
|
+
body = cls.child_by_field_name("body") if cls is not None else None
|
|
894
|
+
for member in (body.named_children if body is not None else ()):
|
|
895
|
+
if member.type == "public_field_definition" and _txt(member.child_by_field_name("name")) == prop:
|
|
896
|
+
value = member.child_by_field_name("value")
|
|
897
|
+
if value is not None and value.id not in self._resolving:
|
|
898
|
+
self._resolving.add(value.id)
|
|
899
|
+
try:
|
|
900
|
+
r = self.resolve(value, value, depth + 1)
|
|
901
|
+
finally:
|
|
902
|
+
self._resolving.discard(value.id)
|
|
903
|
+
if r is not None:
|
|
904
|
+
self._consume(value)
|
|
905
|
+
return r.named()
|
|
906
|
+
return self._global(prop)
|
|
907
|
+
|
|
908
|
+
def _class_named(self, name: str) -> Node | None:
|
|
909
|
+
for n in self.root.named_children:
|
|
910
|
+
decl = n.child_by_field_name("declaration") if n.type == "export_statement" else n
|
|
911
|
+
if decl is not None and decl.type in CLASS_TYPES and _txt(decl.child_by_field_name("name")) == name:
|
|
912
|
+
return decl
|
|
913
|
+
return None
|
|
914
|
+
|
|
915
|
+
def _call(self, node: Node, at: Node | None, depth: int) -> Res | None:
|
|
916
|
+
fn = node.child_by_field_name("function")
|
|
917
|
+
args_node = node.child_by_field_name("arguments")
|
|
918
|
+
name, recv, _ = callee(fn)
|
|
919
|
+
if args_node is None:
|
|
920
|
+
return None
|
|
921
|
+
if args_node.type == "template_string": # a tagged template
|
|
922
|
+
if name in NON_SQL_TAGS or (recv is not None and _txt(recv).split(".")[0] in NON_SQL_TAGS):
|
|
923
|
+
return None
|
|
924
|
+
if name in PASS_TAGS and name not in self.ctx.tag_rules or (name == "raw" and _txt(recv) == "String"):
|
|
925
|
+
return self._template(args_node, at, depth, tagged=False)
|
|
926
|
+
r = self._template(args_node, at, depth, tagged=True)
|
|
927
|
+
return Res(r.text, r.dynamic, r.via_name, True)
|
|
928
|
+
args = call_args(node)
|
|
929
|
+
fn_node = _unwrap(fn)
|
|
930
|
+
if fn_node is not None and fn_node.type == "member_expression" and recv is not None:
|
|
931
|
+
if name in STRING_METHODS or name in REWRITE_METHODS:
|
|
932
|
+
base = self.resolve(recv, at, depth)
|
|
933
|
+
if base is not None:
|
|
934
|
+
if name == "concat":
|
|
935
|
+
return _join([base] + [self.resolve(a, at, depth + 1) or _ph(a) for a in args])
|
|
936
|
+
return base.dyn() if name in REWRITE_METHODS else base
|
|
937
|
+
if name in REWRITE_METHODS and name not in ("format", "append"):
|
|
938
|
+
return None
|
|
939
|
+
if name == "join" and _unwrap(recv) is not None and _unwrap(recv).type == "array":
|
|
940
|
+
sep = self.resolve(args[0], at, depth + 1) if args else Res(",")
|
|
941
|
+
items = [self.resolve(e, at, depth + 1) or _ph(e) for e in _unwrap(recv).named_children if e.type != "comment"]
|
|
942
|
+
if sep is not None and items and any(not i.text.startswith("«") for i in items):
|
|
943
|
+
out: list[Res] = []
|
|
944
|
+
for i, item in enumerate(items):
|
|
945
|
+
if i:
|
|
946
|
+
out.append(sep)
|
|
947
|
+
out.append(item)
|
|
948
|
+
return _join(out)
|
|
949
|
+
return None
|
|
950
|
+
# inside a tagged template: raw text, identifiers, lists
|
|
951
|
+
if name in RAW_FUNCS and len(args) >= 1:
|
|
952
|
+
inner = self.resolve(args[0], at, depth + 1)
|
|
953
|
+
r = inner if inner is not None else _ph(args[0])
|
|
954
|
+
return Res(r.text, r.dynamic, r.via_name, True)
|
|
955
|
+
if name in IDENT_FUNCS and args:
|
|
956
|
+
parts = []
|
|
957
|
+
for a in (args[0].named_children if args[0].type == "array" else args):
|
|
958
|
+
r = self.resolve(a, at, depth + 1) if a.type in ("string", "template_string", "identifier", "member_expression") else None
|
|
959
|
+
parts.append(r.text if r is not None and re.fullmatch(r"[\w.$\"]+", r.text) else _ph(a).text)
|
|
960
|
+
return Res(".".join(parts), any("«" in p for p in parts), False, True)
|
|
961
|
+
if name in JOIN_FUNCS and _txt(recv).split(".")[-1] in ("sql", "Prisma", "SQL", "db", "knex", "eb"):
|
|
962
|
+
if name == "empty":
|
|
963
|
+
return Res("", False, False, True)
|
|
964
|
+
r = _ph(node)
|
|
965
|
+
return Res(r.text, True, False, True)
|
|
966
|
+
if fn_node is not None and fn_node.type == "identifier" and name in self.ctx.tag_rules:
|
|
967
|
+
# postgres.js helpers: sql("table"), sql(columns), sql(rows, "a", "b")
|
|
968
|
+
if len(args) == 1 and args[0].type == "string" and re.fullmatch(r"[\w.$]+", decode_string(args[0])):
|
|
969
|
+
return Res(decode_string(args[0]), False, False, True)
|
|
970
|
+
r = _ph(node)
|
|
971
|
+
return Res(r.text, True, False, True)
|
|
972
|
+
# a helper that returns the SQL: here, or in the file it is imported from
|
|
973
|
+
target = self._find_func(fn_node, name)
|
|
974
|
+
if target is not None:
|
|
975
|
+
owner, func = target
|
|
976
|
+
if func.id not in owner._resolving:
|
|
977
|
+
owner._resolving.add(func.id)
|
|
978
|
+
try:
|
|
979
|
+
r = owner._func_return(func, depth + 1)
|
|
980
|
+
finally:
|
|
981
|
+
owner._resolving.discard(func.id)
|
|
982
|
+
if r is not None:
|
|
983
|
+
if owner is not self and r.text:
|
|
984
|
+
self.ctx.used_globals.add(r.text)
|
|
985
|
+
return Res(r.text, True, True, r.frag)
|
|
986
|
+
# dedent("..."), format("..."): unwrap a single SQL argument
|
|
987
|
+
if len(args) == 1:
|
|
988
|
+
inner = self.resolve(args[0], at, depth + 1)
|
|
989
|
+
if inner is not None and looks_like_sql(inner.text, any_case=True):
|
|
990
|
+
return inner
|
|
991
|
+
return None
|
|
992
|
+
|
|
993
|
+
def _find_func(self, fn: Node | None, name: str) -> tuple["TsFile", Node] | None:
|
|
994
|
+
if fn is None or not name:
|
|
995
|
+
return None
|
|
996
|
+
if fn.type == "member_expression":
|
|
997
|
+
obj = _unwrap(fn.child_by_field_name("object"))
|
|
998
|
+
if obj is not None and obj.type == "identifier":
|
|
999
|
+
imp = self.imports.get(_txt(obj))
|
|
1000
|
+
if imp is not None and imp[1] == "*": # import * as plans from "./plans"; plans.fetchJobs(schema)
|
|
1001
|
+
hit = self.ctx.declaring(self.ctx.resolver.resolve(self.rel, imp[0]), name)
|
|
1002
|
+
other = self.ctx.file(hit[0]) if hit is not None else None
|
|
1003
|
+
func = other.funcs.get(hit[1]) if other is not None else None
|
|
1004
|
+
return (other, func) if func is not None else None
|
|
1005
|
+
literal = self._object_node(_txt(obj), fn, 0) # const queries = { byId: (id) => `SELECT ...` }
|
|
1006
|
+
if literal is not None:
|
|
1007
|
+
value = _unwrap(object_pairs(literal[1]).get(name))
|
|
1008
|
+
if value is not None and value.type in FUNC_TYPES:
|
|
1009
|
+
return literal[0], value
|
|
1010
|
+
for m in literal[1].named_children:
|
|
1011
|
+
if m.type == "method_definition" and _txt(m.child_by_field_name("name")) == name:
|
|
1012
|
+
return literal[0], m
|
|
1013
|
+
return None
|
|
1014
|
+
if obj is None or obj.type != "this":
|
|
1015
|
+
return None
|
|
1016
|
+
elif fn.type != "identifier":
|
|
1017
|
+
return None
|
|
1018
|
+
self._index_funcs()
|
|
1019
|
+
func = self.funcs.get(name)
|
|
1020
|
+
if func is not None:
|
|
1021
|
+
return self, func
|
|
1022
|
+
imp = self.imports.get(name) if fn.type == "identifier" else None
|
|
1023
|
+
if imp is None or imp[1] == "*":
|
|
1024
|
+
return None
|
|
1025
|
+
hit = self.ctx.declaring(self.ctx.resolver.resolve(self.rel, imp[0]), imp[1])
|
|
1026
|
+
other = self.ctx.file(hit[0]) if hit is not None else None
|
|
1027
|
+
if other is None or other is self:
|
|
1028
|
+
return None
|
|
1029
|
+
func = other.funcs.get(hit[1])
|
|
1030
|
+
return (other, func) if func is not None else None
|
|
1031
|
+
|
|
1032
|
+
def _func_return(self, func: Node, depth: int) -> Res | None:
|
|
1033
|
+
if depth > MAX_DEPTH:
|
|
1034
|
+
return None
|
|
1035
|
+
body = func.child_by_field_name("body")
|
|
1036
|
+
if body is None:
|
|
1037
|
+
return None
|
|
1038
|
+
if body.type != "statement_block": # arrow function with an expression body
|
|
1039
|
+
r = self.resolve(body, body, depth)
|
|
1040
|
+
return r if r is not None and (r.frag or sinkish_sql(r.text, True) or SQL_INSIDE.search(r.text)) else None
|
|
1041
|
+
found = []
|
|
1042
|
+
for n in _walk(body, stop=FUNC_TYPES):
|
|
1043
|
+
if n.type == "return_statement" and n.named_children:
|
|
1044
|
+
r = self.resolve(n.named_children[0], n, depth)
|
|
1045
|
+
if r is not None and (r.frag or sinkish_sql(r.text, True) or SQL_INSIDE.search(r.text)):
|
|
1046
|
+
found.append(r)
|
|
1047
|
+
return found[-1] if found else None
|
|
1048
|
+
|
|
1049
|
+
def _consume(self, node: Node) -> None:
|
|
1050
|
+
if node.type in STRING_TYPES:
|
|
1051
|
+
self.consumed.add(node.id)
|
|
1052
|
+
for s in _walk(node):
|
|
1053
|
+
if s.type in STRING_TYPES:
|
|
1054
|
+
self.consumed.add(s.id)
|
|
1055
|
+
|
|
1056
|
+
# ---- call sites -------------------------------------------------------------------
|
|
1057
|
+
def symbol(self, node: Node) -> str:
|
|
1058
|
+
"""Enclosing named scopes: `Class.method`, `fn`, `const x = () =>` as x, `{ key: () => }` as key."""
|
|
1059
|
+
names: list[str] = []
|
|
1060
|
+
pending = False
|
|
1061
|
+
n = node.parent
|
|
1062
|
+
while n is not None:
|
|
1063
|
+
t = n.type
|
|
1064
|
+
if t in ("function_declaration", "generator_function_declaration", "method_definition"):
|
|
1065
|
+
nm = _txt(n.child_by_field_name("name"))
|
|
1066
|
+
if nm:
|
|
1067
|
+
names.append(nm)
|
|
1068
|
+
pending = t == "method_definition" # a method of an object literal: `const repo = { find() {} }`
|
|
1069
|
+
elif t in INLINE_FUNCS:
|
|
1070
|
+
pending = True
|
|
1071
|
+
elif t in CLASS_TYPES:
|
|
1072
|
+
nm = _txt(n.child_by_field_name("name"))
|
|
1073
|
+
if nm:
|
|
1074
|
+
names.append(nm)
|
|
1075
|
+
pending = False
|
|
1076
|
+
elif pending and t == "pair":
|
|
1077
|
+
nm = _txt(n.child_by_field_name("key")).strip("'\"`")
|
|
1078
|
+
if nm:
|
|
1079
|
+
names.append(nm)
|
|
1080
|
+
elif pending and t in ("variable_declarator", "public_field_definition"):
|
|
1081
|
+
nm = n.child_by_field_name("name")
|
|
1082
|
+
if nm is not None and nm.type in ("identifier", "property_identifier", "private_property_identifier"):
|
|
1083
|
+
names.append(_txt(nm))
|
|
1084
|
+
pending = False
|
|
1085
|
+
elif pending and t == "assignment_expression":
|
|
1086
|
+
left = n.child_by_field_name("left")
|
|
1087
|
+
if left is not None and left.type in ("member_expression", "identifier"):
|
|
1088
|
+
names.append(_txt(left).removeprefix("module.exports.").removeprefix("exports.").removeprefix("this."))
|
|
1089
|
+
pending = False
|
|
1090
|
+
elif pending and t == "export_statement" and any(c.type == "default" for c in n.children):
|
|
1091
|
+
names.append("default")
|
|
1092
|
+
pending = False
|
|
1093
|
+
elif t in ("expression_statement", "lexical_declaration", "variable_declaration", "return_statement"):
|
|
1094
|
+
if pending and t == "return_statement":
|
|
1095
|
+
pass
|
|
1096
|
+
elif t != "return_statement":
|
|
1097
|
+
pending = False
|
|
1098
|
+
n = n.parent
|
|
1099
|
+
return ".".join(reversed(names))
|
|
1100
|
+
|
|
1101
|
+
def in_loop(self, node: Node) -> bool:
|
|
1102
|
+
"""Inside a loop of the same function: for / for-of / while, or a callback of map / forEach /
|
|
1103
|
+
Promise.all(xs.map(...)). An inline callback does not end the function; a named function does."""
|
|
1104
|
+
n = node.parent
|
|
1105
|
+
child = node
|
|
1106
|
+
while n is not None:
|
|
1107
|
+
t = n.type
|
|
1108
|
+
if t in LOOP_TYPES:
|
|
1109
|
+
body = n.child_by_field_name("body")
|
|
1110
|
+
if body is None or (body.start_byte <= child.start_byte and child.end_byte <= body.end_byte):
|
|
1111
|
+
return True
|
|
1112
|
+
elif t in ("function_declaration", "generator_function_declaration", "method_definition", "program") or t in CLASS_TYPES:
|
|
1113
|
+
return False
|
|
1114
|
+
elif t in INLINE_FUNCS:
|
|
1115
|
+
p = n.parent
|
|
1116
|
+
while p is not None and p.type in UNWRAP_TYPES:
|
|
1117
|
+
p = p.parent
|
|
1118
|
+
if p is None or p.type != "arguments" or p.parent is None or p.parent.type != "call_expression":
|
|
1119
|
+
return False # a function bound to a name: its own function
|
|
1120
|
+
name, _, _ = callee(p.parent.child_by_field_name("function"))
|
|
1121
|
+
if name in LOOP_METHODS:
|
|
1122
|
+
return True
|
|
1123
|
+
child = n
|
|
1124
|
+
n = n.parent
|
|
1125
|
+
return False
|
|
1126
|
+
|
|
1127
|
+
def _param_root(self, arg: Node | None, at: Node, depth: int = 0) -> tuple[Node, int, str] | None:
|
|
1128
|
+
"""(function, positional index, key) when `arg` is a parameter of an enclosing function, also through
|
|
1129
|
+
`const q = param.replace(...)`, `opts.query` and `` `${param}` ``."""
|
|
1130
|
+
arg = _unwrap(arg)
|
|
1131
|
+
if arg is None or depth > 4:
|
|
1132
|
+
return None
|
|
1133
|
+
t = arg.type
|
|
1134
|
+
if t in ("identifier", "shorthand_property_identifier"):
|
|
1135
|
+
name = _txt(arg)
|
|
1136
|
+
for func in self._scopes(at):
|
|
1137
|
+
assigns = [a for a in self._assigns(func).get(name, ()) if a.end_byte <= at.start_byte]
|
|
1138
|
+
plain = [a for a in assigns if a.type != "augmented_assignment_expression"]
|
|
1139
|
+
if plain:
|
|
1140
|
+
return self._param_root(self._value(plain[-1]), plain[-1], depth + 1)
|
|
1141
|
+
hit = param_index(func, name)
|
|
1142
|
+
if hit is not None:
|
|
1143
|
+
return func, hit[0], hit[1]
|
|
1144
|
+
return None
|
|
1145
|
+
if t == "member_expression":
|
|
1146
|
+
obj = _unwrap(arg.child_by_field_name("object"))
|
|
1147
|
+
if obj is not None and obj.type == "identifier":
|
|
1148
|
+
for func in self._scopes(at):
|
|
1149
|
+
if self._assigns(func).get(_txt(obj)):
|
|
1150
|
+
return None
|
|
1151
|
+
hit = param_index(func, _txt(obj))
|
|
1152
|
+
if hit is not None and not hit[1]:
|
|
1153
|
+
return func, hit[0], _txt(arg.child_by_field_name("property"))
|
|
1154
|
+
return None
|
|
1155
|
+
if t == "call_expression":
|
|
1156
|
+
name, recv, _ = callee(arg.child_by_field_name("function"))
|
|
1157
|
+
if recv is not None and (name in STRING_METHODS or name in REWRITE_METHODS):
|
|
1158
|
+
return self._param_root(recv, at, depth + 1)
|
|
1159
|
+
args = call_args(arg)
|
|
1160
|
+
if recv is None and 1 <= len(args) <= 2:
|
|
1161
|
+
return self._param_root(args[0], at, depth + 1)
|
|
1162
|
+
return None
|
|
1163
|
+
if t == "template_string":
|
|
1164
|
+
subs = [c for c in arg.children if c.type == "template_substitution"]
|
|
1165
|
+
text = "".join(_txt(c) for c in arg.children if c.type == "string_fragment").strip()
|
|
1166
|
+
if len(subs) == 1 and len(text) < 40 and subs[0].named_children:
|
|
1167
|
+
return self._param_root(subs[0].named_children[0], at, depth + 1)
|
|
1168
|
+
for sub in subs[:8]: # `select count(*) from (${query}) t`: the parameter named like SQL
|
|
1169
|
+
inner = _unwrap(sub.named_children[0]) if sub.named_children else None
|
|
1170
|
+
if inner is not None and inner.type == "identifier" and SQLISH_NAME.search(_txt(inner)):
|
|
1171
|
+
root = self._param_root(inner, at, depth + 1)
|
|
1172
|
+
if root is not None:
|
|
1173
|
+
return root
|
|
1174
|
+
return None
|
|
1175
|
+
if t == "binary_expression" and _txt(arg.child_by_field_name("operator")) == "+":
|
|
1176
|
+
return self._param_root(arg.child_by_field_name("left"), at, depth + 1)
|
|
1177
|
+
if t == "ternary_expression":
|
|
1178
|
+
for key in ("consequence", "alternative"):
|
|
1179
|
+
root = self._param_root(arg.child_by_field_name(key), at, depth + 1)
|
|
1180
|
+
if root is not None:
|
|
1181
|
+
return root
|
|
1182
|
+
return None
|
|
1183
|
+
|
|
1184
|
+
def _alternatives(self, node: Node | None, at: Node, depth: int = 0) -> list[Res]:
|
|
1185
|
+
"""Every statement an argument may hold: both arms of `a ? x : y`, each branch that assigns the variable."""
|
|
1186
|
+
node = _unwrap(node)
|
|
1187
|
+
if node is None or depth > 3:
|
|
1188
|
+
return []
|
|
1189
|
+
if node.type == "ternary_expression":
|
|
1190
|
+
out: list[Res] = []
|
|
1191
|
+
for key in ("consequence", "alternative"):
|
|
1192
|
+
out += self._alternatives(node.child_by_field_name(key), at, depth + 1)
|
|
1193
|
+
return [r.dyn() for r in out]
|
|
1194
|
+
if node.type == "member_expression" and _txt(node.child_by_field_name("property")) in SQL_PROPS:
|
|
1195
|
+
obj = _unwrap(node.child_by_field_name("object"))
|
|
1196
|
+
if obj is not None and obj.type == "identifier":
|
|
1197
|
+
node = obj # compiled.sql: the alternatives of `compiled`
|
|
1198
|
+
if node.type in ("identifier", "shorthand_property_identifier"):
|
|
1199
|
+
name = _txt(node)
|
|
1200
|
+
for func in self._scopes(at):
|
|
1201
|
+
assigns = [a for a in self._assigns(func).get(name, ()) if a.end_byte <= at.start_byte]
|
|
1202
|
+
plain = [a for a in assigns if a.type != "augmented_assignment_expression"]
|
|
1203
|
+
if not assigns:
|
|
1204
|
+
if param_index(func, name) is not None:
|
|
1205
|
+
break
|
|
1206
|
+
continue
|
|
1207
|
+
value = _unwrap(self._value(plain[-1])) if plain else None
|
|
1208
|
+
if len(plain) > 1 or (value is not None and value.type == "ternary_expression"):
|
|
1209
|
+
out = []
|
|
1210
|
+
for a in plain:
|
|
1211
|
+
if a.id in self._resolving:
|
|
1212
|
+
continue
|
|
1213
|
+
self._resolving.add(a.id)
|
|
1214
|
+
try:
|
|
1215
|
+
out += self._alternatives(self._value(a), a, depth + 1)
|
|
1216
|
+
finally:
|
|
1217
|
+
self._resolving.discard(a.id)
|
|
1218
|
+
return [r.dyn().named() for r in out]
|
|
1219
|
+
break
|
|
1220
|
+
r = self.resolve(node, at, 0)
|
|
1221
|
+
return [r] if r is not None else []
|
|
1222
|
+
|
|
1223
|
+
def _candidates(self, call: Node, name: str, recv: Node | None, spread: bool = False):
|
|
1224
|
+
"""[(argument node, engine, sure, wrapper, keys)] that may hold the SQL of this call. With `spread`,
|
|
1225
|
+
an options object passed on as `{ ...opts }` is a candidate too: `keys` are the keys it may carry."""
|
|
1226
|
+
args = call_args(call)
|
|
1227
|
+
if not args:
|
|
1228
|
+
return []
|
|
1229
|
+
out = []
|
|
1230
|
+
rule = self.ctx.sink_rules.get(name)
|
|
1231
|
+
if rule is not None:
|
|
1232
|
+
engine, indexes, options = rule
|
|
1233
|
+
weak = "weak" in options
|
|
1234
|
+
for i in indexes:
|
|
1235
|
+
if i >= len(args):
|
|
1236
|
+
continue
|
|
1237
|
+
arg = _unwrap(args[i])
|
|
1238
|
+
if arg is None:
|
|
1239
|
+
continue
|
|
1240
|
+
if arg.type == "object":
|
|
1241
|
+
pairs = object_pairs(arg)
|
|
1242
|
+
if "insert-table" in options:
|
|
1243
|
+
if "table" in pairs and "values" in pairs:
|
|
1244
|
+
out.append((arg, engine, True, "insert", ()))
|
|
1245
|
+
continue
|
|
1246
|
+
keys = sorted(k for k in options if k not in RULE_OPTIONS)
|
|
1247
|
+
hit = next((pairs[k] for k in keys if k in pairs), None)
|
|
1248
|
+
if hit is None:
|
|
1249
|
+
if spread:
|
|
1250
|
+
out.extend((sp, engine, not weak, "", tuple(keys)) for sp in object_spreads(arg))
|
|
1251
|
+
continue
|
|
1252
|
+
if not engine and (pairs.keys() & {"query_params", "clickhouse_settings", "format"}):
|
|
1253
|
+
engine = "clickhouse"
|
|
1254
|
+
out.append((hit, engine, not weak, "", ()))
|
|
1255
|
+
elif "insert-table" not in options:
|
|
1256
|
+
out.append((arg, engine, not weak, "", ()))
|
|
1257
|
+
for w in self.ctx.wrappers.get(name, ()):
|
|
1258
|
+
if w.index >= len(args):
|
|
1259
|
+
continue
|
|
1260
|
+
arg = _unwrap(args[w.index])
|
|
1261
|
+
if arg is None:
|
|
1262
|
+
continue
|
|
1263
|
+
if w.key:
|
|
1264
|
+
if arg.type != "object":
|
|
1265
|
+
continue
|
|
1266
|
+
hit = object_pairs(arg).get(w.key)
|
|
1267
|
+
if hit is not None:
|
|
1268
|
+
out.append((hit, w.engine, True, w, ()))
|
|
1269
|
+
elif spread:
|
|
1270
|
+
out.extend((sp, w.engine, True, w, (w.key,)) for sp in object_spreads(arg))
|
|
1271
|
+
elif arg.type != "object":
|
|
1272
|
+
out.append((arg, w.engine, True, w, ()))
|
|
1273
|
+
return out
|
|
1274
|
+
|
|
1275
|
+
def _db_receiver(self, recv: Node | None) -> bool:
|
|
1276
|
+
recv = _unwrap(recv)
|
|
1277
|
+
if recv is None or recv.type not in ("identifier", "member_expression", "this", "call_expression"):
|
|
1278
|
+
return False
|
|
1279
|
+
return bool(RECEIVER.search(_txt(recv)[-60:]))
|
|
1280
|
+
|
|
1281
|
+
def wrappers(self, names: set[str] | None) -> list[Wrapper]:
|
|
1282
|
+
"""Functions in this file that pass one of their own parameters to a sink (or to a wrapper in `names`)."""
|
|
1283
|
+
out = []
|
|
1284
|
+
for call in self.calls:
|
|
1285
|
+
args_node = call.child_by_field_name("arguments")
|
|
1286
|
+
if args_node is None or args_node.type != "arguments":
|
|
1287
|
+
continue
|
|
1288
|
+
name, recv, _ = callee(call.child_by_field_name("function"))
|
|
1289
|
+
if not name or (names is not None and name not in names):
|
|
1290
|
+
continue
|
|
1291
|
+
if names is None and name not in self.ctx.sink_rules:
|
|
1292
|
+
continue
|
|
1293
|
+
for arg, engine, sure, via, keys in self._candidates(call, name, recv, spread=True):
|
|
1294
|
+
if via == "insert":
|
|
1295
|
+
continue
|
|
1296
|
+
root = self._param_root(arg, call)
|
|
1297
|
+
if root is None:
|
|
1298
|
+
continue
|
|
1299
|
+
func, index, key = root
|
|
1300
|
+
if keys: # f(opts) { sink({ ...opts }) }: opts carries the SQL under the sink's key
|
|
1301
|
+
if key:
|
|
1302
|
+
continue
|
|
1303
|
+
fname = func_name(func)
|
|
1304
|
+
db = self.has_db or (isinstance(via, Wrapper) and via.db) or self._db_receiver(recv)
|
|
1305
|
+
if fname and fname not in NOT_WRAPPER_NAMES and len(fname) >= 3 and fname not in self.ctx.sink_rules \
|
|
1306
|
+
and (db or isinstance(via, Wrapper)):
|
|
1307
|
+
out.extend(Wrapper(fname, index, k, engine or self.file_engine(), db) for k in keys)
|
|
1308
|
+
continue
|
|
1309
|
+
fname = func_name(func)
|
|
1310
|
+
label = key or _txt(params_of(func)[index]) if index < len(params_of(func)) else key
|
|
1311
|
+
named = bool(SQLISH_NAME.search(label[:60]))
|
|
1312
|
+
db = self.has_db or (isinstance(via, Wrapper) and via.db) or self._db_receiver(recv)
|
|
1313
|
+
if not fname or fname in NOT_WRAPPER_NAMES or len(fname) < 3 or fname in self.ctx.sink_rules:
|
|
1314
|
+
continue
|
|
1315
|
+
if not (named and (db or sure)) and not (engine and db and sure):
|
|
1316
|
+
continue
|
|
1317
|
+
out.append(Wrapper(fname, index, key, engine or self.file_engine(), db))
|
|
1318
|
+
return out
|
|
1319
|
+
|
|
1320
|
+
def _emit(self, out: list[RawSite], node: Node, sink_text: str, engine: str, res: Res | None, resolution: str,
|
|
1321
|
+
expr: Node, known: bool = True, kind: str = "call") -> None:
|
|
1322
|
+
out.append(RawSite(
|
|
1323
|
+
file=self.rel, line=node.start_point[0] + 1, end_line=node.end_point[0] + 1, language=LANGUAGE,
|
|
1324
|
+
kind=kind, sink=trim(re.sub(r"\s+", "", sink_text), 80), symbol=self.symbol(node),
|
|
1325
|
+
sql=res.text if res is not None else None, resolution=resolution,
|
|
1326
|
+
expr=trim(_txt(expr)), in_loop=self.in_loop(node),
|
|
1327
|
+
engine_hint=(self.ctx.prisma_provider(self.rel) if engine == "prisma" else engine) or self.file_engine(),
|
|
1328
|
+
is_test=self.test, known_sink=known,
|
|
1329
|
+
))
|
|
1330
|
+
|
|
1331
|
+
def sites(self) -> list[RawSite]:
|
|
1332
|
+
out: list[RawSite] = []
|
|
1333
|
+
ctx = self.ctx
|
|
1334
|
+
tagged: list[Node] = []
|
|
1335
|
+
for call in self.calls:
|
|
1336
|
+
args_node = call.child_by_field_name("arguments")
|
|
1337
|
+
if args_node is None:
|
|
1338
|
+
continue
|
|
1339
|
+
if args_node.type == "template_string":
|
|
1340
|
+
tagged.append(call)
|
|
1341
|
+
continue
|
|
1342
|
+
name, recv, dotted = callee(call.child_by_field_name("function"))
|
|
1343
|
+
if not name or (name not in ctx.sink_rules and name not in ctx.wrappers):
|
|
1344
|
+
continue
|
|
1345
|
+
if name == "raw" and _raw_fragment(call):
|
|
1346
|
+
continue # `knex.raw('(select ..) as x')` handed to select()/where()/orderBy(): a piece of that statement
|
|
1347
|
+
db = self.has_db or self._db_receiver(recv)
|
|
1348
|
+
fallback = None
|
|
1349
|
+
for arg, engine, sure, via, _keys in self._candidates(call, name, recv):
|
|
1350
|
+
if via == "insert":
|
|
1351
|
+
table = self.resolve(object_pairs(arg).get("table"), call, 0)
|
|
1352
|
+
if not (self.has_db or self._db_receiver(recv)):
|
|
1353
|
+
continue
|
|
1354
|
+
name_res = table if table is not None and re.fullmatch(r"[\w.«» \"`$-]+", table.text) else _ph_text("table")
|
|
1355
|
+
res = Res(f"INSERT INTO {name_res.text} FORMAT JSONEachRow", name_res.dynamic or table is None, name_res.via_name)
|
|
1356
|
+
self._emit(out, call, dotted, engine, res, res.resolution, arg)
|
|
1357
|
+
fallback = None
|
|
1358
|
+
break
|
|
1359
|
+
if arg.type in ("object", "array", "number", "true", "false", "null", "arrow_function", "function_expression",
|
|
1360
|
+
"undefined", "regex", "new_expression"):
|
|
1361
|
+
continue
|
|
1362
|
+
wrapper_db = isinstance(via, Wrapper) and via.db
|
|
1363
|
+
res = self.resolve(arg, call, 0)
|
|
1364
|
+
root = self._param_root(arg, call)
|
|
1365
|
+
if res is not None and sinkish_sql(res.text, db or wrapper_db):
|
|
1366
|
+
self._emit(out, call, dotted, engine, res, res.resolution, arg)
|
|
1367
|
+
seen_text = {res.text}
|
|
1368
|
+
for alt in self._alternatives(arg, call)[:MAX_ALTERNATIVES]: # the other branches
|
|
1369
|
+
if alt.text not in seen_text and sinkish_sql(alt.text, db or wrapper_db):
|
|
1370
|
+
seen_text.add(alt.text)
|
|
1371
|
+
self._emit(out, call, dotted, engine, alt, "template", arg)
|
|
1372
|
+
self._consume(arg)
|
|
1373
|
+
holder = arg
|
|
1374
|
+
if arg.type == "member_expression" and _txt(arg.child_by_field_name("property")) in SQL_PROPS:
|
|
1375
|
+
holder = _unwrap(arg.child_by_field_name("object")) or arg
|
|
1376
|
+
for name_node in ([holder] if holder.type in ("identifier", "shorthand_property_identifier") else []):
|
|
1377
|
+
for func in self._scopes(call):
|
|
1378
|
+
for a in self._assigns(func).get(_txt(name_node), ()):
|
|
1379
|
+
if a.end_byte <= call.start_byte:
|
|
1380
|
+
self._consume(a)
|
|
1381
|
+
fallback = None
|
|
1382
|
+
break
|
|
1383
|
+
if res is not None and res.dynamic and (db or wrapper_db) and sure and LEAD_HOLES.match(res.text) \
|
|
1384
|
+
and SQL_INSIDE.search(res.text):
|
|
1385
|
+
self._emit(out, call, dotted, engine, res, "template", arg) # `${base} WHERE ...`
|
|
1386
|
+
self._consume(arg)
|
|
1387
|
+
fallback = None
|
|
1388
|
+
break
|
|
1389
|
+
if res is not None and not (root is not None and res.dynamic):
|
|
1390
|
+
continue # resolved, and it is not SQL
|
|
1391
|
+
if fallback is not None:
|
|
1392
|
+
continue
|
|
1393
|
+
label = _txt(arg)[:80]
|
|
1394
|
+
named = bool(SQLISH_NAME.search(label))
|
|
1395
|
+
if root is not None:
|
|
1396
|
+
# a wrapper found by name (`select`, `execute`) is trusted for SQL-named arguments only
|
|
1397
|
+
if (named and (db or wrapper_db or sure)) or (sure and engine and db and not isinstance(via, Wrapper)):
|
|
1398
|
+
fallback = (arg, engine, "parameter")
|
|
1399
|
+
elif res is None and sure and named and (db or wrapper_db) and arg.type in (
|
|
1400
|
+
"identifier", "member_expression", "call_expression", "shorthand_property_identifier",
|
|
1401
|
+
"template_string", "binary_expression", "ternary_expression", "subscript_expression"):
|
|
1402
|
+
fallback = (arg, engine, "unresolved")
|
|
1403
|
+
if fallback is not None:
|
|
1404
|
+
self._emit(out, call, dotted, fallback[1], None, fallback[2], fallback[0])
|
|
1405
|
+
|
|
1406
|
+
# tagged templates that no call above took as its argument
|
|
1407
|
+
for call in tagged:
|
|
1408
|
+
tpl = call.child_by_field_name("arguments")
|
|
1409
|
+
if tpl.id in self.consumed:
|
|
1410
|
+
continue
|
|
1411
|
+
fn = call.child_by_field_name("function")
|
|
1412
|
+
name, recv, dotted = callee(fn)
|
|
1413
|
+
head = _txt(recv).split(".")[0].split("(")[0] if recv is not None else ""
|
|
1414
|
+
if name in NON_SQL_TAGS or head in NON_SQL_TAGS:
|
|
1415
|
+
continue
|
|
1416
|
+
is_tag = name in ctx.tag_rules or (_unwrap(fn) is not None and _unwrap(fn).type == "call_expression"
|
|
1417
|
+
and head in ctx.tag_rules)
|
|
1418
|
+
if not is_tag:
|
|
1419
|
+
continue # left to the loose-string pass below
|
|
1420
|
+
res = self.resolve(call, call, 0)
|
|
1421
|
+
if res is None:
|
|
1422
|
+
continue
|
|
1423
|
+
db = self.has_db or self._db_receiver(recv) or name.startswith("$")
|
|
1424
|
+
# sql`(SELECT ...)` and sql`EXISTS (...)` are expressions for a query builder, not statements
|
|
1425
|
+
if sinkish_sql(res.text, db) and not (SUBQUERY_START.match(res.text) and not name.startswith("$")):
|
|
1426
|
+
engine = ctx.tag_rules.get(name) or ctx.tag_rules.get(head) or ("prisma" if head == "Prisma" else "")
|
|
1427
|
+
self._emit(out, call, dotted.split("<")[0], engine, res, res.resolution, tpl)
|
|
1428
|
+
self._consume(tpl)
|
|
1429
|
+
else:
|
|
1430
|
+
ctx.fragments += 1
|
|
1431
|
+
# sql<boolean>`...`: with a bare type argument the grammar reads `sql < boolean > template`
|
|
1432
|
+
for s in self.strings:
|
|
1433
|
+
if s.type != "template_string" or s.id in self.consumed:
|
|
1434
|
+
continue
|
|
1435
|
+
top = s # sql<Row>`...`.execute(db): the template is the receiver of a call chain
|
|
1436
|
+
while top.parent is not None and (
|
|
1437
|
+
(top.parent.type == "member_expression" and top.parent.child_by_field_name("object").id == top.id) or
|
|
1438
|
+
(top.parent.type == "call_expression" and top.parent.child_by_field_name("function").id == top.id)):
|
|
1439
|
+
top = top.parent
|
|
1440
|
+
p = top.parent
|
|
1441
|
+
if p is None or p.type != "binary_expression" or _txt(p.child_by_field_name("operator")) != ">":
|
|
1442
|
+
continue
|
|
1443
|
+
left = p.child_by_field_name("left")
|
|
1444
|
+
if left is None or left.type != "binary_expression" or _txt(left.child_by_field_name("operator")) != "<":
|
|
1445
|
+
continue
|
|
1446
|
+
name, recv, dotted = callee(left.child_by_field_name("left"))
|
|
1447
|
+
if name not in ctx.tag_rules:
|
|
1448
|
+
continue
|
|
1449
|
+
res = self._template(s, s, 0, tagged=True)
|
|
1450
|
+
if sinkish_sql(res.text, self.has_db or self._db_receiver(recv)):
|
|
1451
|
+
self._emit(out, p, dotted, ctx.tag_rules.get(name) or "", res, res.resolution, s)
|
|
1452
|
+
else:
|
|
1453
|
+
ctx.fragments += 1
|
|
1454
|
+
self._consume(s)
|
|
1455
|
+
out.extend(self._loose_strings())
|
|
1456
|
+
return out
|
|
1457
|
+
|
|
1458
|
+
def _loose_strings(self) -> list[RawSite]:
|
|
1459
|
+
"""SQL strings not attached to a known sink: wrapper calls, fragments, constants."""
|
|
1460
|
+
out: list[RawSite] = []
|
|
1461
|
+
found: list[tuple[Node, Node, Res]] = []
|
|
1462
|
+
for s in self.strings:
|
|
1463
|
+
if s.id in self.consumed or s.end_byte - s.start_byte < 14:
|
|
1464
|
+
continue
|
|
1465
|
+
parent = s.parent
|
|
1466
|
+
if parent is None or parent.type in ("import_statement", "export_statement", "expression_statement",
|
|
1467
|
+
"literal_type", "jsx_attribute"):
|
|
1468
|
+
continue
|
|
1469
|
+
if parent.type == "pair" and parent.child_by_field_name("key") is not None \
|
|
1470
|
+
and parent.child_by_field_name("key").id == s.id:
|
|
1471
|
+
continue
|
|
1472
|
+
top = s
|
|
1473
|
+
if parent.type == "call_expression" and parent.child_by_field_name("arguments") is not None \
|
|
1474
|
+
and parent.child_by_field_name("arguments").id == s.id:
|
|
1475
|
+
name, recv, _ = callee(parent.child_by_field_name("function"))
|
|
1476
|
+
if name in NON_SQL_TAGS or (recv is not None and _txt(recv).split(".")[0] in NON_SQL_TAGS):
|
|
1477
|
+
continue
|
|
1478
|
+
top = parent # a tagged template: resolved with its tag
|
|
1479
|
+
while top.parent is not None and (top.parent.type in UNWRAP_TYPES or (
|
|
1480
|
+
top.parent.type == "binary_expression" and _txt(top.parent.child_by_field_name("operator")) == "+")):
|
|
1481
|
+
top = top.parent
|
|
1482
|
+
if top.id != s.id and top.type == "binary_expression":
|
|
1483
|
+
first = next((n for n in _walk(top) if n.type in STRING_TYPES), None)
|
|
1484
|
+
if first is None or first.id != s.id:
|
|
1485
|
+
continue
|
|
1486
|
+
res = self.resolve(top, top, 0)
|
|
1487
|
+
if res is None or not looks_like_sql(res.text):
|
|
1488
|
+
continue
|
|
1489
|
+
found.append((s, top, res))
|
|
1490
|
+
for s, top, res in found:
|
|
1491
|
+
if s.id in self.consumed:
|
|
1492
|
+
continue # a larger SQL string was built from this one
|
|
1493
|
+
# `SELECT ...`.trim(), dedent(`SELECT ...`): report the built string
|
|
1494
|
+
while top.parent is not None:
|
|
1495
|
+
p = top.parent
|
|
1496
|
+
if p.type == "member_expression" and p.parent is not None and p.parent.type == "call_expression" and \
|
|
1497
|
+
_txt(p.child_by_field_name("property")) in STRING_METHODS | REWRITE_METHODS:
|
|
1498
|
+
top = p.parent
|
|
1499
|
+
elif p.type in UNWRAP_TYPES:
|
|
1500
|
+
top = p
|
|
1501
|
+
else:
|
|
1502
|
+
break
|
|
1503
|
+
call = None
|
|
1504
|
+
if top.parent is not None and top.parent.type == "arguments" and top.parent.parent is not None \
|
|
1505
|
+
and top.parent.parent.type == "call_expression":
|
|
1506
|
+
call = top.parent.parent
|
|
1507
|
+
sink_text = ""
|
|
1508
|
+
if call is not None:
|
|
1509
|
+
name, _, dotted = callee(call.child_by_field_name("function"))
|
|
1510
|
+
sink_text = dotted
|
|
1511
|
+
if NOT_A_SINK.search(dotted) or NOT_A_SINK.search(name):
|
|
1512
|
+
continue # a test on the text, a log line or an error message, not a query
|
|
1513
|
+
elif top.parent is not None and top.parent.type in ("new_expression", "throw_statement"):
|
|
1514
|
+
continue
|
|
1515
|
+
self._consume(top)
|
|
1516
|
+
self._emit(out, top, sink_text.split("<")[0], "", res, res.resolution, top, known=False,
|
|
1517
|
+
kind="call" if call is not None else "sql_string")
|
|
1518
|
+
return out
|
|
1519
|
+
|
|
1520
|
+
def module_constants(self) -> dict[str, str]:
|
|
1521
|
+
"""Module-level NAME = "..." values that resolve fully."""
|
|
1522
|
+
out = {}
|
|
1523
|
+
for name in list(self._assigns(self.root)):
|
|
1524
|
+
if not CONST_NAME.match(name):
|
|
1525
|
+
continue
|
|
1526
|
+
r = self.export_value(name, 0)
|
|
1527
|
+
if r is not None and not r.dynamic and r.text and len(r.text) < CONST_VALUE_LIMIT:
|
|
1528
|
+
out[name] = r.text
|
|
1529
|
+
return out
|
|
1530
|
+
|
|
1531
|
+
|
|
1532
|
+
def _ctx_exported_value(self: Ctx, rel: str, name: str, depth: int) -> Res | None:
|
|
1533
|
+
"""Value of an exported name, following `export { x } from "./y"` and `export * from "./y"`."""
|
|
1534
|
+
hit = self.declaring(rel, name)
|
|
1535
|
+
f = self.file(hit[0]) if hit is not None else None
|
|
1536
|
+
if f is None or depth > MAX_DEPTH:
|
|
1537
|
+
return None
|
|
1538
|
+
return f.export_value(hit[1], depth)
|
|
1539
|
+
|
|
1540
|
+
|
|
1541
|
+
_REEXPORT = re.compile(rb"export\s+(?:type\s+)?(\*(?:\s+as\s+\w+)?|\{[^}]*\})\s*from\s*['\"]([^'\"]+)['\"]")
|
|
1542
|
+
|
|
1543
|
+
|
|
1544
|
+
def _ctx_declaring(self: Ctx, rel: str | None, name: str, depth: int = 0) -> tuple[str, str] | None:
|
|
1545
|
+
"""(file, local name) that declares an exported name: this file, or the one a barrel re-exports it from."""
|
|
1546
|
+
f = self.file(rel) if rel is not None and depth <= 5 else None
|
|
1547
|
+
if f is None:
|
|
1548
|
+
return None
|
|
1549
|
+
f._index_funcs()
|
|
1550
|
+
if name in f.funcs or name in f._assigns(f.root):
|
|
1551
|
+
return rel, name
|
|
1552
|
+
imp = f.imports.get(name)
|
|
1553
|
+
if imp is not None and imp[1] != "*": # import { x } from "./y"; export { x }
|
|
1554
|
+
return self.declaring(self.resolver.resolve(rel, imp[0]), imp[1], depth + 1)
|
|
1555
|
+
stars = []
|
|
1556
|
+
for m in _REEXPORT.finditer(f.src):
|
|
1557
|
+
what, spec = m.group(1).decode("utf-8", "replace"), m.group(2).decode("utf-8", "replace")
|
|
1558
|
+
if what.startswith("*"):
|
|
1559
|
+
if " as " not in what:
|
|
1560
|
+
stars.append(spec)
|
|
1561
|
+
continue
|
|
1562
|
+
for part in what.strip("{}").split(","):
|
|
1563
|
+
bits = part.split()
|
|
1564
|
+
if bits[:1] == ["type"]:
|
|
1565
|
+
bits = bits[1:]
|
|
1566
|
+
if bits and bits[-1] == name: # `a as b` exports b, defined as a
|
|
1567
|
+
return self.declaring(self.resolver.resolve(rel, spec), bits[0], depth + 1)
|
|
1568
|
+
for spec in stars:
|
|
1569
|
+
hit = self.declaring(self.resolver.resolve(rel, spec), name, depth + 1)
|
|
1570
|
+
if hit is not None:
|
|
1571
|
+
return hit
|
|
1572
|
+
return None
|
|
1573
|
+
|
|
1574
|
+
|
|
1575
|
+
Ctx.exported_value = _ctx_exported_value
|
|
1576
|
+
Ctx.declaring = _ctx_declaring
|
|
1577
|
+
|
|
1578
|
+
|
|
1579
|
+
# --------------------------------------------------------------------------------------- driver
|
|
1580
|
+
|
|
1581
|
+
LAST_SUMMARY: dict = {}
|
|
1582
|
+
|
|
1583
|
+
|
|
1584
|
+
def summary_extras() -> dict:
|
|
1585
|
+
"""Counts from the last `extract` call, merged into the inventory summary by discover()."""
|
|
1586
|
+
return dict(LAST_SUMMARY)
|
|
1587
|
+
|
|
1588
|
+
|
|
1589
|
+
def _is_minified(src: bytes) -> bool:
|
|
1590
|
+
if len(src) < MINIFIED_MIN_BYTES:
|
|
1591
|
+
return False
|
|
1592
|
+
return len(src) / (src.count(b"\n") + 1) > MINIFIED_AVG_LINE
|
|
1593
|
+
|
|
1594
|
+
|
|
1595
|
+
def _deps(ctx: Ctx, rel: str, cache: dict[str, frozenset[str]]) -> frozenset[str]:
|
|
1596
|
+
"""Dependencies of the nearest package and of the repo root package."""
|
|
1597
|
+
near = ctx.resolver.nearest_package(rel)
|
|
1598
|
+
d = near[0] if near else ""
|
|
1599
|
+
got = cache.get(d)
|
|
1600
|
+
if got is None:
|
|
1601
|
+
names: set[str] = set()
|
|
1602
|
+
for pkg in (near[1] if near else None, ctx.resolver.package_json("")):
|
|
1603
|
+
for key in ("dependencies", "devDependencies", "peerDependencies"):
|
|
1604
|
+
deps = (pkg or {}).get(key)
|
|
1605
|
+
names.update(deps if isinstance(deps, dict) else ())
|
|
1606
|
+
got = cache[d] = frozenset(names)
|
|
1607
|
+
return got
|
|
1608
|
+
|
|
1609
|
+
|
|
1610
|
+
def extract(root: Path, files: list[str], rules: LangRules) -> list[RawSite]:
|
|
1611
|
+
"""Index the files that can hold SQL, find wrapper functions, then find call sites and loose SQL strings."""
|
|
1612
|
+
ctx = Ctx(root, files, rules)
|
|
1613
|
+
skipped: Counter[str] = Counter()
|
|
1614
|
+
orm: Counter[str] = Counter()
|
|
1615
|
+
orm_tests: Counter[str] = Counter()
|
|
1616
|
+
deps_cache: dict[str, frozenset[str]] = {}
|
|
1617
|
+
from . import orm_ts # ORM and builder calls as SQL sites (orm_ts_*.py)
|
|
1618
|
+
orm_scan = orm_ts.Scan(ctx, root, files)
|
|
1619
|
+
prisma_re = None
|
|
1620
|
+
if ctx.prisma_models:
|
|
1621
|
+
models = "|".join(sorted({re.escape(m[0].lower() + m[1:]) for m in ctx.prisma_models}, key=len, reverse=True))
|
|
1622
|
+
prisma_re = re.compile(rb"\.\s*(?:" + models.encode() + rb")\s*\.\s*(?:" + PRISMA_METHODS.encode() + rb")\s*\(")
|
|
1623
|
+
relevant: list[str] = []
|
|
1624
|
+
quiet: list[str] = []
|
|
1625
|
+
strong = sorted((n for n, (_, _, options) in ctx.sink_rules.items() if "weak" not in options and len(n) >= 5),
|
|
1626
|
+
key=len, reverse=True)
|
|
1627
|
+
sink_re = re.compile(rb"(?:" + b"|".join(re.escape(n.encode()) for n in strong) + rb")\s*[(<`]") if strong else None
|
|
1628
|
+
for rel in files:
|
|
1629
|
+
if SKIP_PATH.search(rel):
|
|
1630
|
+
skipped["generated_or_build_path"] += 1
|
|
1631
|
+
continue
|
|
1632
|
+
src = read_bytes(root / rel)
|
|
1633
|
+
if src is None:
|
|
1634
|
+
skipped["too_large_or_unreadable"] += 1
|
|
1635
|
+
continue
|
|
1636
|
+
if _is_minified(src):
|
|
1637
|
+
skipped["minified"] += 1
|
|
1638
|
+
continue
|
|
1639
|
+
if GENERATED_HEAD.search(src[:600]):
|
|
1640
|
+
skipped["generated_header"] += 1
|
|
1641
|
+
continue
|
|
1642
|
+
# ORM and query-builder calls: counted only
|
|
1643
|
+
deps = _deps(ctx, rel, deps_cache)
|
|
1644
|
+
bucket = orm_tests if is_ts_test(rel) else orm
|
|
1645
|
+
orm_scan.offer(rel, src, deps)
|
|
1646
|
+
if prisma_re is not None:
|
|
1647
|
+
n = len(prisma_re.findall(src))
|
|
1648
|
+
elif any(p in deps for p in ORM_PACKAGES["prisma"]):
|
|
1649
|
+
n = len(PRISMA_GENERIC.findall(src))
|
|
1650
|
+
else:
|
|
1651
|
+
n = 0
|
|
1652
|
+
if n:
|
|
1653
|
+
bucket["prisma"] += n
|
|
1654
|
+
for lib, pattern in ORM_PATTERNS.items():
|
|
1655
|
+
if any(p in deps for p in ORM_PACKAGES[lib]):
|
|
1656
|
+
n = len(pattern.findall(src))
|
|
1657
|
+
if n:
|
|
1658
|
+
bucket[lib] += n
|
|
1659
|
+
if RELEVANT.search(src) or (sink_re is not None and sink_re.search(src)):
|
|
1660
|
+
ctx.sources[rel] = src
|
|
1661
|
+
relevant.append(rel)
|
|
1662
|
+
else:
|
|
1663
|
+
quiet.append(rel)
|
|
1664
|
+
|
|
1665
|
+
def guarded(fn, default):
|
|
1666
|
+
try:
|
|
1667
|
+
return fn()
|
|
1668
|
+
except Exception: # one odd file must not stop the inventory
|
|
1669
|
+
return default
|
|
1670
|
+
|
|
1671
|
+
# module-level string constants, for names used from a file whose import cannot be followed
|
|
1672
|
+
for rel in relevant:
|
|
1673
|
+
f = ctx.file(rel)
|
|
1674
|
+
if f is None:
|
|
1675
|
+
continue
|
|
1676
|
+
for name, value in guarded(f.module_constants, {}).items():
|
|
1677
|
+
ctx.global_consts[name].add(value)
|
|
1678
|
+
# wrappers, to a fixed point: a function that passes its parameter to a wrapper is a wrapper too
|
|
1679
|
+
names: set[str] | None = None
|
|
1680
|
+
for _ in range(WRAPPER_ROUNDS):
|
|
1681
|
+
fresh: set[str] = set()
|
|
1682
|
+
for rel in relevant:
|
|
1683
|
+
f = ctx.parsed.get(rel)
|
|
1684
|
+
if f is None:
|
|
1685
|
+
continue
|
|
1686
|
+
for w in guarded(lambda: f.wrappers(names), []):
|
|
1687
|
+
known = ctx.wrappers[w.name]
|
|
1688
|
+
if not any(k.index == w.index and k.key == w.key for k in known):
|
|
1689
|
+
known.append(w)
|
|
1690
|
+
fresh.add(w.name)
|
|
1691
|
+
if not fresh:
|
|
1692
|
+
break
|
|
1693
|
+
names = fresh
|
|
1694
|
+
# a file with no SQL text of its own can still call a wrapper with SQL built elsewhere
|
|
1695
|
+
if ctx.wrappers:
|
|
1696
|
+
distinct = sorted((n for n in ctx.wrappers if len(n) >= 5), key=len, reverse=True)
|
|
1697
|
+
if distinct:
|
|
1698
|
+
wrapper_re = re.compile(rb"\b(?:" + b"|".join(re.escape(n.encode()) for n in distinct) + rb")\s*[(<]")
|
|
1699
|
+
for rel in quiet:
|
|
1700
|
+
src = read_bytes(root / rel)
|
|
1701
|
+
if src is not None and wrapper_re.search(src):
|
|
1702
|
+
ctx.sources[rel] = src
|
|
1703
|
+
relevant.append(rel)
|
|
1704
|
+
for f in ctx.parsed.values():
|
|
1705
|
+
if f is not None:
|
|
1706
|
+
f.consumed.clear()
|
|
1707
|
+
ctx.used_globals.clear()
|
|
1708
|
+
ctx.fragments = 0
|
|
1709
|
+
|
|
1710
|
+
out: list[RawSite] = []
|
|
1711
|
+
for rel in relevant:
|
|
1712
|
+
f = ctx.file(rel)
|
|
1713
|
+
if f is not None:
|
|
1714
|
+
out.extend(guarded(f.sites, []))
|
|
1715
|
+
out.extend(guarded(orm_scan.sites, []))
|
|
1716
|
+
LAST_SUMMARY.clear()
|
|
1717
|
+
LAST_SUMMARY.update(orm_scan.summary())
|
|
1718
|
+
LAST_SUMMARY.update({
|
|
1719
|
+
"orm_calls": dict(orm.most_common()),
|
|
1720
|
+
"orm_calls_in_tests": dict(orm_tests.most_common()),
|
|
1721
|
+
"typescript": {
|
|
1722
|
+
"files": len(files), "files_parsed": len(relevant), "files_skipped": dict(skipped.most_common()),
|
|
1723
|
+
"sql_fragments": ctx.fragments,
|
|
1724
|
+
"wrappers": sorted(ctx.wrappers),
|
|
1725
|
+
},
|
|
1726
|
+
})
|
|
1727
|
+
# a constant used from another file is reported at its use sites, not again at its definition
|
|
1728
|
+
return [s for s in out if not (s.kind == "sql_string" and s.sql in ctx.used_globals)]
|