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,258 @@
|
|
|
1
|
+
"""Named queries in Go projects: SQL kept in .sql files and reached from code by name.
|
|
2
|
+
|
|
3
|
+
Two shapes are linked, so one statement is one site that has both its SQL and its callers:
|
|
4
|
+
|
|
5
|
+
- sqlc: `-- name: ListUsers :many` in a .sql file is compiled into a Go method that sends the same statement
|
|
6
|
+
(rewritten: `sqlc.arg(x)` becomes `$1`, `*` becomes the column list). The generated method is the call site;
|
|
7
|
+
the statement in the .sql file is the same query and is not reported a second time. The Go site carries
|
|
8
|
+
`named_query: {tool, name, file, line}` pointing at the source statement.
|
|
9
|
+
- goyesql (`-- name: get-subscriber` blocks, loaded into a struct whose fields are tagged `query:"get-subscriber"`):
|
|
10
|
+
every use of such a field (`q.GetSubscriber.Get(&out, id)`, `fmt.Sprintf(q.QuerySubscribers, cond)`) is a call
|
|
11
|
+
site with the statement from the file.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
from collections import Counter, defaultdict
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
|
|
21
|
+
from tree_sitter import Node, Query, QueryCursor
|
|
22
|
+
|
|
23
|
+
from .base import RawSite, is_test_path, read_text, trim
|
|
24
|
+
from .go import FUNC_DECL, LANG, _txt
|
|
25
|
+
|
|
26
|
+
NAME_LINE = re.compile(r"^\s*--\s*name:\s*([\w.-]+)[ \t]*(?::(\w+))?[^\n]*$", re.M)
|
|
27
|
+
SQLC_HEAD = re.compile(r"^\s*--\s*name:\s*(\w+)\s+:(\w+)")
|
|
28
|
+
SKIP_DIRS = {".git", "node_modules", "vendor", "target", "dist", "build", ".venv", "venv"}
|
|
29
|
+
SELECTORS = Query(LANG, "(selector_expression field: (field_identifier) @f)")
|
|
30
|
+
VERB = re.compile(r"%(?:\[\d+\])?[svd](?![A-Za-z%])")
|
|
31
|
+
HOLDER = re.compile(r"(?i)(?:^|\.)(q|qs|queries|stmts?|statements)$")
|
|
32
|
+
|
|
33
|
+
LAST: dict = {"goyesql": {}}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class NamedSite(RawSite):
|
|
38
|
+
named_query: dict | None = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def leading_name(sql: str) -> tuple[str, str] | None:
|
|
42
|
+
"""(name, kind) from a `-- name:` line in the comment lines a statement starts with."""
|
|
43
|
+
for line in sql.split("\n"):
|
|
44
|
+
text = line.strip()
|
|
45
|
+
if not text:
|
|
46
|
+
continue
|
|
47
|
+
if not text.startswith("--"):
|
|
48
|
+
return None
|
|
49
|
+
m = NAME_LINE.match(text)
|
|
50
|
+
if m:
|
|
51
|
+
return m.group(1), m.group(2) or ""
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# ---------------------------------------------------------------------------------------- goyesql
|
|
56
|
+
|
|
57
|
+
def _sql_files(root) -> list[str]:
|
|
58
|
+
out = []
|
|
59
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
60
|
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
|
61
|
+
for name in filenames:
|
|
62
|
+
if name.endswith(".sql"):
|
|
63
|
+
out.append(os.path.relpath(os.path.join(dirpath, name), root))
|
|
64
|
+
return sorted(out)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _blocks(text: str) -> list[tuple[str, int, str]]:
|
|
68
|
+
"""(name, line, statement) of each `-- name:` block of a goyesql file."""
|
|
69
|
+
marks = list(NAME_LINE.finditer(text))
|
|
70
|
+
out = []
|
|
71
|
+
for i, m in enumerate(marks):
|
|
72
|
+
end = marks[i + 1].start() if i + 1 < len(marks) else len(text)
|
|
73
|
+
body = text[m.end(): end]
|
|
74
|
+
lines = [ln for ln in body.split("\n") if not re.match(r"\s*--\s*\w+:\s", ln)] # other tags: `-- raw: 1`
|
|
75
|
+
stmt = "\n".join(lines).strip().rstrip(";").strip()
|
|
76
|
+
if stmt:
|
|
77
|
+
out.append((m.group(1), text.count("\n", 0, m.start()) + 1, stmt))
|
|
78
|
+
return out
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def extract(ctx, existing: list[RawSite]) -> list[RawSite]:
|
|
82
|
+
"""Call sites for uses of goyesql query fields. An existing site at the same call that could not resolve its
|
|
83
|
+
SQL is replaced."""
|
|
84
|
+
LAST["goyesql"] = {}
|
|
85
|
+
fields: dict[str, tuple[str, str]] = {} # field name -> (query name, field type)
|
|
86
|
+
owners: set[tuple[str, str]] = set() # (package directory, struct name) of the structs that hold them
|
|
87
|
+
clash: set[str] = set()
|
|
88
|
+
uses_lib = False
|
|
89
|
+
for gf in ctx.files.values():
|
|
90
|
+
if any("goyesql" in p or p.endswith("/yesql") for p in gf.imports.values()):
|
|
91
|
+
uses_lib = True
|
|
92
|
+
if b'query:"' not in gf.src:
|
|
93
|
+
continue
|
|
94
|
+
text = gf.src.decode("utf-8", "replace")
|
|
95
|
+
for m in re.finditer(r"^\s*(\w+)\s+([\w.*\[\]]+)\s+`[^`\n]*\bquery:\"([^\"]+)\"", text, re.M):
|
|
96
|
+
name, typ, query = m.group(1), m.group(2), m.group(3)
|
|
97
|
+
if name in fields and fields[name][0] != query:
|
|
98
|
+
clash.add(name)
|
|
99
|
+
fields[name] = (query, typ)
|
|
100
|
+
holder = None
|
|
101
|
+
for sm in re.finditer(r"^type\s+(\w+)\s+struct\b", text[: m.start()], re.M):
|
|
102
|
+
holder = sm.group(1)
|
|
103
|
+
if holder:
|
|
104
|
+
owners.add((gf.dir, holder))
|
|
105
|
+
if not uses_lib or not fields:
|
|
106
|
+
return existing
|
|
107
|
+
for name in clash:
|
|
108
|
+
fields.pop(name, None)
|
|
109
|
+
|
|
110
|
+
statements: dict[str, list[tuple[str, int, str]]] = defaultdict(list) # query name -> (file, line, sql)
|
|
111
|
+
for rel in _sql_files(ctx.root):
|
|
112
|
+
text = read_text(ctx.root / rel)
|
|
113
|
+
if text is None or "-- name:" not in text:
|
|
114
|
+
continue
|
|
115
|
+
for name, line, stmt in _blocks(text):
|
|
116
|
+
statements[name].append((rel, line, stmt))
|
|
117
|
+
|
|
118
|
+
from .orm_go_types import Types # the type of `x` in `x.GetSubscriber`: a handler method may share the field's name
|
|
119
|
+
types = Types(ctx)
|
|
120
|
+
out: list[NamedSite] = []
|
|
121
|
+
taken: set[tuple[str, int]] = set()
|
|
122
|
+
stats: Counter = Counter()
|
|
123
|
+
for gf in ctx.files.values():
|
|
124
|
+
if not any(name.encode() in gf.src for name in fields):
|
|
125
|
+
continue
|
|
126
|
+
seen_calls: set[int] = set()
|
|
127
|
+
for fld in QueryCursor(SELECTORS).captures(gf.root).get("f", []):
|
|
128
|
+
name = _txt(fld)
|
|
129
|
+
if name not in fields:
|
|
130
|
+
continue
|
|
131
|
+
sel = fld.parent
|
|
132
|
+
if sel is None or sel.type != "selector_expression":
|
|
133
|
+
continue
|
|
134
|
+
query, ftype = fields[name]
|
|
135
|
+
holder = sel.child_by_field_name("operand")
|
|
136
|
+
if holder is None or (holder.type == "identifier" and _txt(holder) in gf.imports):
|
|
137
|
+
continue
|
|
138
|
+
owner = types.named(types.type_of(gf, holder, sel))
|
|
139
|
+
if owner is not None:
|
|
140
|
+
if owner not in owners:
|
|
141
|
+
continue # a method or field of another type with the same name
|
|
142
|
+
elif not HOLDER.search(_txt(holder)):
|
|
143
|
+
continue # type unknown, and the holder is not named like a set of queries
|
|
144
|
+
stats["uses"] += 1
|
|
145
|
+
found = statements.get(query, [])
|
|
146
|
+
app = [f for f in found if not is_test_path(f[0])] or found
|
|
147
|
+
if len(app) != 1:
|
|
148
|
+
stats["not linked: " + ("no statement by that name in a .sql file" if not app else "several statements by that name")] += 1
|
|
149
|
+
continue
|
|
150
|
+
rel, line, stmt = app[0]
|
|
151
|
+
call, method, formatted = _use(sel)
|
|
152
|
+
anchor = call if call is not None else sel
|
|
153
|
+
if anchor.id in seen_calls:
|
|
154
|
+
continue
|
|
155
|
+
seen_calls.add(anchor.id)
|
|
156
|
+
sql = VERB.sub(lambda m: "«" + m.group(0) + "»", stmt) if formatted else stmt
|
|
157
|
+
fn = call.child_by_field_name("function") if call is not None else None
|
|
158
|
+
out.append(NamedSite(
|
|
159
|
+
file=gf.rel, line=anchor.start_point[0] + 1, end_line=anchor.end_point[0] + 1, language="go",
|
|
160
|
+
kind="call" if call is not None else "sql_string", sink=trim(_txt(fn), 80) if fn is not None else "",
|
|
161
|
+
symbol=gf.symbol(anchor), sql=sql, resolution="template" if sql != stmt else "file", expr=trim(_txt(sel)),
|
|
162
|
+
in_loop=gf.in_loop(anchor), engine_hint=gf.file_engine(), is_test=gf.test, known_sink=call is not None and bool(method),
|
|
163
|
+
named_query={"tool": "goyesql", "name": query, "file": rel, "line": line}))
|
|
164
|
+
taken.add((gf.rel, anchor.start_point[0] + 1))
|
|
165
|
+
stats["linked"] += 1
|
|
166
|
+
kept = [s for s in existing if not (s.sql is None and (s.file, s.line) in taken)]
|
|
167
|
+
stats["unresolved_sites_replaced"] = len(existing) - len(kept)
|
|
168
|
+
stats["statements_in_sql_files"] = sum(len(v) for v in statements.values())
|
|
169
|
+
stats["statements_used"] = len({(s.named_query["file"], s.named_query["name"]) for s in out})
|
|
170
|
+
LAST["goyesql"] = dict(stats)
|
|
171
|
+
return kept + out
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _use(sel: Node) -> tuple[Node | None, str, bool]:
|
|
175
|
+
"""(the call a query field is used in, the method called on it, whether it goes through fmt.Sprintf)."""
|
|
176
|
+
p = sel.parent
|
|
177
|
+
if p is not None and p.type == "selector_expression" and p.parent is not None and p.parent.type == "call_expression":
|
|
178
|
+
fld = p.child_by_field_name("field")
|
|
179
|
+
return p.parent, _txt(fld) if fld is not None else "", False # q.GetSubscriber.Get(...)
|
|
180
|
+
formatted = False
|
|
181
|
+
n = sel
|
|
182
|
+
call = None
|
|
183
|
+
while n.parent is not None and n.parent.type not in FUNC_DECL:
|
|
184
|
+
n = n.parent
|
|
185
|
+
if n.type == "call_expression":
|
|
186
|
+
fn = n.child_by_field_name("function")
|
|
187
|
+
text = _txt(fn) if fn is not None else ""
|
|
188
|
+
if text in ("fmt.Sprintf", "strings.ReplaceAll", "strings.Replace", "strings.TrimSpace", "string"):
|
|
189
|
+
formatted = formatted or text == "fmt.Sprintf"
|
|
190
|
+
call = call or n
|
|
191
|
+
continue
|
|
192
|
+
return n, "", formatted
|
|
193
|
+
if n.type in ("block", "statement_list"):
|
|
194
|
+
break
|
|
195
|
+
return call, "", formatted
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# ---------------------------------------------------------------------------------------- linking
|
|
199
|
+
|
|
200
|
+
def link(sites: list[dict]) -> tuple[list[dict], dict]:
|
|
201
|
+
"""Drop the .sql statement that a Go call site stands for, and say on the Go site where the statement is
|
|
202
|
+
written. Returns the sites and the counts for the summary."""
|
|
203
|
+
counts: dict = {}
|
|
204
|
+
sql_named: dict[str, list[dict]] = defaultdict(list)
|
|
205
|
+
for s in sites:
|
|
206
|
+
if s["kind"] == "sql_file" and s["sql"] and "name:" in s["sql"][:400]:
|
|
207
|
+
got = leading_name(s["sql"])
|
|
208
|
+
if got:
|
|
209
|
+
sql_named[got[0]].append(s)
|
|
210
|
+
drop: set[int] = set()
|
|
211
|
+
|
|
212
|
+
# goyesql: the Go site knows its statement's file and name
|
|
213
|
+
by_file_name = {(s["file"], n): s for n, group in sql_named.items() for s in group}
|
|
214
|
+
for s in sites:
|
|
215
|
+
nq = s.get("named_query")
|
|
216
|
+
if nq and nq.get("tool") == "goyesql":
|
|
217
|
+
hit = by_file_name.get((nq["file"], nq["name"]))
|
|
218
|
+
if hit is not None:
|
|
219
|
+
drop.add(id(hit))
|
|
220
|
+
|
|
221
|
+
# sqlc: the generated constant starts with the same `-- name: X :kind` line
|
|
222
|
+
linked = unlinked = 0
|
|
223
|
+
for s in sites:
|
|
224
|
+
if s["language"] != "go" or not s["sql"] or s["kind"] == "sql_file":
|
|
225
|
+
continue
|
|
226
|
+
m = SQLC_HEAD.match(s["sql"])
|
|
227
|
+
if not m:
|
|
228
|
+
continue
|
|
229
|
+
cands = sql_named.get(m.group(1), [])
|
|
230
|
+
if not cands:
|
|
231
|
+
unlinked += 1
|
|
232
|
+
continue
|
|
233
|
+
source = os.path.basename(s["file"])[:-3] if s["file"].endswith(".sql.go") else ""
|
|
234
|
+
same = [c for c in cands if os.path.basename(c["file"]) == source] or cands
|
|
235
|
+
gdir = s["file"].split("/")[:-1]
|
|
236
|
+
|
|
237
|
+
def closeness(c: dict) -> int:
|
|
238
|
+
cdir = c["file"].split("/")[:-1]
|
|
239
|
+
n = 0
|
|
240
|
+
while n < min(len(gdir), len(cdir)) and gdir[n] == cdir[n]:
|
|
241
|
+
n += 1
|
|
242
|
+
return n
|
|
243
|
+
|
|
244
|
+
best = max(same, key=closeness)
|
|
245
|
+
s["named_query"] = {"tool": "sqlc", "name": m.group(1), "kind": m.group(2), "file": best["file"], "line": best["line"]}
|
|
246
|
+
drop.add(id(best))
|
|
247
|
+
linked += 1
|
|
248
|
+
if linked or unlinked:
|
|
249
|
+
counts["sqlc"] = {"generated_sites_linked": linked, "generated_sites_without_source": unlinked}
|
|
250
|
+
if LAST["goyesql"]:
|
|
251
|
+
counts["goyesql"] = dict(LAST["goyesql"])
|
|
252
|
+
if drop:
|
|
253
|
+
counts["sql_file_statements_merged"] = len(drop)
|
|
254
|
+
sites = [s for s in sites if id(s) not in drop]
|
|
255
|
+
left = sum(1 for group in sql_named.values() for s in group if id(s) not in drop)
|
|
256
|
+
if counts:
|
|
257
|
+
counts["named_statements_without_code_site"] = left
|
|
258
|
+
return sites, counts
|