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,806 @@
|
|
|
1
|
+
"""jOOQ DSL chains as SQL.
|
|
2
|
+
|
|
3
|
+
`dsl.select(A, B).from(T).where(A.eq(x)).and(cond).orderBy(B.desc()).limit(10).fetch()` becomes
|
|
4
|
+
`SELECT a, b FROM t WHERE a = ? AND «cond» ORDER BY b DESC LIMIT 10`. Tables and fields are read from
|
|
5
|
+
`DSL.table("...")` / `DSL.field("...")` / `DSL.name("...")` (also through constants and local variables) and from
|
|
6
|
+
generated classes (`AUTHOR.FIRST_NAME`: the constant names, lower-cased; stated in the notes). Bound values are
|
|
7
|
+
`?`. A condition, table or field that is built in a variable or a helper is a «run-time part» holding its source
|
|
8
|
+
text; so is a step added inside an `if` after the chain was assigned to a variable.
|
|
9
|
+
|
|
10
|
+
A chain whose table is only known at run time is still reported (the statement's shape is real) with the table
|
|
11
|
+
as a run-time part and confidence "low". What is not a jOOQ chain this reader knows is counted with the reason.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
|
|
18
|
+
from tree_sitter import Node
|
|
19
|
+
|
|
20
|
+
from .base import RawSite, is_test_path, trim
|
|
21
|
+
|
|
22
|
+
STARTERS = {"select", "selectDistinct", "selectFrom", "selectCount", "selectOne", "selectZero", "insertInto", "update",
|
|
23
|
+
"deleteFrom", "delete", "mergeInto"}
|
|
24
|
+
TERMINALS = {"fetch", "fetchOne", "fetchAny", "fetchInto", "fetchOneInto", "fetchOptional", "fetchOptionalInto",
|
|
25
|
+
"fetchSingle", "fetchSingleInto", "fetchMap", "fetchGroups", "fetchSet", "fetchArray", "fetchLazy",
|
|
26
|
+
"fetchStream", "fetchStreamInto", "fetchSize", "stream", "iterator", "execute", "executeAsync", "fetchAsync",
|
|
27
|
+
"fetchAnyInto", "fetchMaps", "fetchOneMap", "fetchResultSet", "fetchMany", "collect", "forEach", "getSQL",
|
|
28
|
+
"getQuery", "asTable", "asField", "fetchValues", "fetchValue", "queryTimeout", "keepStatement", "maxRows",
|
|
29
|
+
"fetchExists", "fetchCount"}
|
|
30
|
+
COMPARE = {"eq": "=", "equal": "=", "ne": "<>", "notEqual": "<>", "lt": "<", "lessThan": "<", "le": "<=",
|
|
31
|
+
"lessOrEqual": "<=", "gt": ">", "greaterThan": ">", "ge": ">=", "greaterOrEqual": ">=",
|
|
32
|
+
"isDistinctFrom": "IS DISTINCT FROM", "isNotDistinctFrom": "IS NOT DISTINCT FROM"}
|
|
33
|
+
FUNCS = {"count": "COUNT", "max": "MAX", "min": "MIN", "sum": "SUM", "avg": "AVG", "lower": "LOWER", "upper": "UPPER",
|
|
34
|
+
"coalesce": "COALESCE", "nvl": "COALESCE", "concat": "CONCAT", "length": "LENGTH", "trim": "TRIM", "abs": "ABS",
|
|
35
|
+
"round": "ROUND", "floor": "FLOOR", "ceil": "CEIL", "greatest": "GREATEST", "least": "LEAST", "nullif": "NULLIF",
|
|
36
|
+
"ifnull": "COALESCE", "isnull": "COALESCE", "countDistinct": "COUNT(DISTINCT", "rowNumber": "ROW_NUMBER",
|
|
37
|
+
"trunc": "TRUNC", "substring": "SUBSTRING", "replace": "REPLACE", "year": "YEAR", "month": "MONTH", "day": "DAY",
|
|
38
|
+
"md5": "MD5", "position": "POSITION", "left": "LEFT", "right": "RIGHT", "sqrt": "SQRT", "power": "POWER",
|
|
39
|
+
"any": "ANY", "all": "ALL", "exp": "EXP", "ln": "LN", "sign": "SIGN", "rank": "RANK", "denseRank": "DENSE_RANK",
|
|
40
|
+
"lead": "LEAD", "lag": "LAG", "firstValue": "FIRST_VALUE", "lastValue": "LAST_VALUE", "arrayAgg": "ARRAY_AGG",
|
|
41
|
+
"stringAgg": "STRING_AGG", "groupConcat": "GROUP_CONCAT", "jsonArrayAgg": "JSON_ARRAYAGG", "toChar": "TO_CHAR",
|
|
42
|
+
"toDate": "TO_DATE", "dateDiff": "DATEDIFF", "bitAnd": "BIT_AND", "bitOr": "BIT_OR"}
|
|
43
|
+
NO_ARG = {"now": "CURRENT_TIMESTAMP", "currentTimestamp": "CURRENT_TIMESTAMP", "currentDate": "CURRENT_DATE",
|
|
44
|
+
"currentTime": "CURRENT_TIME", "currentLocalDateTime": "CURRENT_TIMESTAMP", "currentOffsetDateTime": "CURRENT_TIMESTAMP",
|
|
45
|
+
"currentLocalDate": "CURRENT_DATE", "asterisk": "*", "rand": "RANDOM()", "uuid": "UUID()", "one": "1", "zero": "0"}
|
|
46
|
+
JOINS = {"join": "JOIN", "innerJoin": "JOIN", "leftJoin": "LEFT JOIN", "leftOuterJoin": "LEFT JOIN",
|
|
47
|
+
"rightJoin": "RIGHT JOIN", "rightOuterJoin": "RIGHT JOIN", "fullJoin": "FULL JOIN", "fullOuterJoin": "FULL JOIN",
|
|
48
|
+
"crossJoin": "CROSS JOIN", "naturalJoin": "NATURAL JOIN", "straightJoin": "JOIN"}
|
|
49
|
+
UPPER = re.compile(r"^[A-Z][A-Z0-9_]*$")
|
|
50
|
+
RECEIVER = re.compile(r"(dsl|ctx|context|create|jooq|db|database|sql|query|tx|trx|configuration|using)", re.I)
|
|
51
|
+
TEST_FILE = re.compile(r"(^|/)src/(test|it|integration-?test)/|(Test|Tests|IT|TestCase)\.java$")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Skip(Exception):
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _txt(node: Node | None) -> str:
|
|
59
|
+
return node.text.decode("utf-8", "replace") if node is not None else ""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _args(node: Node | None) -> list[Node]:
|
|
63
|
+
al = node.child_by_field_name("arguments") if node is not None else None
|
|
64
|
+
return [c for c in al.named_children if c.type not in ("line_comment", "block_comment")] if al is not None else []
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _ph(node: Node | str) -> str:
|
|
68
|
+
text = node if isinstance(node, str) else _txt(node)
|
|
69
|
+
return "«" + trim(text, 80).replace("»", ">").replace("«", "<") + "»"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _ident(name: str) -> str:
|
|
73
|
+
name = name.strip()
|
|
74
|
+
return name if re.fullmatch(r"[A-Za-z_][\w.$]*|\*", name) else '"' + name.replace('"', "") + '"' if name else name
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Chain:
|
|
78
|
+
"""One jOOQ statement being assembled from the steps of a call chain."""
|
|
79
|
+
|
|
80
|
+
def __init__(self) -> None:
|
|
81
|
+
self.kind = ""
|
|
82
|
+
self.distinct = False
|
|
83
|
+
self.select: list[str] = []
|
|
84
|
+
self.table = ""
|
|
85
|
+
self.tables: list[str] = []
|
|
86
|
+
self.joins: list[str] = []
|
|
87
|
+
self.where: list[str] = []
|
|
88
|
+
self.group: list[str] = []
|
|
89
|
+
self.having: list[str] = []
|
|
90
|
+
self.order: list[str] = []
|
|
91
|
+
self.limit = ""
|
|
92
|
+
self.offset = ""
|
|
93
|
+
self.tail: list[str] = []
|
|
94
|
+
self.sets: list[str] = []
|
|
95
|
+
self.columns: list[str] = []
|
|
96
|
+
self.values: list[str] = []
|
|
97
|
+
self.conflict = ""
|
|
98
|
+
self.returning: list[str] = []
|
|
99
|
+
self.pending_join = -1
|
|
100
|
+
self.last = "" # where | having | on: what a following and()/or() extends
|
|
101
|
+
self.set_ops: list[str] = []
|
|
102
|
+
self.runtime_table = False
|
|
103
|
+
self.generated = False
|
|
104
|
+
self.unknown_steps: list[str] = []
|
|
105
|
+
self.hints: list[str] = []
|
|
106
|
+
|
|
107
|
+
def sql(self) -> str:
|
|
108
|
+
if self.kind == "select":
|
|
109
|
+
cols = ", ".join(self.select) if self.select else "*"
|
|
110
|
+
out = "SELECT " + ("DISTINCT " if self.distinct else "") + cols
|
|
111
|
+
if self.tables:
|
|
112
|
+
out += " FROM " + ", ".join(self.tables)
|
|
113
|
+
out += "".join(" " + j for j in self.joins)
|
|
114
|
+
if self.where:
|
|
115
|
+
out += " WHERE " + " AND ".join(self.where)
|
|
116
|
+
if self.group:
|
|
117
|
+
out += " GROUP BY " + ", ".join(self.group)
|
|
118
|
+
if self.having:
|
|
119
|
+
out += " HAVING " + " AND ".join(self.having)
|
|
120
|
+
out += "".join(" " + s for s in self.set_ops)
|
|
121
|
+
if self.order:
|
|
122
|
+
out += " ORDER BY " + ", ".join(self.order)
|
|
123
|
+
if self.limit:
|
|
124
|
+
out += " LIMIT " + self.limit
|
|
125
|
+
if self.offset:
|
|
126
|
+
out += " OFFSET " + self.offset
|
|
127
|
+
return out + "".join(" " + t for t in self.tail)
|
|
128
|
+
if self.kind == "insert":
|
|
129
|
+
out = f"INSERT INTO {self.table}"
|
|
130
|
+
if self.sets and not self.columns:
|
|
131
|
+
self.columns = [s.split(" = ", 1)[0] for s in self.sets]
|
|
132
|
+
self.values = [s.split(" = ", 1)[1] if " = " in s else "?" for s in self.sets]
|
|
133
|
+
if self.columns:
|
|
134
|
+
out += " (" + ", ".join(self.columns) + ")"
|
|
135
|
+
if self.set_ops:
|
|
136
|
+
out += " " + " ".join(self.set_ops)
|
|
137
|
+
else:
|
|
138
|
+
unknown = any("«" in c for c in self.columns)
|
|
139
|
+
out += " VALUES (" + ", ".join(self.values or (["«values»"] if unknown else ["?" for _ in self.columns]) or ["«values»"]) + ")"
|
|
140
|
+
if self.conflict:
|
|
141
|
+
out += " " + self.conflict
|
|
142
|
+
if self.returning:
|
|
143
|
+
out += " RETURNING " + ", ".join(self.returning)
|
|
144
|
+
return out
|
|
145
|
+
if self.kind == "update":
|
|
146
|
+
out = f"UPDATE {self.table} SET " + ", ".join(self.sets or ["«columns» = «values»"])
|
|
147
|
+
if self.where:
|
|
148
|
+
out += " WHERE " + " AND ".join(self.where)
|
|
149
|
+
if self.returning:
|
|
150
|
+
out += " RETURNING " + ", ".join(self.returning)
|
|
151
|
+
return out
|
|
152
|
+
if self.kind == "delete":
|
|
153
|
+
out = f"DELETE FROM {self.table}"
|
|
154
|
+
if self.where:
|
|
155
|
+
out += " WHERE " + " AND ".join(self.where)
|
|
156
|
+
if self.returning:
|
|
157
|
+
out += " RETURNING " + ", ".join(self.returning)
|
|
158
|
+
return out
|
|
159
|
+
raise Skip("statement kind not handled")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class Jooq:
|
|
163
|
+
def __init__(self, ctx, jf):
|
|
164
|
+
self.ctx = ctx
|
|
165
|
+
self.jf = jf
|
|
166
|
+
self.depth = 0
|
|
167
|
+
self.generated = False
|
|
168
|
+
self.runtime = False
|
|
169
|
+
|
|
170
|
+
# ---- definitions behind names -----------------------------------------------------------------
|
|
171
|
+
def _definition(self, name: str, at: Node) -> Node | None:
|
|
172
|
+
"""The expression a constant or an unconditionally assigned local variable stands for."""
|
|
173
|
+
jf = self.jf
|
|
174
|
+
for func in jf._scopes(at):
|
|
175
|
+
events = [e for e in jf.scope(func).events.get(name, ()) if e[0] == "set" and e[1].end_byte <= at.start_byte]
|
|
176
|
+
if name in jf.scope(func).declared:
|
|
177
|
+
return events[0][2] if len(events) == 1 else None
|
|
178
|
+
value = jf.fields_flat.get(name)
|
|
179
|
+
if value is not None:
|
|
180
|
+
return value
|
|
181
|
+
cls = jf.static_imports.get(name)
|
|
182
|
+
if cls:
|
|
183
|
+
for ojf, node in jf.repo.classes.get(cls, ()):
|
|
184
|
+
v = ojf.class_fields.get(node.id, {}).get(name)
|
|
185
|
+
if v is not None:
|
|
186
|
+
return v
|
|
187
|
+
cur = jf._enclosing(at, ("class_declaration", "interface_declaration"))
|
|
188
|
+
seen: set[str] = set()
|
|
189
|
+
queue = list(jf.supers(cur)) if cur is not None else []
|
|
190
|
+
while queue:
|
|
191
|
+
sup = queue.pop(0)
|
|
192
|
+
if sup in seen:
|
|
193
|
+
continue
|
|
194
|
+
seen.add(sup)
|
|
195
|
+
for ojf, node in jf.repo.classes.get(sup, ()):
|
|
196
|
+
v = ojf.class_fields.get(node.id, {}).get(name)
|
|
197
|
+
if v is not None:
|
|
198
|
+
return v
|
|
199
|
+
queue.extend(ojf.supers(node))
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
def _elsewhere(self, name: str, table: bool) -> str | None:
|
|
203
|
+
"""A constant defined in another class (static import, wildcard import): its name, when every definition
|
|
204
|
+
of that constant in the repository gives the same one."""
|
|
205
|
+
if not UPPER.match(name):
|
|
206
|
+
return None
|
|
207
|
+
found: set[str] = set()
|
|
208
|
+
for ojf, value in self.jf.repo.statics.get(name, ()):
|
|
209
|
+
if value.type != "method_invocation":
|
|
210
|
+
return None
|
|
211
|
+
other = Jooq(self.ctx, ojf)
|
|
212
|
+
other.depth = self.depth
|
|
213
|
+
text = other.name(value, table)
|
|
214
|
+
if "«" in text:
|
|
215
|
+
return None
|
|
216
|
+
found.add(text)
|
|
217
|
+
return next(iter(found)) if len(found) == 1 else None
|
|
218
|
+
|
|
219
|
+
def _class_const(self, cls: str, name: str) -> Node | None:
|
|
220
|
+
for ojf, node in self.jf.repo.classes.get(cls, ()):
|
|
221
|
+
v = ojf.class_fields.get(node.id, {}).get(name)
|
|
222
|
+
if v is not None:
|
|
223
|
+
return v
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
def _string(self, node: Node) -> str | None:
|
|
227
|
+
try:
|
|
228
|
+
r = self.jf.resolve(node, node, 0)
|
|
229
|
+
except Exception:
|
|
230
|
+
return None
|
|
231
|
+
return r.text if r is not None and not r.dynamic and "«" not in r.text else None
|
|
232
|
+
|
|
233
|
+
# ---- names: tables and fields -----------------------------------------------------------------
|
|
234
|
+
def name(self, node: Node, table: bool = False) -> str:
|
|
235
|
+
"""A table or a field as SQL text, or a «run-time part»."""
|
|
236
|
+
self.depth += 1
|
|
237
|
+
try:
|
|
238
|
+
if self.depth > 12:
|
|
239
|
+
return self._runtime(node, table)
|
|
240
|
+
t = node.type
|
|
241
|
+
if t == "string_literal":
|
|
242
|
+
return _ident(self._string(node) or "") or self._runtime(node, table)
|
|
243
|
+
if t == "identifier":
|
|
244
|
+
d = self._definition(_txt(node), node)
|
|
245
|
+
if d is not None and d.id != node.id:
|
|
246
|
+
return self.name(d, table)
|
|
247
|
+
far = self._elsewhere(_txt(node), table)
|
|
248
|
+
return far if far is not None else self._runtime(node, table)
|
|
249
|
+
if t == "field_access":
|
|
250
|
+
obj, fld = node.child_by_field_name("object"), _txt(node.child_by_field_name("field"))
|
|
251
|
+
otext = _txt(obj)
|
|
252
|
+
d = self._class_const(otext.split(".")[-1], fld)
|
|
253
|
+
if d is not None:
|
|
254
|
+
return self.name(d, table)
|
|
255
|
+
parts = [p for p in (otext + "." + fld).split(".")]
|
|
256
|
+
if all(UPPER.match(p) for p in parts[-2:]) or (UPPER.match(parts[-1]) and parts[0] in ("Tables", "Keys")):
|
|
257
|
+
self.generated = True # generated jOOQ classes: TABLE.COLUMN
|
|
258
|
+
keep = [p.lower() for p in parts if UPPER.match(p)]
|
|
259
|
+
return ".".join(keep[-2:]) if not table else keep[-1]
|
|
260
|
+
return self._runtime(node, table)
|
|
261
|
+
if t == "method_invocation":
|
|
262
|
+
nm = _txt(node.child_by_field_name("name"))
|
|
263
|
+
obj = node.child_by_field_name("object")
|
|
264
|
+
args = _args(node)
|
|
265
|
+
if nm in ("field", "table", "name", "quotedName", "unquotedName", "keyword", "sql", "raw") and args and \
|
|
266
|
+
(obj is None or _txt(obj) in ("DSL", "org.jooq.impl.DSL")):
|
|
267
|
+
first = args[0]
|
|
268
|
+
if first.type == "method_invocation" and _txt(first.child_by_field_name("name")) in ("name", "quotedName", "unquotedName", "sql", "raw", "select", "selectFrom", "selectDistinct"):
|
|
269
|
+
if _txt(first.child_by_field_name("name")).startswith("select"):
|
|
270
|
+
return "(" + self.subquery(first) + ")"
|
|
271
|
+
return self.name(first, table)
|
|
272
|
+
parts = [self._string(a) for a in args if a.type != "class_literal" and not _txt(a).endswith(".class")]
|
|
273
|
+
if nm in ("name", "quotedName", "unquotedName") and parts and all(p is not None for p in parts):
|
|
274
|
+
return ".".join(_ident(p) for p in parts)
|
|
275
|
+
s = self._string(first)
|
|
276
|
+
if s is not None:
|
|
277
|
+
return s if re.search(r"[\s(]", s) else _ident(s)
|
|
278
|
+
return self._runtime(node, table)
|
|
279
|
+
if nm == "as" and obj is not None and args:
|
|
280
|
+
alias = self._string(args[0])
|
|
281
|
+
base = self.name(obj, table) if table else self.expr(obj)
|
|
282
|
+
return f"{base} AS {_ident(alias)}" if alias else base
|
|
283
|
+
if not table:
|
|
284
|
+
return self.expr(node)
|
|
285
|
+
if nm.startswith("select"):
|
|
286
|
+
return "(" + self.subquery(node) + ")"
|
|
287
|
+
return self._runtime(node, table)
|
|
288
|
+
return self._runtime(node, table)
|
|
289
|
+
finally:
|
|
290
|
+
self.depth -= 1
|
|
291
|
+
|
|
292
|
+
def _runtime(self, node: Node, table: bool) -> str:
|
|
293
|
+
if table:
|
|
294
|
+
self.runtime = True
|
|
295
|
+
return _ph(node)
|
|
296
|
+
|
|
297
|
+
def _is_fieldish(self, node: Node) -> bool:
|
|
298
|
+
t = node.type
|
|
299
|
+
if t == "field_access":
|
|
300
|
+
return True
|
|
301
|
+
if t == "identifier":
|
|
302
|
+
d = self._definition(_txt(node), node)
|
|
303
|
+
if d is None:
|
|
304
|
+
return self._elsewhere(_txt(node), False) is not None
|
|
305
|
+
return d.type == "method_invocation" and _txt(d.child_by_field_name("name")) in ("field", "name", "quotedName") \
|
|
306
|
+
and (d.child_by_field_name("object") is None or _txt(d.child_by_field_name("object")) == "DSL")
|
|
307
|
+
if t == "method_invocation":
|
|
308
|
+
nm = _txt(node.child_by_field_name("name"))
|
|
309
|
+
obj = node.child_by_field_name("object")
|
|
310
|
+
dsl = obj is None or _txt(obj) in ("DSL", "org.jooq.impl.DSL")
|
|
311
|
+
if dsl and (nm in ("field", "name", "quotedName", "val", "value", "inline", "sql", "raw") or nm in NO_ARG or nm.startswith("select")):
|
|
312
|
+
return True
|
|
313
|
+
if nm in FUNCS and (obj is None or _txt(obj) == "DSL"):
|
|
314
|
+
return True
|
|
315
|
+
if nm in ("as", "cast", "coerce", "plus", "minus", "add", "sub", "mul", "div", "times", "divide", "lower", "upper",
|
|
316
|
+
"trim", "max", "min", "sum", "count", "avg", "desc", "asc"):
|
|
317
|
+
return obj is not None and self._is_fieldish(obj)
|
|
318
|
+
return False
|
|
319
|
+
|
|
320
|
+
def value(self, node: Node) -> str:
|
|
321
|
+
t = node.type
|
|
322
|
+
if t == "string_literal":
|
|
323
|
+
s = self._string(node)
|
|
324
|
+
return "'" + s.replace("'", "''") + "'" if s is not None else "?"
|
|
325
|
+
if t in ("decimal_integer_literal", "decimal_floating_point_literal"):
|
|
326
|
+
return re.sub(r"[LlFfDd]$", "", _txt(node))
|
|
327
|
+
if t in ("true", "false"):
|
|
328
|
+
return t.upper()
|
|
329
|
+
if t == "null_literal":
|
|
330
|
+
return "NULL"
|
|
331
|
+
if self._is_fieldish(node):
|
|
332
|
+
return self.expr(node)
|
|
333
|
+
return "?"
|
|
334
|
+
|
|
335
|
+
# ---- expressions ------------------------------------------------------------------------------
|
|
336
|
+
def expr(self, node: Node) -> str:
|
|
337
|
+
"""A field expression, an order item or a condition."""
|
|
338
|
+
self.depth += 1
|
|
339
|
+
try:
|
|
340
|
+
if self.depth > 14:
|
|
341
|
+
return _ph(node)
|
|
342
|
+
t = node.type
|
|
343
|
+
if t == "parenthesized_expression":
|
|
344
|
+
return self.expr(node.named_children[0]) if node.named_children else _ph(node)
|
|
345
|
+
if t in ("string_literal", "decimal_integer_literal", "decimal_floating_point_literal", "true", "false", "null_literal"):
|
|
346
|
+
return self.value(node)
|
|
347
|
+
if t in ("identifier", "field_access"):
|
|
348
|
+
if t == "identifier":
|
|
349
|
+
d = self._definition(_txt(node), node)
|
|
350
|
+
if d is not None and d.id != node.id:
|
|
351
|
+
if d.type == "method_invocation" and (self._is_fieldish(d) or self._is_condition(d)):
|
|
352
|
+
return self.expr(d)
|
|
353
|
+
return _ph(node)
|
|
354
|
+
far = self._elsewhere(_txt(node), False)
|
|
355
|
+
return far if far is not None else _ph(node)
|
|
356
|
+
return self.name(node)
|
|
357
|
+
if t != "method_invocation":
|
|
358
|
+
return _ph(node)
|
|
359
|
+
nm = _txt(node.child_by_field_name("name"))
|
|
360
|
+
obj = node.child_by_field_name("object")
|
|
361
|
+
args = _args(node)
|
|
362
|
+
dsl = obj is None or _txt(obj) in ("DSL", "org.jooq.impl.DSL")
|
|
363
|
+
if nm in ("field", "name", "quotedName", "unquotedName", "sql", "raw") and dsl:
|
|
364
|
+
return self.name(node)
|
|
365
|
+
if nm in ("val", "value", "inline", "param") and dsl:
|
|
366
|
+
return self.value(args[0]) if args and nm == "inline" else "?"
|
|
367
|
+
if nm in NO_ARG and not args:
|
|
368
|
+
if nm == "asterisk" and obj is not None and not dsl:
|
|
369
|
+
return self.name(obj, True).split(" AS ")[-1] + ".*"
|
|
370
|
+
return NO_ARG[nm]
|
|
371
|
+
if nm in ("select", "selectDistinct", "selectFrom", "selectCount", "selectOne"):
|
|
372
|
+
return "(" + self.subquery(node) + ")"
|
|
373
|
+
if dsl:
|
|
374
|
+
if nm in ("and", "or"):
|
|
375
|
+
parts = [self.expr(a) for a in args]
|
|
376
|
+
return "(" + f" {nm.upper()} ".join(parts) + ")" if parts else "1 = 1"
|
|
377
|
+
if nm == "not" and args:
|
|
378
|
+
return "NOT (" + self.expr(args[0]) + ")"
|
|
379
|
+
if nm in ("noCondition", "trueCondition"):
|
|
380
|
+
return "1 = 1"
|
|
381
|
+
if nm == "falseCondition":
|
|
382
|
+
return "1 = 0"
|
|
383
|
+
if nm == "condition" and args:
|
|
384
|
+
s = self._string(args[0])
|
|
385
|
+
return "(" + s + ")" if s is not None else _ph(node)
|
|
386
|
+
if nm in ("exists", "notExists") and args:
|
|
387
|
+
return ("NOT " if nm == "notExists" else "") + "EXISTS (" + self.subquery(args[0]) + ")"
|
|
388
|
+
if nm == "count" and not args:
|
|
389
|
+
return "COUNT(*)"
|
|
390
|
+
if nm == "countDistinct":
|
|
391
|
+
return "COUNT(DISTINCT " + ", ".join(self.expr(a) for a in args) + ")"
|
|
392
|
+
if nm in FUNCS:
|
|
393
|
+
return FUNCS[nm] + "(" + ", ".join(self.value(a) if not self._is_fieldish(a) else self.expr(a) for a in args) + ")"
|
|
394
|
+
return _ph(node)
|
|
395
|
+
# methods on a field or a condition
|
|
396
|
+
left = self.expr(obj)
|
|
397
|
+
if nm in COMPARE and len(args) == 1:
|
|
398
|
+
return f"{left} {COMPARE[nm]} {self.operand(args[0])}"
|
|
399
|
+
if nm in ("in", "notIn"):
|
|
400
|
+
neg = "NOT " if nm == "notIn" else ""
|
|
401
|
+
if len(args) == 1 and args[0].type == "method_invocation" and _txt(args[0].child_by_field_name("name")).startswith("select"):
|
|
402
|
+
return f"{left} {neg}IN ({self.subquery(args[0])})"
|
|
403
|
+
if len(args) == 1 and self._chain_start(args[0]) is not None:
|
|
404
|
+
return f"{left} {neg}IN ({self.subquery(args[0])})"
|
|
405
|
+
vals = [self.value(a) for a in args] if len(args) > 1 else ["?"]
|
|
406
|
+
return f"{left} {neg}IN ({', '.join(vals)})"
|
|
407
|
+
if nm in ("like", "notLike", "likeIgnoreCase", "notLikeIgnoreCase", "contains", "containsIgnoreCase", "startsWith",
|
|
408
|
+
"endsWith", "startsWithIgnoreCase", "endsWithIgnoreCase", "notContains", "likeRegex", "similarTo") and args:
|
|
409
|
+
neg = "NOT " if nm.startswith("not") else ""
|
|
410
|
+
op = "~" if nm == "likeRegex" else "SIMILAR TO" if nm == "similarTo" else "LIKE"
|
|
411
|
+
if "IgnoreCase" in nm:
|
|
412
|
+
return f"LOWER({left}) {neg}LIKE LOWER({self.operand(args[0])})"
|
|
413
|
+
return f"{left} {neg}{op} {self.operand(args[0])}"
|
|
414
|
+
if nm in ("isNull", "isNotNull", "isTrue", "isFalse") and not args:
|
|
415
|
+
return left + {"isNull": " IS NULL", "isNotNull": " IS NOT NULL", "isTrue": " = TRUE", "isFalse": " = FALSE"}[nm]
|
|
416
|
+
if nm in ("between", "notBetween") and len(args) == 2:
|
|
417
|
+
return f"{left} {'NOT ' if nm == 'notBetween' else ''}BETWEEN {self.operand(args[0])} AND {self.operand(args[1])}"
|
|
418
|
+
if nm in ("and", "or", "andNot", "orNot") and len(args) == 1:
|
|
419
|
+
if obj is not None and obj.type == "method_invocation" and _txt(obj.child_by_field_name("name")) == "between" and len(_args(obj)) == 1:
|
|
420
|
+
return f"{self.expr(obj.child_by_field_name('object'))} BETWEEN {self.operand(_args(obj)[0])} AND {self.operand(args[0])}"
|
|
421
|
+
right = self.expr(args[0])
|
|
422
|
+
if nm.endswith("Not"):
|
|
423
|
+
right = "NOT (" + right + ")"
|
|
424
|
+
return f"({left} {'AND' if nm.startswith('and') else 'OR'} {right})"
|
|
425
|
+
if nm == "not" and not args:
|
|
426
|
+
return "NOT (" + left + ")"
|
|
427
|
+
if nm in ("desc", "asc") and not args:
|
|
428
|
+
return f"{left} {nm.upper()}"
|
|
429
|
+
if nm in ("nullsFirst", "nullsLast") and not args:
|
|
430
|
+
return f"{left} NULLS {'FIRST' if nm == 'nullsFirst' else 'LAST'}"
|
|
431
|
+
if nm == "as" and args:
|
|
432
|
+
alias = self._string(args[0])
|
|
433
|
+
return f"{left} AS {_ident(alias)}" if alias else left
|
|
434
|
+
if nm in ("cast", "coerce", "convertFrom", "convert", "getField", "getName"):
|
|
435
|
+
return left
|
|
436
|
+
if nm in ("plus", "add", "minus", "sub", "mul", "times", "div", "divide", "mod") and len(args) == 1:
|
|
437
|
+
op = {"plus": "+", "add": "+", "minus": "-", "sub": "-", "mul": "*", "times": "*", "div": "/", "divide": "/", "mod": "%"}[nm]
|
|
438
|
+
return f"({left} {op} {self.operand(args[0])})"
|
|
439
|
+
if nm in ("max", "min", "sum", "avg", "count", "lower", "upper", "trim", "length", "abs") and not args:
|
|
440
|
+
return f"{FUNCS[nm]}({left})"
|
|
441
|
+
if nm == "countDistinct" and not args:
|
|
442
|
+
return f"COUNT(DISTINCT {left})"
|
|
443
|
+
if nm in ("coalesce", "nvl", "concat") and args:
|
|
444
|
+
return f"{FUNCS[nm]}({left}, {', '.join(self.operand(a) for a in args)})"
|
|
445
|
+
if nm == "field" and args: # TABLE.field("name")
|
|
446
|
+
s = self._string(args[0])
|
|
447
|
+
return (left.split(" AS ")[-1] + "." + _ident(s)) if s else _ph(node)
|
|
448
|
+
if nm == "over":
|
|
449
|
+
return left + (" OVER (" + _ph(args[0]) + ")" if args else " OVER ()")
|
|
450
|
+
return _ph(node)
|
|
451
|
+
finally:
|
|
452
|
+
self.depth -= 1
|
|
453
|
+
|
|
454
|
+
def _is_condition(self, node: Node) -> bool:
|
|
455
|
+
if node.type != "method_invocation":
|
|
456
|
+
return False
|
|
457
|
+
nm = _txt(node.child_by_field_name("name"))
|
|
458
|
+
return nm in COMPARE or nm in ("in", "notIn", "like", "isNull", "isNotNull", "between", "and", "or", "not", "condition",
|
|
459
|
+
"noCondition", "trueCondition", "falseCondition", "exists", "notExists", "contains",
|
|
460
|
+
"startsWith", "endsWith", "likeIgnoreCase", "isTrue", "isFalse", "notLike")
|
|
461
|
+
|
|
462
|
+
def operand(self, node: Node) -> str:
|
|
463
|
+
return self.expr(node) if self._is_fieldish(node) else self.value(node)
|
|
464
|
+
|
|
465
|
+
def cond(self, node: Node) -> str:
|
|
466
|
+
if node.type == "string_literal":
|
|
467
|
+
s = self._string(node)
|
|
468
|
+
return "(" + s + ")" if s else _ph(node)
|
|
469
|
+
if node.type == "method_invocation" or node.type == "parenthesized_expression":
|
|
470
|
+
return self.expr(node)
|
|
471
|
+
if node.type == "identifier":
|
|
472
|
+
d = self._definition(_txt(node), node)
|
|
473
|
+
if d is not None and self._is_condition(d):
|
|
474
|
+
return self.expr(d)
|
|
475
|
+
return _ph(node)
|
|
476
|
+
|
|
477
|
+
# ---- chains -----------------------------------------------------------------------------------
|
|
478
|
+
def _chain_start(self, node: Node) -> Node | None:
|
|
479
|
+
"""The starter call (`select`, `insertInto`, ...) at the bottom of a call chain, or None."""
|
|
480
|
+
cur = node
|
|
481
|
+
while cur is not None and cur.type == "method_invocation":
|
|
482
|
+
if _txt(cur.child_by_field_name("name")) in STARTERS:
|
|
483
|
+
return cur
|
|
484
|
+
cur = cur.child_by_field_name("object")
|
|
485
|
+
return None
|
|
486
|
+
|
|
487
|
+
def links(self, top: Node) -> list[tuple[str, list[Node], Node]]:
|
|
488
|
+
out = []
|
|
489
|
+
cur = top
|
|
490
|
+
while cur is not None and cur.type == "method_invocation":
|
|
491
|
+
nm = _txt(cur.child_by_field_name("name"))
|
|
492
|
+
out.append((nm, _args(cur), cur))
|
|
493
|
+
if nm in STARTERS:
|
|
494
|
+
break
|
|
495
|
+
cur = cur.child_by_field_name("object")
|
|
496
|
+
out.reverse()
|
|
497
|
+
for k, (nm, _a, _n) in enumerate(out):
|
|
498
|
+
if nm in TERMINALS:
|
|
499
|
+
return out[:k] # what follows processes the result
|
|
500
|
+
return out
|
|
501
|
+
|
|
502
|
+
def subquery(self, node: Node) -> str:
|
|
503
|
+
if node.type == "identifier":
|
|
504
|
+
d = self._definition(_txt(node), node)
|
|
505
|
+
if d is None or self._chain_start(d) is None:
|
|
506
|
+
return _ph(node)
|
|
507
|
+
node = d
|
|
508
|
+
if self._chain_start(node) is None:
|
|
509
|
+
return _ph(node)
|
|
510
|
+
c = Chain()
|
|
511
|
+
for nm, args, n in self.links(node):
|
|
512
|
+
self.step(c, nm, args, n, False)
|
|
513
|
+
return c.sql()
|
|
514
|
+
|
|
515
|
+
def step(self, c: Chain, nm: str, args: list[Node], node: Node, conditional: bool) -> None:
|
|
516
|
+
if conditional:
|
|
517
|
+
text = _ph(nm + "(" + ", ".join(_txt(a) for a in args) + ")")
|
|
518
|
+
if nm in ("where", "and", "or", "andNot", "orNot", "having") or nm in JOINS or nm == "on":
|
|
519
|
+
(c.having if c.last == "having" else c.where).append(text) if nm not in JOINS and nm != "on" else c.joins.append(text)
|
|
520
|
+
elif nm in ("orderBy",):
|
|
521
|
+
c.order.append(text)
|
|
522
|
+
elif nm == "limit":
|
|
523
|
+
c.limit = c.limit or text
|
|
524
|
+
elif nm == "offset":
|
|
525
|
+
c.offset = c.offset or text
|
|
526
|
+
elif nm in ("set", "values", "columns"):
|
|
527
|
+
c.sets.append(text + " = ?") if c.kind == "update" else c.tail.append(text)
|
|
528
|
+
elif nm not in TERMINALS:
|
|
529
|
+
c.tail.append(text)
|
|
530
|
+
return
|
|
531
|
+
if nm in ("select", "selectDistinct"):
|
|
532
|
+
c.kind = "select"
|
|
533
|
+
c.distinct = nm == "selectDistinct"
|
|
534
|
+
for a in args:
|
|
535
|
+
c.select.append(self.name(a) if a.type != "method_invocation" else self.expr(a))
|
|
536
|
+
elif nm == "selectFrom":
|
|
537
|
+
c.kind = "select"
|
|
538
|
+
c.tables.append(self.name(args[0], True) if args else "«table»")
|
|
539
|
+
elif nm in ("selectCount", "selectOne", "selectZero"):
|
|
540
|
+
c.kind = "select"
|
|
541
|
+
c.select.append({"selectCount": "COUNT(*)", "selectOne": "1", "selectZero": "0"}[nm])
|
|
542
|
+
elif nm == "from":
|
|
543
|
+
for a in args:
|
|
544
|
+
c.tables.append(self.name(a, True))
|
|
545
|
+
elif nm in JOINS and args:
|
|
546
|
+
c.joins.append(f"{JOINS[nm]} {self.name(args[0], True)}")
|
|
547
|
+
c.pending_join = len(c.joins) - 1
|
|
548
|
+
c.last = "on"
|
|
549
|
+
elif nm in ("on", "onKey", "using") and c.pending_join >= 0:
|
|
550
|
+
if nm == "on" and args:
|
|
551
|
+
c.joins[c.pending_join] += " ON " + " AND ".join(self.cond(a) for a in args)
|
|
552
|
+
elif nm == "using" and args:
|
|
553
|
+
c.joins[c.pending_join] += " USING (" + ", ".join(self.name(a) for a in args) + ")"
|
|
554
|
+
c.last = "on"
|
|
555
|
+
elif nm == "where":
|
|
556
|
+
c.where.extend(self.cond(a) for a in args)
|
|
557
|
+
c.last = "where"
|
|
558
|
+
elif nm in ("and", "or", "andNot", "orNot", "andExists", "andNotExists") and args:
|
|
559
|
+
target = c.having if c.last == "having" else c.where
|
|
560
|
+
piece = self.cond(args[0]) if "Exists" not in nm else ("NOT " if "Not" in nm else "") + "EXISTS (" + self.subquery(args[0]) + ")"
|
|
561
|
+
if nm.endswith("Not") and "Exists" not in nm:
|
|
562
|
+
piece = "NOT (" + piece + ")"
|
|
563
|
+
if c.last == "on" and c.pending_join >= 0:
|
|
564
|
+
c.joins[c.pending_join] += (" AND " if nm.startswith("and") else " OR ") + piece
|
|
565
|
+
elif nm.startswith("or") and target:
|
|
566
|
+
target[:] = ["(" + " AND ".join(target) + " OR " + piece + ")"]
|
|
567
|
+
else:
|
|
568
|
+
target.append(piece)
|
|
569
|
+
elif nm == "groupBy":
|
|
570
|
+
c.group.extend(self.name(a) if a.type != "method_invocation" else self.expr(a) for a in args)
|
|
571
|
+
elif nm == "having":
|
|
572
|
+
c.having.extend(self.cond(a) for a in args)
|
|
573
|
+
c.last = "having"
|
|
574
|
+
elif nm == "orderBy":
|
|
575
|
+
c.order.extend(self.expr(a) if a.type == "method_invocation" else self.name(a) for a in args)
|
|
576
|
+
elif nm == "limit" and args:
|
|
577
|
+
if len(args) == 2:
|
|
578
|
+
c.offset, c.limit = self._num(args[0]), self._num(args[1])
|
|
579
|
+
else:
|
|
580
|
+
c.limit = self._num(args[0])
|
|
581
|
+
elif nm == "offset" and args:
|
|
582
|
+
c.offset = self._num(args[0])
|
|
583
|
+
elif nm in ("seek", "seekAfter", "seekBefore"):
|
|
584
|
+
c.where.append(_ph("seek(" + ", ".join(_txt(a) for a in args) + ")"))
|
|
585
|
+
elif nm in ("forUpdate", "forShare", "forNoKeyUpdate", "forKeyShare"):
|
|
586
|
+
c.tail.append({"forUpdate": "FOR UPDATE", "forShare": "FOR SHARE", "forNoKeyUpdate": "FOR NO KEY UPDATE", "forKeyShare": "FOR KEY SHARE"}[nm])
|
|
587
|
+
elif nm in ("skipLocked", "noWait"):
|
|
588
|
+
c.tail.append("SKIP LOCKED" if nm == "skipLocked" else "NOWAIT")
|
|
589
|
+
elif nm in ("union", "unionAll", "except", "intersect", "exceptAll", "intersectAll") and args:
|
|
590
|
+
op = re.sub(r"(All)$", " ALL", nm).upper()
|
|
591
|
+
c.set_ops.append(f"{op} {self.subquery(args[0])}")
|
|
592
|
+
elif nm == "insertInto":
|
|
593
|
+
c.kind = "insert"
|
|
594
|
+
c.table = self.name(args[0], True) if args else "«table»"
|
|
595
|
+
c.columns = [self.name(a) for a in args[1:]]
|
|
596
|
+
elif nm == "columns":
|
|
597
|
+
c.columns = [self.name(a) for a in args]
|
|
598
|
+
elif nm == "values":
|
|
599
|
+
c.values = [self.value(a) for a in args] if len(args) > 1 or (args and args[0].type != "identifier") else ["«" + trim(_txt(args[0]), 60) + "»"]
|
|
600
|
+
elif nm in ("update", "mergeInto"):
|
|
601
|
+
c.kind = "update" if nm == "update" else "insert"
|
|
602
|
+
c.table = self.name(args[0], True) if args else "«table»"
|
|
603
|
+
elif nm in ("deleteFrom", "delete"):
|
|
604
|
+
c.kind = "delete"
|
|
605
|
+
c.table = self.name(args[0], True) if args else "«table»"
|
|
606
|
+
elif nm == "set" and c.last == "conflict":
|
|
607
|
+
piece = f"{self.name(args[0]).split('.')[-1]} = {self.operand(args[1])}" if len(args) == 2 else (_ph(args[0]) + " = ?" if args else "")
|
|
608
|
+
if "DO UPDATE" not in c.conflict:
|
|
609
|
+
c.conflict += " DO UPDATE"
|
|
610
|
+
c.conflict += (", " if " SET " in c.conflict else " SET ") + piece
|
|
611
|
+
elif nm == "set":
|
|
612
|
+
if len(args) == 2:
|
|
613
|
+
col = self.name(args[0]).split(".")[-1]
|
|
614
|
+
c.sets.append(f"{col} = {self.operand(args[1])}")
|
|
615
|
+
elif args:
|
|
616
|
+
c.sets.append(_ph(args[0]) + " = ?")
|
|
617
|
+
elif nm in ("onConflict", "onConflictDoNothing", "onDuplicateKeyUpdate", "onDuplicateKeyIgnore", "onConflictOnConstraint"):
|
|
618
|
+
if nm == "onConflict":
|
|
619
|
+
c.conflict = "ON CONFLICT (" + ", ".join(self.name(a).split(".")[-1] for a in args) + ")"
|
|
620
|
+
elif nm == "onConflictDoNothing":
|
|
621
|
+
c.conflict = "ON CONFLICT DO NOTHING"
|
|
622
|
+
elif nm == "onDuplicateKeyIgnore":
|
|
623
|
+
c.conflict = "ON CONFLICT DO NOTHING"
|
|
624
|
+
else:
|
|
625
|
+
c.conflict = "ON CONFLICT DO UPDATE" if nm == "onDuplicateKeyUpdate" else "ON CONFLICT ON CONSTRAINT " + _ph(args[0] if args else nm)
|
|
626
|
+
c.last = "conflict"
|
|
627
|
+
elif nm in ("doUpdate", "doNothing"):
|
|
628
|
+
c.conflict += " DO NOTHING" if nm == "doNothing" else " DO UPDATE"
|
|
629
|
+
elif nm in ("returning", "returningResult"):
|
|
630
|
+
c.returning = [self.name(a) for a in args] or ["*"]
|
|
631
|
+
elif nm == "select" or nm in TERMINALS or nm in ("hint", "option", "comment", "withTies", "percent", "distinct"):
|
|
632
|
+
if nm == "distinct":
|
|
633
|
+
c.distinct = True
|
|
634
|
+
elif nm in ("hint", "option") and args:
|
|
635
|
+
c.hints.append(f"{nm}: " + trim(_txt(args[0]), 120))
|
|
636
|
+
else:
|
|
637
|
+
c.unknown_steps.append(nm)
|
|
638
|
+
|
|
639
|
+
def _num(self, node: Node) -> str:
|
|
640
|
+
if node.type == "decimal_integer_literal":
|
|
641
|
+
return _txt(node)
|
|
642
|
+
return _ph(node)
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def _conditional(jf, node: Node, anchor: Node) -> bool:
|
|
646
|
+
"""True when `node` runs only on some path after `anchor` (inside an if, loop, switch, try or lambda that
|
|
647
|
+
does not also contain `anchor`)."""
|
|
648
|
+
n = node.parent
|
|
649
|
+
while n is not None and n.type not in ("method_declaration", "constructor_declaration", "class_declaration"):
|
|
650
|
+
if n.type in ("if_statement", "for_statement", "enhanced_for_statement", "while_statement", "do_statement",
|
|
651
|
+
"switch_expression", "switch_statement", "catch_clause", "ternary_expression",
|
|
652
|
+
"switch_block_statement_group", "switch_rule"):
|
|
653
|
+
if not (n.start_byte <= anchor.start_byte and anchor.end_byte <= n.end_byte):
|
|
654
|
+
return True
|
|
655
|
+
n = n.parent
|
|
656
|
+
return False
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def extend(ctx, sites: list[RawSite], stats) -> list[RawSite]:
|
|
660
|
+
claimed: list[tuple[str, str, str, int, int]] = []
|
|
661
|
+
for jf in ctx.repo.files:
|
|
662
|
+
if not any(i.startswith("org.jooq") for i in jf.imports):
|
|
663
|
+
continue
|
|
664
|
+
test = is_test_path(jf.rel) or bool(TEST_FILE.search(jf.rel))
|
|
665
|
+
starts = [c for c in jf.calls if _txt(c.child_by_field_name("name")) in STARTERS]
|
|
666
|
+
for start in starts:
|
|
667
|
+
obj = start.child_by_field_name("object")
|
|
668
|
+
name = _txt(start.child_by_field_name("name"))
|
|
669
|
+
args = _args(start)
|
|
670
|
+
if name in ("update", "delete") and (len(args) != 1 or obj is None):
|
|
671
|
+
continue
|
|
672
|
+
if name in ("update", "delete") and obj is not None and obj.type != "method_invocation":
|
|
673
|
+
# `repository.delete(entity)` is not the DSL: the receiver must be a DSLContext
|
|
674
|
+
rtype = jf._type_of(_txt(obj).split(".")[-1], start) if obj.type in ("identifier", "field_access") else ""
|
|
675
|
+
if not (rtype in ("DSLContext", "DSL", "Configuration") or re.fullmatch(r"(?i)(dsl|ctx|context|create|jooq|dslContext|DSL)", _txt(obj))):
|
|
676
|
+
continue
|
|
677
|
+
if obj is None and name not in jf.static_imports and not any(w == "DSL" for w in jf.static_wildcards):
|
|
678
|
+
continue
|
|
679
|
+
if obj is not None:
|
|
680
|
+
otext = _txt(obj)
|
|
681
|
+
last = otext.split("(")[0].split(".")[-1] if obj.type != "method_invocation" else _txt(obj.child_by_field_name("name"))
|
|
682
|
+
if not (otext.startswith("DSL") or RECEIVER.search(last) or obj.type == "method_invocation"):
|
|
683
|
+
continue
|
|
684
|
+
# a chain used as an argument or operand of another jOOQ chain is a subquery of that statement
|
|
685
|
+
top = start
|
|
686
|
+
while top.parent is not None and top.parent.type == "method_invocation" and \
|
|
687
|
+
top.parent.child_by_field_name("object") is not None and top.parent.child_by_field_name("object").id == top.id:
|
|
688
|
+
top = top.parent
|
|
689
|
+
holder = top.parent
|
|
690
|
+
nested = False
|
|
691
|
+
while holder is not None and holder.type in ("argument_list", "parenthesized_expression"):
|
|
692
|
+
call = holder.parent
|
|
693
|
+
if call is not None and call.type == "method_invocation":
|
|
694
|
+
inner = call
|
|
695
|
+
while inner is not None and inner.type == "method_invocation":
|
|
696
|
+
if _txt(inner.child_by_field_name("name")) in STARTERS | {"exists", "notExists", "in", "notIn", "eq", "field", "table", "union", "unionAll", "with", "as", "fetchCount", "fetchExists"}:
|
|
697
|
+
nested = True
|
|
698
|
+
break
|
|
699
|
+
inner = inner.child_by_field_name("object")
|
|
700
|
+
if nested and _txt(call.child_by_field_name("name")) in ("fetchCount", "fetchExists", "fetch", "execute"):
|
|
701
|
+
nested = False
|
|
702
|
+
break
|
|
703
|
+
if nested:
|
|
704
|
+
continue
|
|
705
|
+
stats.seen("jooq", test)
|
|
706
|
+
var = ""
|
|
707
|
+
line = start.start_point[0] + 1
|
|
708
|
+
j = Jooq(ctx, jf)
|
|
709
|
+
c = Chain()
|
|
710
|
+
try:
|
|
711
|
+
for nm, a, n in j.links(top):
|
|
712
|
+
j.step(c, nm, a, n, False)
|
|
713
|
+
# the chain kept in a variable and extended later in the same method
|
|
714
|
+
decl = top.parent
|
|
715
|
+
if decl is not None and decl.type == "variable_declarator":
|
|
716
|
+
var = _txt(decl.child_by_field_name("name"))
|
|
717
|
+
elif decl is not None and decl.type == "assignment_expression" and decl.child_by_field_name("left") is not None \
|
|
718
|
+
and decl.child_by_field_name("left").type == "identifier":
|
|
719
|
+
var = _txt(decl.child_by_field_name("left"))
|
|
720
|
+
func = jf._enclosing(start, ("method_declaration", "constructor_declaration", "lambda_expression"))
|
|
721
|
+
if var and func is not None:
|
|
722
|
+
outer = jf._enclosing(start, ("method_declaration", "constructor_declaration")) or func
|
|
723
|
+
handled: set[int] = set()
|
|
724
|
+
for kind, node, payload in jf.scope(outer).events.get(var, ()):
|
|
725
|
+
if node.start_byte <= top.end_byte:
|
|
726
|
+
continue
|
|
727
|
+
later: Node | None = None
|
|
728
|
+
if kind == "chain":
|
|
729
|
+
later = node
|
|
730
|
+
elif kind == "set" and payload.type == "method_invocation":
|
|
731
|
+
base = payload
|
|
732
|
+
while base is not None and base.type == "method_invocation":
|
|
733
|
+
base = base.child_by_field_name("object")
|
|
734
|
+
if base is not None and base.type == "identifier" and _txt(base) == var:
|
|
735
|
+
later = payload
|
|
736
|
+
else:
|
|
737
|
+
break # the variable now holds another statement
|
|
738
|
+
if later is None or later.id in handled:
|
|
739
|
+
continue
|
|
740
|
+
handled.add(later.id)
|
|
741
|
+
cond = _conditional(jf, later, top)
|
|
742
|
+
steps = []
|
|
743
|
+
cur = later
|
|
744
|
+
while cur is not None and cur.type == "method_invocation":
|
|
745
|
+
steps.append((_txt(cur.child_by_field_name("name")), _args(cur), cur))
|
|
746
|
+
cur = cur.child_by_field_name("object")
|
|
747
|
+
for nm, a, n in reversed(steps):
|
|
748
|
+
if nm in TERMINALS:
|
|
749
|
+
break # what follows processes the result
|
|
750
|
+
j.step(c, nm, a, n, cond and nm not in ("forUpdate", "forShare", "skipLocked", "noWait"))
|
|
751
|
+
parent_call = top.parent.parent if top.parent is not None and top.parent.type == "argument_list" else None
|
|
752
|
+
if parent_call is not None and _txt(parent_call.child_by_field_name("name")) == "fetchCount":
|
|
753
|
+
sql = "SELECT COUNT(*) FROM (" + c.sql() + ") q"
|
|
754
|
+
elif parent_call is not None and _txt(parent_call.child_by_field_name("name")) == "fetchExists":
|
|
755
|
+
sql = "SELECT EXISTS (" + c.sql() + ")"
|
|
756
|
+
else:
|
|
757
|
+
sql = c.sql()
|
|
758
|
+
except Skip as exc:
|
|
759
|
+
stats.miss("jooq", str(exc), jf.rel, line, test)
|
|
760
|
+
continue
|
|
761
|
+
except RecursionError:
|
|
762
|
+
stats.miss("jooq", "expression nested too deeply", jf.rel, line, test)
|
|
763
|
+
continue
|
|
764
|
+
if c.kind == "select" and not c.tables:
|
|
765
|
+
stats.miss("jooq", "SELECT without FROM in this chain (the FROM is added elsewhere)", jf.rel, line, test)
|
|
766
|
+
continue
|
|
767
|
+
if c.unknown_steps:
|
|
768
|
+
stats.miss("jooq", "chain step not known: " + c.unknown_steps[0], jf.rel, line, test)
|
|
769
|
+
continue
|
|
770
|
+
table = (c.tables[0] if c.tables else c.table)
|
|
771
|
+
notes = []
|
|
772
|
+
conf = "high"
|
|
773
|
+
if j.generated:
|
|
774
|
+
notes.append("table and column names are the generated jOOQ constants in lower case")
|
|
775
|
+
conf = "medium"
|
|
776
|
+
if "«" in sql:
|
|
777
|
+
conf = "medium" if conf == "high" else conf
|
|
778
|
+
if c.hints:
|
|
779
|
+
notes.append("jOOQ " + "; ".join(c.hints) + " (not shown in the statement)")
|
|
780
|
+
if j.runtime or "«" in table:
|
|
781
|
+
notes.append("the table is decided at run time")
|
|
782
|
+
conf = "low"
|
|
783
|
+
s = RawSite(
|
|
784
|
+
file=jf.rel, line=start.child_by_field_name("name").start_point[0] + 1, end_line=top.end_point[0] + 1,
|
|
785
|
+
language="java", kind="call", sink=trim((_txt(obj) + "." if obj is not None else "") + name, 80),
|
|
786
|
+
symbol=jf.symbol(start), sql=sql, resolution="orm", expr=trim(_txt(top)), in_loop=jf.in_loop(start),
|
|
787
|
+
engine_hint="", is_test=test, known_sink=True)
|
|
788
|
+
s.orm = {"library": "jooq", "model_or_table": table.split(" AS ")[0], "operation": c.kind, "confidence": conf}
|
|
789
|
+
if notes:
|
|
790
|
+
s.orm["notes"] = "; ".join(notes)
|
|
791
|
+
ctx.out.append(s)
|
|
792
|
+
stats.hit("jooq", 1, test)
|
|
793
|
+
claimed.append((jf.rel, s.symbol, var, top.start_point[0] + 1, top.end_point[0] + 1))
|
|
794
|
+
if not claimed:
|
|
795
|
+
return sites
|
|
796
|
+
# A call that only executes a chain reported above (`repository.fetch(select)`, or a sink name such as
|
|
797
|
+
# `update` matched inside the chain) was an unresolved site: the statement is the chain's.
|
|
798
|
+
kept = []
|
|
799
|
+
for s in sites:
|
|
800
|
+
if s.sql is None and s.language == "java":
|
|
801
|
+
head = re.match(r"[A-Za-z_]\w*", s.expr or "")
|
|
802
|
+
if any(rel == s.file and ((lo <= s.line <= hi) or (var and head and head.group(0) == var and sym == s.symbol))
|
|
803
|
+
for rel, sym, var, lo, hi in claimed):
|
|
804
|
+
continue
|
|
805
|
+
kept.append(s)
|
|
806
|
+
return kept
|