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,298 @@
|
|
|
1
|
+
"""Prisma Client Python (`prisma_client.db.<model>.find_many(where={...})`) as SQL sites.
|
|
2
|
+
|
|
3
|
+
The Python client is generated from the same `schema.prisma` as the TypeScript one (orm_ts_prisma reads it: models,
|
|
4
|
+
@@map / @map names, relations), and its calls take keyword arguments that mirror the TypeScript object:
|
|
5
|
+
|
|
6
|
+
await prisma_client.db.litellm_verificationtoken.find_unique(where={"token": hashed})
|
|
7
|
+
-> SELECT "token", "key_name", ... FROM "LiteLLM_VerificationToken" WHERE "token" = $1 LIMIT 1
|
|
8
|
+
|
|
9
|
+
A model is reached as `<client>.<model in lower case>` (`db.litellm_verificationtoken`, `tx.user`, `batcher.user`).
|
|
10
|
+
Translated: find_many, find_first, find_first_or_raise, find_unique, find_unique_or_raise, count, group_by, with
|
|
11
|
+
`where` (equality, None as IS NULL, `in`, `not_in`, `not`, `lt`/`lte`/`gt`/`gte`, `contains`/`startswith`/`endswith`,
|
|
12
|
+
`mode: "insensitive"`, AND / OR / NOT), `order`, `take`, `skip`, `distinct`, and each relation in `include` as the
|
|
13
|
+
extra statement Prisma runs for it (one IN over the keys of the rows the first returned). A `where` held in a
|
|
14
|
+
variable, a relation filter (`is`, `some`, `every`, `none`) and a value the source does not say are «run-time parts».
|
|
15
|
+
Writes (create, update, upsert, delete, *_many) are counted, not translated.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import ast
|
|
21
|
+
import re
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from .base import RawSite
|
|
25
|
+
from .orm_py import Emitter, Mod, Project, Stats, src
|
|
26
|
+
|
|
27
|
+
NAME = "prisma"
|
|
28
|
+
READS = {"find_many": "select", "find_first": "select", "find_first_or_raise": "select", "find_unique": "select",
|
|
29
|
+
"find_unique_or_raise": "select", "count": "select", "group_by": "select"}
|
|
30
|
+
WRITES = {"create", "create_many", "update", "update_many", "upsert", "delete", "delete_many", "query_raw", "execute_raw", "query_first"}
|
|
31
|
+
CLIENT = re.compile(r"prisma|\bdb\b|\btx\b|transaction|batch", re.I)
|
|
32
|
+
OPS = {"lt": "<", "lte": "<=", "gt": ">", "gte": ">="}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _key(node: ast.AST | None) -> str | None:
|
|
36
|
+
return node.value if isinstance(node, ast.Constant) and isinstance(node.value, str) else None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Call:
|
|
40
|
+
def __init__(self, model, schema, mod: Mod):
|
|
41
|
+
self.model, self.schema, self.mod = model, schema, mod
|
|
42
|
+
self.engine = schema.engine or "postgres"
|
|
43
|
+
self.n = 0
|
|
44
|
+
self.notes: list[str] = []
|
|
45
|
+
self.partial = False
|
|
46
|
+
|
|
47
|
+
def q(self, name: str) -> str:
|
|
48
|
+
return f'"{name}"' if self.engine == "postgres" else f"`{name}`" if self.engine == "mysql" else name
|
|
49
|
+
|
|
50
|
+
def ph(self) -> str:
|
|
51
|
+
self.n += 1
|
|
52
|
+
return f"${self.n}" if self.engine == "postgres" else "?"
|
|
53
|
+
|
|
54
|
+
def mark(self, node: ast.AST, why: str = "") -> str:
|
|
55
|
+
self.partial = True
|
|
56
|
+
if why:
|
|
57
|
+
self.notes.append(why)
|
|
58
|
+
return "«" + src(node)[:80].replace("»", ">") + "»"
|
|
59
|
+
|
|
60
|
+
def column(self, field: str, model=None) -> str | None:
|
|
61
|
+
f = (model or self.model).fields.get(field)
|
|
62
|
+
if f is None or f.relation:
|
|
63
|
+
return None
|
|
64
|
+
return self.q(f.column)
|
|
65
|
+
|
|
66
|
+
def where(self, node: ast.AST | None, model=None) -> str:
|
|
67
|
+
model = model or self.model
|
|
68
|
+
if node is None:
|
|
69
|
+
return ""
|
|
70
|
+
if not isinstance(node, ast.Dict):
|
|
71
|
+
return self.mark(node, "the where is a variable")
|
|
72
|
+
parts = []
|
|
73
|
+
for k, v in zip(node.keys, node.values):
|
|
74
|
+
key = _key(k)
|
|
75
|
+
if key is None:
|
|
76
|
+
parts.append(self.mark(v, "a where key chosen at run time"))
|
|
77
|
+
continue
|
|
78
|
+
if key in ("AND", "OR", "NOT"):
|
|
79
|
+
items = v.elts if isinstance(v, (ast.List, ast.Tuple)) else [v]
|
|
80
|
+
inner = [self.where(x, model) for x in items]
|
|
81
|
+
inner = [x for x in inner if x]
|
|
82
|
+
if not inner:
|
|
83
|
+
continue
|
|
84
|
+
if key == "NOT":
|
|
85
|
+
parts.append("NOT (" + " AND ".join(inner) + ")")
|
|
86
|
+
else:
|
|
87
|
+
parts.append("(" + f" {key} ".join(inner) + ")" if len(inner) > 1 else inner[0])
|
|
88
|
+
continue
|
|
89
|
+
field = model.fields.get(key)
|
|
90
|
+
if field is None:
|
|
91
|
+
parts.append(self.mark(v, f"`{key}` is not a field of {model.name}"))
|
|
92
|
+
continue
|
|
93
|
+
if field.relation:
|
|
94
|
+
parts.append(self.mark(v, f"a filter on the relation {key}"))
|
|
95
|
+
continue
|
|
96
|
+
col = self.q(field.column)
|
|
97
|
+
parts.append(self.filter(col, v))
|
|
98
|
+
return " AND ".join(p for p in parts if p)
|
|
99
|
+
|
|
100
|
+
def filter(self, col: str, v: ast.AST) -> str:
|
|
101
|
+
if isinstance(v, ast.Constant) and v.value is None:
|
|
102
|
+
return f"{col} IS NULL"
|
|
103
|
+
if not isinstance(v, ast.Dict):
|
|
104
|
+
return f"{col} = {self.ph()}"
|
|
105
|
+
insensitive = any(_key(k) == "mode" and _key(x) == "insensitive" for k, x in zip(v.keys, v.values))
|
|
106
|
+
out = []
|
|
107
|
+
for k, x in zip(v.keys, v.values):
|
|
108
|
+
op = _key(k)
|
|
109
|
+
if op in ("mode", None):
|
|
110
|
+
continue
|
|
111
|
+
if op == "equals":
|
|
112
|
+
out.append(f"{col} IS NULL" if isinstance(x, ast.Constant) and x.value is None else f"{col} = {self.ph()}")
|
|
113
|
+
elif op == "not":
|
|
114
|
+
out.append(f"{col} IS NOT NULL" if isinstance(x, ast.Constant) and x.value is None else
|
|
115
|
+
f"NOT ({self.filter(col, x)})" if isinstance(x, ast.Dict) else f"{col} <> {self.ph()}")
|
|
116
|
+
elif op in ("in", "not_in"):
|
|
117
|
+
items = x.elts if isinstance(x, (ast.List, ast.Tuple)) else None
|
|
118
|
+
listed = ", ".join(self.ph() for _ in items) if items is not None else self.mark(x)
|
|
119
|
+
out.append(f"{col} {'NOT IN' if op == 'not_in' else 'IN'} ({listed})")
|
|
120
|
+
elif op in OPS:
|
|
121
|
+
out.append(f"{col} {OPS[op]} {self.ph()}")
|
|
122
|
+
elif op in ("contains", "startswith", "endswith"):
|
|
123
|
+
like = "ILIKE" if insensitive and self.engine == "postgres" else "LIKE"
|
|
124
|
+
out.append(f"{col} {like} {self.ph()}")
|
|
125
|
+
else:
|
|
126
|
+
out.append(self.mark(x, f"filter `{op}` not read"))
|
|
127
|
+
return " AND ".join(out) if out else f"{col} = {self.ph()}"
|
|
128
|
+
|
|
129
|
+
def order(self, node: ast.AST | None) -> str:
|
|
130
|
+
if node is None:
|
|
131
|
+
return ""
|
|
132
|
+
items = node.elts if isinstance(node, (ast.List, ast.Tuple)) else [node]
|
|
133
|
+
out = []
|
|
134
|
+
for it in items:
|
|
135
|
+
if not isinstance(it, ast.Dict):
|
|
136
|
+
out.append(self.mark(it))
|
|
137
|
+
continue
|
|
138
|
+
for k, v in zip(it.keys, it.values):
|
|
139
|
+
col = self.column(_key(k) or "")
|
|
140
|
+
if col is None:
|
|
141
|
+
out.append(self.mark(it))
|
|
142
|
+
continue
|
|
143
|
+
out.append(col + (" DESC" if _key(v) == "desc" else ""))
|
|
144
|
+
return ", ".join(out)
|
|
145
|
+
|
|
146
|
+
def number(self, node: ast.AST | None) -> str:
|
|
147
|
+
if node is None:
|
|
148
|
+
return ""
|
|
149
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, int):
|
|
150
|
+
return str(node.value)
|
|
151
|
+
return self.mark(node)
|
|
152
|
+
|
|
153
|
+
def columns(self, model=None) -> str:
|
|
154
|
+
model = model or self.model
|
|
155
|
+
return ", ".join(self.q(f.column) for f in model.scalars())
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _kw(call: ast.Call, name: str) -> ast.AST | None:
|
|
159
|
+
return next((k.value for k in call.keywords if k.arg == name), None)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def translate(call: ast.Call, op: str, model, schema, mod: Mod) -> list[tuple[str, str, list[str], bool]]:
|
|
163
|
+
"""[(sql, table, notes, partial)] for one read."""
|
|
164
|
+
c = Call(model, schema, mod)
|
|
165
|
+
table = c.q(model.table) if not model.schema or model.schema == "public" else f"{c.q(model.schema)}.{c.q(model.table)}"
|
|
166
|
+
where = c.where(_kw(call, "where"))
|
|
167
|
+
w = f" WHERE {where}" if where else ""
|
|
168
|
+
if op == "count":
|
|
169
|
+
sql = f"SELECT COUNT(*) FROM {table}{w}"
|
|
170
|
+
elif op == "group_by":
|
|
171
|
+
by = _kw(call, "by")
|
|
172
|
+
cols = [c.column(_key(x) or "") for x in (by.elts if isinstance(by, (ast.List, ast.Tuple)) else [])]
|
|
173
|
+
if not cols or any(x is None for x in cols):
|
|
174
|
+
sql = f"SELECT {c.mark(by) if by is not None else '«by»'}, COUNT(*) FROM {table}{w} GROUP BY «by»"
|
|
175
|
+
else:
|
|
176
|
+
sql = f"SELECT {', '.join(cols)}, COUNT(*) FROM {table}{w} GROUP BY {', '.join(cols)}"
|
|
177
|
+
c.notes.append("group_by: the aggregates it asks for are written as COUNT(*)")
|
|
178
|
+
else:
|
|
179
|
+
order = c.order(_kw(call, "order"))
|
|
180
|
+
take = c.number(_kw(call, "take"))
|
|
181
|
+
skip = c.number(_kw(call, "skip"))
|
|
182
|
+
if op.startswith(("find_first", "find_unique")):
|
|
183
|
+
take = "1"
|
|
184
|
+
distinct = _kw(call, "distinct")
|
|
185
|
+
head = "SELECT DISTINCT" if distinct is not None else "SELECT"
|
|
186
|
+
if distinct is not None:
|
|
187
|
+
c.notes.append("distinct: Prisma may deduplicate in the client instead")
|
|
188
|
+
sql = (f"{head} {c.columns()} FROM {table}{w}" + (f" ORDER BY {order}" if order else "") + (f" LIMIT {take}" if take else "")
|
|
189
|
+
+ (f" OFFSET {skip}" if skip else ""))
|
|
190
|
+
out = [(sql, model.table, list(dict.fromkeys(c.notes)), c.partial)]
|
|
191
|
+
inc = _kw(call, "include")
|
|
192
|
+
if isinstance(inc, ast.Dict) and op not in ("count", "group_by"):
|
|
193
|
+
for k, v in zip(inc.keys, inc.values):
|
|
194
|
+
name = _key(k)
|
|
195
|
+
f = model.fields.get(name or "")
|
|
196
|
+
if f is None or not f.relation or (isinstance(v, ast.Constant) and v.value is False):
|
|
197
|
+
continue
|
|
198
|
+
target = schema.models.get(f.type)
|
|
199
|
+
if target is None:
|
|
200
|
+
continue
|
|
201
|
+
e = Call(target, schema, mod)
|
|
202
|
+
ttable = e.q(target.table)
|
|
203
|
+
back = None
|
|
204
|
+
if f.fk: # this model holds the key: the parents by their key
|
|
205
|
+
keys = [target.fields[r].column if r in target.fields else r for r in f.refs] or target.pk
|
|
206
|
+
cond = f"{e.q(keys[0])} IN («{', '.join(f.fk)} of the {model.table} rows»)" if keys else "«keys»"
|
|
207
|
+
else: # the other model holds it: the children by their foreign key
|
|
208
|
+
back = next((x for x in target.fields.values() if x.relation and x.type == model.name and x.fk), None)
|
|
209
|
+
cond = (f"{e.q(target.fields[back.fk[0]].column if back.fk[0] in target.fields else back.fk[0])} IN («keys of the {model.table} rows»)"
|
|
210
|
+
if back else "«keys»")
|
|
211
|
+
out.append((f"SELECT {e.columns()} FROM {ttable} WHERE {cond}", target.table,
|
|
212
|
+
[f"include {name}: the extra statement Prisma runs for the relation"], "«keys»" in cond))
|
|
213
|
+
return out
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class Finder(ast.NodeVisitor):
|
|
217
|
+
def __init__(self, mod: Mod, schemas, emitter: Emitter, stats: Stats):
|
|
218
|
+
self.mod, self.schemas, self.out, self.stats = mod, schemas, emitter, stats
|
|
219
|
+
self.func: list[str] = []
|
|
220
|
+
self.loops = 0
|
|
221
|
+
|
|
222
|
+
def _scope(self, node, name):
|
|
223
|
+
self.func.append(name)
|
|
224
|
+
loops, self.loops = self.loops, 0
|
|
225
|
+
self.generic_visit(node)
|
|
226
|
+
self.loops = loops
|
|
227
|
+
self.func.pop()
|
|
228
|
+
|
|
229
|
+
def visit_FunctionDef(self, node):
|
|
230
|
+
self._scope(node, node.name)
|
|
231
|
+
|
|
232
|
+
visit_AsyncFunctionDef = visit_FunctionDef
|
|
233
|
+
|
|
234
|
+
def visit_ClassDef(self, node):
|
|
235
|
+
self._scope(node, node.name)
|
|
236
|
+
|
|
237
|
+
def _loop(self, node):
|
|
238
|
+
self.loops += 1
|
|
239
|
+
self.generic_visit(node)
|
|
240
|
+
self.loops -= 1
|
|
241
|
+
|
|
242
|
+
visit_For = visit_AsyncFor = visit_While = _loop
|
|
243
|
+
|
|
244
|
+
def visit_Call(self, node: ast.Call):
|
|
245
|
+
self.generic_visit(node)
|
|
246
|
+
fn = node.func
|
|
247
|
+
if not isinstance(fn, ast.Attribute) or (fn.attr not in READS and fn.attr not in WRITES):
|
|
248
|
+
return
|
|
249
|
+
holder = fn.value
|
|
250
|
+
if not isinstance(holder, ast.Attribute):
|
|
251
|
+
return
|
|
252
|
+
recv = src(holder.value)
|
|
253
|
+
if not CLIENT.search(recv):
|
|
254
|
+
return
|
|
255
|
+
model, schema = None, None
|
|
256
|
+
for s in self.schemas:
|
|
257
|
+
m = next((x for x in s.models.values() if x.name.lower() == holder.attr.lower()), None)
|
|
258
|
+
if m is not None:
|
|
259
|
+
model, schema = m, s
|
|
260
|
+
break
|
|
261
|
+
if model is None:
|
|
262
|
+
return
|
|
263
|
+
self.stats.seen += 1
|
|
264
|
+
where = f"{self.mod.rel}:{node.lineno}"
|
|
265
|
+
if fn.attr in WRITES:
|
|
266
|
+
self.stats.miss("writes are not translated", where)
|
|
267
|
+
return
|
|
268
|
+
try:
|
|
269
|
+
got = translate(node, fn.attr, model, schema, self.mod)
|
|
270
|
+
except Exception as e: # an odd call is counted, never fatal
|
|
271
|
+
self.stats.miss(f"internal error ({type(e).__name__})", where)
|
|
272
|
+
return
|
|
273
|
+
symbol = ".".join(self.func[-2:]) if self.func else ""
|
|
274
|
+
wrote = False
|
|
275
|
+
for sql, table, notes, partial in got:
|
|
276
|
+
wrote = self.out.emit(self.mod, node, symbol, sql, sink=src(fn)[:80], in_loop=self.loops > 0, model=model.name,
|
|
277
|
+
operation="select", confidence="medium" if partial else "high", notes="; ".join(notes),
|
|
278
|
+
engine=schema.engine or "") or wrote
|
|
279
|
+
if wrote:
|
|
280
|
+
self.stats.translated += 1
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def run(root: Path, project: Project):
|
|
284
|
+
"""(sites, stats, tables): the Prisma Client Python reads of the project."""
|
|
285
|
+
stats = Stats(NAME + "_py")
|
|
286
|
+
emitter = Emitter(stats)
|
|
287
|
+
if not any("prisma" in m.text for m in project.mods.values()):
|
|
288
|
+
return [], stats, []
|
|
289
|
+
from . import list_files
|
|
290
|
+
from .orm_ts_prisma import load_schemas
|
|
291
|
+
schemas = load_schemas(None, root, [f for f in list_files(root) if f.endswith(".prisma")])
|
|
292
|
+
if not schemas:
|
|
293
|
+
return [], stats, []
|
|
294
|
+
for mod in project.mods.values():
|
|
295
|
+
if "prisma" not in mod.text and ".db." not in mod.text:
|
|
296
|
+
continue
|
|
297
|
+
Finder(mod, schemas, emitter, stats).visit(mod.tree)
|
|
298
|
+
return emitter.sites, stats, []
|