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,1045 @@
|
|
|
1
|
+
"""Prisma client calls (`prisma.<model>.<operation>({...})`) as SQL sites.
|
|
2
|
+
|
|
3
|
+
The schema is read in full: models, `@map` / `@@map`, ids and compound uniques, relations with
|
|
4
|
+
`@relation(fields, references)`, and implicit many-to-many tables. A call is recognised by its shape and the
|
|
5
|
+
schema together: the method is a Prisma operation and the property before it is a model of the schema
|
|
6
|
+
(`prisma.user`, `tx.user` inside `$transaction`, `this.prisma.user`, `ctx.prisma.user`, a repository's client).
|
|
7
|
+
|
|
8
|
+
What Prisma runs is written as it would run it, simplified: one statement for the model; relations in `include` /
|
|
9
|
+
`select` are one more statement per relation level (`WHERE fk IN (parent ids)`) unless the schema enables
|
|
10
|
+
`relationJoins` (then LATERAL joins in the one statement) or the call says `relationLoadStrategy`.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
|
|
18
|
+
from tree_sitter import Node
|
|
19
|
+
|
|
20
|
+
from . import orm_ts as o
|
|
21
|
+
from .base import read_text
|
|
22
|
+
from .orm_ts import as_object, mark, mark_node, txt, unwrap
|
|
23
|
+
|
|
24
|
+
NAME = "prisma"
|
|
25
|
+
READS = {"findMany", "findFirst", "findFirstOrThrow", "findUnique", "findUniqueOrThrow"}
|
|
26
|
+
OPS = READS | {"create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert",
|
|
27
|
+
"delete", "deleteMany", "count", "aggregate", "groupBy"}
|
|
28
|
+
SCALARS = {"String", "Int", "BigInt", "Float", "Decimal", "Boolean", "DateTime", "Json", "Bytes"}
|
|
29
|
+
# receivers that are known not to be a Prisma client although `x.<model>.<op>(` matches (tRPC callers and hooks)
|
|
30
|
+
NOT_CLIENT = re.compile(r"^(?:caller|trpc|api|utils|router|t|trpcClient|queryClient)\b")
|
|
31
|
+
SURE_CLIENT = re.compile(r"prisma|\btx\b|trx|transaction|\bdb\b|Db\b|client|\$extends|\$replica", re.I)
|
|
32
|
+
CMP = {"lt": "<", "lte": "<=", "gt": ">", "gte": ">="}
|
|
33
|
+
AGGREGATES = {"_sum": "SUM", "_avg": "AVG", "_min": "MIN", "_max": "MAX"}
|
|
34
|
+
_BLOCK = re.compile(r"(?m)^[ \t]*(model|enum|type|view)\s+(\w+)\s*\{")
|
|
35
|
+
_FIELD = re.compile(r"^\s*(\w+)\s+(Unsupported\(\"[^\"]*\"\)|\w+)(\[\])?(\?)?(.*)$")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Field:
|
|
39
|
+
__slots__ = ("name", "type", "is_list", "column", "relation", "rel_name", "fk", "refs", "is_id", "unique")
|
|
40
|
+
|
|
41
|
+
def __init__(self, name, type_, is_list):
|
|
42
|
+
self.name, self.type, self.is_list = name, type_, is_list
|
|
43
|
+
self.column = name
|
|
44
|
+
self.relation = False
|
|
45
|
+
self.rel_name = ""
|
|
46
|
+
self.fk: list[str] = [] # this model's fields that hold the key (`fields: [...]`)
|
|
47
|
+
self.refs: list[str] = [] # the other model's fields they point at
|
|
48
|
+
self.is_id = self.unique = False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Model:
|
|
52
|
+
def __init__(self, name: str):
|
|
53
|
+
self.name = name
|
|
54
|
+
self.table = name
|
|
55
|
+
self.schema = ""
|
|
56
|
+
self.fields: dict[str, Field] = {}
|
|
57
|
+
self.pk: list[str] = []
|
|
58
|
+
self.compound: dict[str, list[str]] = {} # name of a compound unique / id -> its fields
|
|
59
|
+
|
|
60
|
+
def scalars(self) -> list[Field]:
|
|
61
|
+
return [f for f in self.fields.values() if not f.relation]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _names(arg: str) -> list[str]:
|
|
65
|
+
m = re.search(r"\[([^\]]*)\]", arg)
|
|
66
|
+
return [n.group(1) for n in (re.match(r"\s*(\w+)", p) for p in m.group(1).split(",")) if n] if m else []
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Schema:
|
|
70
|
+
"""One Prisma schema (possibly several files)."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, base: str, texts: list[str]):
|
|
73
|
+
self.base = base # directory the schema serves (the package that holds `prisma/`)
|
|
74
|
+
self.models: dict[str, Model] = {}
|
|
75
|
+
self.by_accessor: dict[str, Model] = {}
|
|
76
|
+
self.engine = ""
|
|
77
|
+
self.relation_joins = False
|
|
78
|
+
self.native_distinct = False
|
|
79
|
+
blocks = []
|
|
80
|
+
for text in texts:
|
|
81
|
+
m = re.search(r"datasource\s+\w+\s*\{[^}]*?provider\s*=\s*\"(\w+)\"", text, re.S)
|
|
82
|
+
if m:
|
|
83
|
+
from .typescript import PRISMA_PROVIDERS
|
|
84
|
+
self.engine = PRISMA_PROVIDERS.get(m.group(1), "")
|
|
85
|
+
m = re.search(r"previewFeatures\s*=\s*\[([^\]]*)\]", text)
|
|
86
|
+
if m:
|
|
87
|
+
self.relation_joins = self.relation_joins or "relationJoins" in m.group(1)
|
|
88
|
+
self.native_distinct = self.native_distinct or "nativeDistinct" in m.group(1)
|
|
89
|
+
for b in _BLOCK.finditer(text):
|
|
90
|
+
end = text.find("\n}", b.end())
|
|
91
|
+
if end >= 0:
|
|
92
|
+
blocks.append((b.group(1), b.group(2), text[b.end(): end]))
|
|
93
|
+
enums = {name for kind, name, _ in blocks if kind == "enum"}
|
|
94
|
+
composites = {name for kind, name, _ in blocks if kind == "type"}
|
|
95
|
+
for kind, name, body in blocks:
|
|
96
|
+
if kind not in ("model", "view"):
|
|
97
|
+
continue
|
|
98
|
+
model = Model(name)
|
|
99
|
+
for raw in body.split("\n"):
|
|
100
|
+
line = raw.split("//")[0].strip()
|
|
101
|
+
if not line:
|
|
102
|
+
continue
|
|
103
|
+
if line.startswith("@@"):
|
|
104
|
+
head, _, arg = line.partition("(")
|
|
105
|
+
if head == "@@map":
|
|
106
|
+
mm = re.search(r"\"([^\"]+)\"", arg)
|
|
107
|
+
if mm:
|
|
108
|
+
model.table = mm.group(1)
|
|
109
|
+
elif head == "@@schema":
|
|
110
|
+
mm = re.search(r"\"([^\"]+)\"", arg)
|
|
111
|
+
model.schema = mm.group(1) if mm else ""
|
|
112
|
+
elif head in ("@@id", "@@unique"):
|
|
113
|
+
cols = _names(arg)
|
|
114
|
+
named = re.search(r"\bname\s*:\s*\"([^\"]+)\"", arg)
|
|
115
|
+
if cols:
|
|
116
|
+
model.compound[named.group(1) if named else "_".join(cols)] = cols
|
|
117
|
+
if head == "@@id":
|
|
118
|
+
model.pk = cols
|
|
119
|
+
continue
|
|
120
|
+
fm = _FIELD.match(line)
|
|
121
|
+
if not fm:
|
|
122
|
+
continue
|
|
123
|
+
fname, ftype, is_list, _opt, rest = fm.groups()
|
|
124
|
+
base = ftype.split("(")[0]
|
|
125
|
+
field = Field(fname, base, bool(is_list))
|
|
126
|
+
if base not in SCALARS and base not in enums and base != "Unsupported" and base not in composites:
|
|
127
|
+
field.relation = True
|
|
128
|
+
rm = re.search(r"@relation\(((?:[^()]|\([^()]*\))*)\)", rest)
|
|
129
|
+
if rm:
|
|
130
|
+
arg = rm.group(1)
|
|
131
|
+
nm = re.match(r"\s*(?:name\s*:\s*)?\"([^\"]+)\"", arg)
|
|
132
|
+
field.rel_name = nm.group(1) if nm else ""
|
|
133
|
+
fk = re.search(r"\bfields\s*:\s*(\[[^\]]*\])", arg)
|
|
134
|
+
rf = re.search(r"\breferences\s*:\s*(\[[^\]]*\])", arg)
|
|
135
|
+
field.fk = _names(fk.group(1)) if fk else []
|
|
136
|
+
field.refs = _names(rf.group(1)) if rf else []
|
|
137
|
+
else:
|
|
138
|
+
mapped = re.search(r"@map\(\s*\"([^\"]+)\"", rest)
|
|
139
|
+
if mapped:
|
|
140
|
+
field.column = mapped.group(1)
|
|
141
|
+
field.is_id = bool(re.search(r"@id\b", rest))
|
|
142
|
+
field.unique = bool(re.search(r"@unique\b", rest))
|
|
143
|
+
if field.is_id:
|
|
144
|
+
model.pk = [fname]
|
|
145
|
+
model.fields[fname] = field
|
|
146
|
+
if model.fields:
|
|
147
|
+
self.models[name] = model
|
|
148
|
+
self.by_accessor[name[0].lower() + name[1:]] = model
|
|
149
|
+
for m in self.models.values(): # a relation to something that is not a model is not a relation
|
|
150
|
+
for f in m.fields.values():
|
|
151
|
+
if f.relation and f.type not in self.models:
|
|
152
|
+
f.relation = False
|
|
153
|
+
|
|
154
|
+
# -- relations ------------------------------------------------------------------
|
|
155
|
+
def opposite(self, model: Model, field: Field) -> Field | None:
|
|
156
|
+
other = self.models.get(field.type)
|
|
157
|
+
if other is None:
|
|
158
|
+
return None
|
|
159
|
+
cands = [f for f in other.fields.values() if f.relation and f.type == model.name and f.rel_name == field.rel_name
|
|
160
|
+
and not (other is model and f is field)]
|
|
161
|
+
if other is model and len(cands) > 1:
|
|
162
|
+
cands = [f for f in cands if bool(f.fk) != bool(field.fk)] or cands
|
|
163
|
+
return cands[0] if cands else None
|
|
164
|
+
|
|
165
|
+
def link(self, model: Model, field: Field):
|
|
166
|
+
"""How `model.field` joins its target: ("fk", [(own column, target column)]) when the key is on this side,
|
|
167
|
+
("back", [(own column, target column)]) when it is on the other, ("m2m", join table, own column, target
|
|
168
|
+
column, own id column, target id column) for an implicit many-to-many. None when it cannot be told."""
|
|
169
|
+
target = self.models.get(field.type)
|
|
170
|
+
if target is None:
|
|
171
|
+
return None
|
|
172
|
+
if field.fk and len(field.fk) == len(field.refs):
|
|
173
|
+
try:
|
|
174
|
+
return ("fk", [(model.fields[a].column, target.fields[b].column) for a, b in zip(field.fk, field.refs)])
|
|
175
|
+
except KeyError:
|
|
176
|
+
return None
|
|
177
|
+
opp = self.opposite(model, field)
|
|
178
|
+
if opp is not None and opp.fk and len(opp.fk) == len(opp.refs):
|
|
179
|
+
try:
|
|
180
|
+
return ("back", [(model.fields[b].column, target.fields[a].column) for a, b in zip(opp.fk, opp.refs)])
|
|
181
|
+
except KeyError:
|
|
182
|
+
return None
|
|
183
|
+
if field.is_list and (opp is None or opp.is_list) and len(model.pk) == 1 and len(target.pk) == 1:
|
|
184
|
+
first, second = sorted([model.name, target.name])
|
|
185
|
+
table = "_" + (field.rel_name or f"{first}To{second}")
|
|
186
|
+
if model is target:
|
|
187
|
+
own = "A" if opp is None or field.name < opp.name else "B"
|
|
188
|
+
else:
|
|
189
|
+
own = "A" if model.name == first else "B"
|
|
190
|
+
return ("m2m", table, own, "B" if own == "A" else "A", model.fields[model.pk[0]].column,
|
|
191
|
+
target.fields[target.pk[0]].column)
|
|
192
|
+
return None
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def load_schemas(ctx, root, files) -> list[Schema]:
|
|
196
|
+
groups: dict[str, list[str]] = {}
|
|
197
|
+
for f in sorted(files):
|
|
198
|
+
if not f.endswith(".prisma"):
|
|
199
|
+
continue
|
|
200
|
+
d = f.rpartition("/")[0]
|
|
201
|
+
home = next((g for g in groups if d == g or d.startswith(g + "/") or g.startswith(d + "/") or (not g and not d)), None)
|
|
202
|
+
groups.setdefault(home if home is not None else d, []).append(f)
|
|
203
|
+
out = []
|
|
204
|
+
for d, names in groups.items():
|
|
205
|
+
texts = [t for t in (read_text(root / n) for n in names) if t is not None]
|
|
206
|
+
parts = d.split("/") if d else []
|
|
207
|
+
base = "/".join(parts[: len(parts) - 1 - parts[::-1].index("prisma")]) if "prisma" in parts else d
|
|
208
|
+
try:
|
|
209
|
+
schema = Schema(base, texts)
|
|
210
|
+
except Exception:
|
|
211
|
+
continue
|
|
212
|
+
if schema.models:
|
|
213
|
+
out.append(schema)
|
|
214
|
+
return out
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Library:
|
|
218
|
+
name = NAME
|
|
219
|
+
|
|
220
|
+
def __init__(self, ctx, root, files, stats):
|
|
221
|
+
self.ctx, self.stats = ctx, stats
|
|
222
|
+
from . import list_files # the .prisma files: the extractor is handed source files only
|
|
223
|
+
self.schemas = load_schemas(ctx, root, [f for f in list_files(root) if f.endswith(".prisma")])
|
|
224
|
+
self.active = bool(self.schemas)
|
|
225
|
+
ctx.orm_prisma_schemas = self.schemas # Kysely types are often generated from the Prisma schema
|
|
226
|
+
accessors = sorted({a for s in self.schemas for a in s.by_accessor}, key=len, reverse=True)
|
|
227
|
+
ops = "|".join(sorted(OPS, key=len, reverse=True))
|
|
228
|
+
self.pre = re.compile(rb"\.\s*(?:" + "|".join(map(re.escape, accessors)).encode() + rb")\s*\.\s*(?:" + ops.encode()
|
|
229
|
+
+ rb")\s*\(|\]\s*\.\s*(?:findMany|findFirst|findUnique|updateMany|deleteMany|upsert)\s*\(") \
|
|
230
|
+
if accessors else None
|
|
231
|
+
|
|
232
|
+
def wants(self, rel: str, src: bytes, deps) -> bool:
|
|
233
|
+
return self.pre is not None and bool(self.pre.search(src))
|
|
234
|
+
|
|
235
|
+
def prepare(self, wanted) -> None:
|
|
236
|
+
pass
|
|
237
|
+
|
|
238
|
+
def schema_for(self, rel: str, accessor: str) -> Schema | None:
|
|
239
|
+
having = [s for s in self.schemas if accessor in s.by_accessor]
|
|
240
|
+
if len(having) <= 1:
|
|
241
|
+
return having[0] if having else None
|
|
242
|
+
d = os.path.dirname(rel)
|
|
243
|
+
near = [s for s in having if not s.base or d == s.base or d.startswith(s.base + "/")]
|
|
244
|
+
if near:
|
|
245
|
+
return max(near, key=lambda s: len(s.base))
|
|
246
|
+
return max(having, key=lambda s: len(s.models))
|
|
247
|
+
|
|
248
|
+
def sites(self, f) -> list:
|
|
249
|
+
out = []
|
|
250
|
+
for call in f.calls:
|
|
251
|
+
fn = unwrap(call.child_by_field_name("function"))
|
|
252
|
+
if fn is None or fn.type != "member_expression":
|
|
253
|
+
continue
|
|
254
|
+
op = txt(fn.child_by_field_name("property"))
|
|
255
|
+
if op not in OPS:
|
|
256
|
+
continue
|
|
257
|
+
args_node = call.child_by_field_name("arguments")
|
|
258
|
+
if args_node is None or args_node.type != "arguments":
|
|
259
|
+
continue
|
|
260
|
+
holder = unwrap(fn.child_by_field_name("object"))
|
|
261
|
+
if holder is None:
|
|
262
|
+
continue
|
|
263
|
+
line = call.start_point[0] + 1
|
|
264
|
+
if holder.type == "subscript_expression":
|
|
265
|
+
recv = txt(holder.child_by_field_name("object"))
|
|
266
|
+
if SURE_CLIENT.search(recv) and not NOT_CLIENT.match(recv):
|
|
267
|
+
self.stats.see(NAME, f.test)
|
|
268
|
+
self.stats.miss(NAME, f.test, "model chosen at run time (client[model])", f.rel, line)
|
|
269
|
+
continue
|
|
270
|
+
if holder.type != "member_expression":
|
|
271
|
+
continue
|
|
272
|
+
accessor = txt(holder.child_by_field_name("property"))
|
|
273
|
+
schema = self.schema_for(f.rel, accessor)
|
|
274
|
+
if schema is None:
|
|
275
|
+
continue
|
|
276
|
+
recv = txt(holder.child_by_field_name("object"))
|
|
277
|
+
if NOT_CLIENT.match(recv):
|
|
278
|
+
continue
|
|
279
|
+
self.stats.see(NAME, f.test)
|
|
280
|
+
model = schema.by_accessor[accessor]
|
|
281
|
+
args = [a for a in args_node.named_children if a.type != "comment"]
|
|
282
|
+
try:
|
|
283
|
+
made = Call(self, f, call, schema, model, op, args, recv).run()
|
|
284
|
+
except Exception as e: # an odd call is counted, never fatal
|
|
285
|
+
if os.environ.get("CODECOP_ORM_DEBUG"):
|
|
286
|
+
raise
|
|
287
|
+
self.stats.miss(NAME, f.test, f"internal error ({type(e).__name__})", f.rel, line)
|
|
288
|
+
continue
|
|
289
|
+
if not made:
|
|
290
|
+
self.stats.miss(NAME, f.test, "arguments could not be read", f.rel, line)
|
|
291
|
+
continue
|
|
292
|
+
self.stats.ok(NAME, f.test, len(made))
|
|
293
|
+
out.extend(made)
|
|
294
|
+
return out
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
class Call:
|
|
298
|
+
"""One client call being translated."""
|
|
299
|
+
|
|
300
|
+
def __init__(self, lib: Library, f, call: Node, schema: Schema, model: Model, op: str, args: list[Node], recv: str):
|
|
301
|
+
self.lib, self.f, self.call, self.schema, self.model, self.op, self.args = lib, f, call, schema, model, op, args
|
|
302
|
+
self.engine = schema.engine or f.ctx.prisma_provider(f.rel) or f.file_engine()
|
|
303
|
+
self.notes: list[str] = []
|
|
304
|
+
self.level = 2 if SURE_CLIENT.search(recv) else 1
|
|
305
|
+
if self.level == 1:
|
|
306
|
+
self.notes.append(f"receiver `{o.trim(recv, 40)}` taken to be a Prisma client because `{model.name}` is a model")
|
|
307
|
+
self.sink = txt(call.child_by_field_name("function"))
|
|
308
|
+
self.qualify = False
|
|
309
|
+
self.aliases = 0
|
|
310
|
+
self.extra_sites: list[tuple[str, str, str]] = [] # (sql, table, note)
|
|
311
|
+
|
|
312
|
+
# -- small helpers -----------------------------------------------------------------
|
|
313
|
+
def q(self, name: str) -> str:
|
|
314
|
+
return o.quote(self.engine, name)
|
|
315
|
+
|
|
316
|
+
def table(self, model: Model) -> str:
|
|
317
|
+
return (self.q(model.schema) + "." if model.schema and model.schema != "public" else "") + self.q(model.table)
|
|
318
|
+
|
|
319
|
+
def col(self, ref: str | None, column: str) -> str:
|
|
320
|
+
return f"{ref}.{self.q(column)}" if ref else self.q(column)
|
|
321
|
+
|
|
322
|
+
def lower(self, level: int, note: str) -> None:
|
|
323
|
+
self.level = min(self.level, level)
|
|
324
|
+
self.notes.append(note)
|
|
325
|
+
|
|
326
|
+
def obj(self, node: Node | None):
|
|
327
|
+
return as_object(self.f, node, self.call)
|
|
328
|
+
|
|
329
|
+
def like(self, colref: str, pattern: str, insensitive: bool) -> str:
|
|
330
|
+
if self.engine == "mysql":
|
|
331
|
+
parts = [p.strip() for p in pattern.split("||")]
|
|
332
|
+
return f"{colref} LIKE CONCAT({', '.join(parts)})" if len(parts) > 1 else f"{colref} LIKE {pattern}"
|
|
333
|
+
return f"{colref} {'ILIKE' if insensitive else 'LIKE'} {pattern}"
|
|
334
|
+
|
|
335
|
+
# -- where -------------------------------------------------------------------------
|
|
336
|
+
def where(self, node: Node | None, model: Model, ref: str | None) -> str:
|
|
337
|
+
"""The predicate of a `where` object ("" when there is none)."""
|
|
338
|
+
node = unwrap(node)
|
|
339
|
+
if node is None or o.is_undefined(node):
|
|
340
|
+
return ""
|
|
341
|
+
obj = self.obj(node)
|
|
342
|
+
if obj is None:
|
|
343
|
+
return mark_node(node)
|
|
344
|
+
preds = [p for p in (self.cond(k, v, model, ref) for k, v in obj.entries) if p]
|
|
345
|
+
preds += [mark(e) for e in obj.extra]
|
|
346
|
+
preds += [mark("optional: " + text) for _k, _v, text in obj.maybe]
|
|
347
|
+
if obj.maybe:
|
|
348
|
+
self.notes.append("filters added under a condition: " + ", ".join(dict.fromkeys(k for k, _v, _t in obj.maybe)))
|
|
349
|
+
return " AND ".join(preds)
|
|
350
|
+
|
|
351
|
+
def _each(self, node: Node, model: Model, ref: str | None) -> list[str] | None:
|
|
352
|
+
"""The predicates of `AND: [...]` / `OR: [...]`: one per element; None when the list is built at run time."""
|
|
353
|
+
node = unwrap(node)
|
|
354
|
+
items = o.array_items(node)
|
|
355
|
+
if items is not None:
|
|
356
|
+
out = []
|
|
357
|
+
for it in items:
|
|
358
|
+
p = self.where(it, model, ref)
|
|
359
|
+
out.append(f"({p})" if p else "TRUE")
|
|
360
|
+
return out
|
|
361
|
+
if node is not None and node.type == "call_expression": # xs.map((x) => ({ ... })): one predicate per element
|
|
362
|
+
fn = unwrap(node.child_by_field_name("function"))
|
|
363
|
+
cargs = [a for a in node.child_by_field_name("arguments").named_children] if node.child_by_field_name("arguments") else []
|
|
364
|
+
if fn is not None and fn.type == "member_expression" and txt(fn.child_by_field_name("property")) in ("map", "flatMap") and cargs:
|
|
365
|
+
body = o.callback_body(cargs[0])
|
|
366
|
+
if body is not None and body.type == "object":
|
|
367
|
+
p = self.where(body, model, ref)
|
|
368
|
+
return [f"({p})" if p else "TRUE", mark("…for each of " + txt(fn.child_by_field_name("object")))]
|
|
369
|
+
return None
|
|
370
|
+
|
|
371
|
+
def cond(self, key: str, v: Node, model: Model, ref: str | None) -> str:
|
|
372
|
+
if key in ("AND", "OR", "NOT"):
|
|
373
|
+
uv = unwrap(v)
|
|
374
|
+
if o.is_undefined(uv):
|
|
375
|
+
return ""
|
|
376
|
+
if uv is not None and uv.type in ("object", "identifier") and self.obj(uv) is not None:
|
|
377
|
+
p = self.where(uv, model, ref)
|
|
378
|
+
if not p:
|
|
379
|
+
return ""
|
|
380
|
+
return f"NOT ({p})" if key == "NOT" else f"({p})"
|
|
381
|
+
parts = self._each(uv, model, ref)
|
|
382
|
+
if parts is None:
|
|
383
|
+
return ("NOT " if key == "NOT" else "") + mark(f"{key}: {txt(uv)}")
|
|
384
|
+
if not parts:
|
|
385
|
+
return "FALSE" if key == "OR" else ""
|
|
386
|
+
if key == "NOT":
|
|
387
|
+
return " AND ".join(f"NOT {p}" for p in parts)
|
|
388
|
+
joined = (" OR " if key == "OR" else " AND ").join(parts)
|
|
389
|
+
return f"({joined})"
|
|
390
|
+
field = model.fields.get(key)
|
|
391
|
+
if field is None:
|
|
392
|
+
cols = model.compound.get(key)
|
|
393
|
+
sub = self.obj(v) if cols else None
|
|
394
|
+
if sub is not None: # `projectId_id: { projectId, id }`: a compound unique key
|
|
395
|
+
return " AND ".join(p for p in (self.cond(k, x, model, ref) for k, x in sub.entries) if p)
|
|
396
|
+
self.lower(1, f"`{key}` is not a field of {model.name}")
|
|
397
|
+
return mark(f"{key}: {txt(v)}")
|
|
398
|
+
if field.relation:
|
|
399
|
+
return self.relation(field, v, model, ref)
|
|
400
|
+
uv = unwrap(v)
|
|
401
|
+
if field.is_list and uv is not None and uv.type in ("call_expression", "identifier", "member_expression") and self.obj(uv) is None:
|
|
402
|
+
return mark(f"{key}: {txt(uv)}") # a list filter object (has / hasSome / equals) built elsewhere
|
|
403
|
+
return self.scalar(self.col(ref, field.column), v)
|
|
404
|
+
|
|
405
|
+
def scalar(self, colref: str, v: Node) -> str:
|
|
406
|
+
uv = unwrap(v)
|
|
407
|
+
if uv is None or o.is_undefined(uv):
|
|
408
|
+
return ""
|
|
409
|
+
lit = o.literal(uv)
|
|
410
|
+
if lit == "NULL":
|
|
411
|
+
return f"{colref} IS NULL"
|
|
412
|
+
if lit is not None:
|
|
413
|
+
return f"{colref} = {lit}"
|
|
414
|
+
obj = self.obj(uv) if uv.type in ("object", "identifier", "shorthand_property_identifier") else None
|
|
415
|
+
if obj is None:
|
|
416
|
+
return f"{colref} = {mark_node(uv)}"
|
|
417
|
+
mode = obj.get("mode")
|
|
418
|
+
insensitive = mode is not None and "insensitive" in txt(mode)
|
|
419
|
+
preds = []
|
|
420
|
+
for op, x in obj.entries:
|
|
421
|
+
ux = unwrap(x)
|
|
422
|
+
xl = o.literal(ux)
|
|
423
|
+
val = o.value(ux)
|
|
424
|
+
if op == "mode" or o.is_undefined(ux):
|
|
425
|
+
continue
|
|
426
|
+
if op == "equals":
|
|
427
|
+
preds.append(f"{colref} IS NULL" if xl == "NULL" else self.like(colref, val, True) if insensitive else f"{colref} = {val}")
|
|
428
|
+
elif op == "not":
|
|
429
|
+
if xl == "NULL":
|
|
430
|
+
preds.append(f"{colref} IS NOT NULL")
|
|
431
|
+
elif ux is not None and ux.type == "object":
|
|
432
|
+
inner = self.scalar(colref, ux)
|
|
433
|
+
preds.append(f"NOT ({inner})" if inner else "")
|
|
434
|
+
else:
|
|
435
|
+
preds.append(f"{colref} <> {val}")
|
|
436
|
+
elif op in ("in", "notIn"):
|
|
437
|
+
preds.append(f"{colref} {'NOT IN' if op == 'notIn' else 'IN'} ({o.in_list(ux)})")
|
|
438
|
+
elif op in ("lt", "lte", "gt", "gte"):
|
|
439
|
+
preds.append(f"{colref} {CMP[op]} {val}")
|
|
440
|
+
elif op == "contains":
|
|
441
|
+
preds.append(self.like(colref, f"'%' || {val} || '%'", insensitive))
|
|
442
|
+
elif op == "startsWith":
|
|
443
|
+
preds.append(self.like(colref, f"{val} || '%'", insensitive))
|
|
444
|
+
elif op == "endsWith":
|
|
445
|
+
preds.append(self.like(colref, f"'%' || {val}", insensitive))
|
|
446
|
+
elif op == "has":
|
|
447
|
+
preds.append(f"{val} = ANY({colref})")
|
|
448
|
+
elif op == "hasSome":
|
|
449
|
+
preds.append(f"{colref} && {val}")
|
|
450
|
+
elif op == "hasEvery":
|
|
451
|
+
preds.append(f"{colref} @> {val}")
|
|
452
|
+
elif op == "isEmpty":
|
|
453
|
+
preds.append(f"{colref} = '{{}}'")
|
|
454
|
+
elif op == "search":
|
|
455
|
+
preds.append(f"to_tsvector({colref}) @@ to_tsquery({val})")
|
|
456
|
+
else: # Json filters (path, string_contains, array_contains ...) and anything newer
|
|
457
|
+
preds.append(mark(f"{op}: {txt(ux)}"))
|
|
458
|
+
preds += [mark(e) for e in obj.extra]
|
|
459
|
+
preds = [p for p in preds if p]
|
|
460
|
+
if not preds:
|
|
461
|
+
return ""
|
|
462
|
+
return " AND ".join(preds)
|
|
463
|
+
|
|
464
|
+
def _alias(self, target: Model, ref: str | None) -> tuple[str, str]:
|
|
465
|
+
"""(FROM text, reference) for a related table inside a subquery; aliased so a self-relation stays distinct."""
|
|
466
|
+
self.aliases += 1
|
|
467
|
+
alias = self.q(f"j{self.aliases}")
|
|
468
|
+
return f"{self.table(target)} AS {alias}", alias
|
|
469
|
+
|
|
470
|
+
def _join_pred(self, link, ref: str, inner_ref: str) -> tuple[str, str]:
|
|
471
|
+
"""(extra FROM text, join predicate) between the outer reference and the related table's reference."""
|
|
472
|
+
if link[0] in ("fk", "back"):
|
|
473
|
+
return "", " AND ".join(f"{self.col(inner_ref, b)} = {self.col(ref, a)}" for a, b in link[1])
|
|
474
|
+
_, jt, own, other, own_id, target_id = link
|
|
475
|
+
jref = self.q(jt)
|
|
476
|
+
return (f" INNER JOIN {jref} ON {self.col(jref, other)} = {self.col(inner_ref, target_id)}",
|
|
477
|
+
f"{self.col(jref, own)} = {self.col(ref, own_id)}")
|
|
478
|
+
|
|
479
|
+
def relation(self, field: Field, v: Node, model: Model, ref: str | None) -> str:
|
|
480
|
+
uv = unwrap(v)
|
|
481
|
+
if uv is None or o.is_undefined(uv):
|
|
482
|
+
return ""
|
|
483
|
+
self.qualify = True
|
|
484
|
+
ref = ref or self.table(model)
|
|
485
|
+
target = self.schema.models[field.type]
|
|
486
|
+
link = self.schema.link(model, field)
|
|
487
|
+
if link is None:
|
|
488
|
+
self.lower(1, f"relation {model.name}.{field.name} could not be read from the schema")
|
|
489
|
+
return mark(f"{field.name}: {txt(uv)}")
|
|
490
|
+
|
|
491
|
+
def exists(inner: Node | None, negate: bool = False, negate_inner: bool = False) -> str:
|
|
492
|
+
from_, iref = self._alias(target, ref)
|
|
493
|
+
more, join = self._join_pred(link, ref, iref)
|
|
494
|
+
p = self.where(inner, target, iref) if inner is not None else ""
|
|
495
|
+
if negate_inner:
|
|
496
|
+
p = f"NOT ({p})" if p else "FALSE"
|
|
497
|
+
return f"{'NOT ' if negate else ''}EXISTS (SELECT 1 FROM {from_}{more} WHERE {join}{' AND ' + p if p else ''})"
|
|
498
|
+
|
|
499
|
+
if o.literal(uv) == "NULL":
|
|
500
|
+
if link[0] == "fk":
|
|
501
|
+
return " AND ".join(f"{self.col(ref, a)} IS NULL" for a, _ in link[1])
|
|
502
|
+
return exists(None, negate=True)
|
|
503
|
+
obj = self.obj(uv)
|
|
504
|
+
if obj is None:
|
|
505
|
+
return mark(f"{field.name}: {txt(uv)}")
|
|
506
|
+
keys = obj.keys()
|
|
507
|
+
if keys and all(k in ("some", "every", "none", "is", "isNot") for k in keys) and not obj.extra:
|
|
508
|
+
preds = []
|
|
509
|
+
for k, inner in obj.entries:
|
|
510
|
+
if o.is_undefined(inner):
|
|
511
|
+
continue
|
|
512
|
+
if o.literal(inner) == "NULL": # is: null / isNot: null
|
|
513
|
+
if link[0] == "fk":
|
|
514
|
+
preds.append(" AND ".join(f"{self.col(ref, a)} IS {'NOT ' if k == 'isNot' else ''}NULL" for a, _ in link[1]))
|
|
515
|
+
else:
|
|
516
|
+
preds.append(exists(None, negate=k == "is"))
|
|
517
|
+
elif k in ("some", "is"):
|
|
518
|
+
preds.append(exists(inner))
|
|
519
|
+
elif k in ("none", "isNot"):
|
|
520
|
+
preds.append(exists(inner, negate=True))
|
|
521
|
+
else:
|
|
522
|
+
preds.append(exists(inner, negate=True, negate_inner=True))
|
|
523
|
+
return " AND ".join(preds)
|
|
524
|
+
return exists(uv)
|
|
525
|
+
|
|
526
|
+
# -- columns and relations to load -----------------------------------------------------
|
|
527
|
+
def columns(self, model: Model, ref: str | None, args, *, need: set[str] | None = None) -> tuple[list[str], list[tuple[Field, Node | None]], list[tuple[Field, Node | None]]]:
|
|
528
|
+
"""(select list, relations to load with their arguments, relations to count) for `select` / `include` /
|
|
529
|
+
`omit`."""
|
|
530
|
+
select = self.obj(args.get("select")) if args is not None and args.get("select") is not None else None
|
|
531
|
+
include = self.obj(args.get("include")) if args is not None and args.get("include") is not None else None
|
|
532
|
+
omit = self.obj(args.get("omit")) if args is not None and args.get("omit") is not None else None
|
|
533
|
+
relations: list[tuple[Field, Node | None]] = []
|
|
534
|
+
counts: list[tuple[Field, Node | None]] = []
|
|
535
|
+
dynamic: list[str] = []
|
|
536
|
+
|
|
537
|
+
def take_relations(obj) -> None:
|
|
538
|
+
for k, v in obj.entries:
|
|
539
|
+
fld = model.fields.get(k)
|
|
540
|
+
if k == "_count":
|
|
541
|
+
sub = self.obj(v)
|
|
542
|
+
sel = self.obj(sub.get("select")) if sub is not None and sub.get("select") is not None else None
|
|
543
|
+
if sel is not None:
|
|
544
|
+
for ck, cv in sel.entries:
|
|
545
|
+
cf = model.fields.get(ck)
|
|
546
|
+
if cf is not None and cf.relation and txt(unwrap(cv)) != "false":
|
|
547
|
+
counts.append((cf, cv))
|
|
548
|
+
else:
|
|
549
|
+
counts.extend((cf, None) for cf in model.fields.values() if cf.relation and cf.is_list)
|
|
550
|
+
elif fld is not None and fld.relation and txt(unwrap(v)) not in ("false", "undefined"):
|
|
551
|
+
relations.append((fld, v))
|
|
552
|
+
|
|
553
|
+
if args is not None and args.get("select") is not None and select is None:
|
|
554
|
+
dynamic.append(mark_node(args.get("select")))
|
|
555
|
+
fields = []
|
|
556
|
+
elif select is not None:
|
|
557
|
+
fields = [model.fields[k] for k, v in select.entries
|
|
558
|
+
if k in model.fields and not model.fields[k].relation and txt(unwrap(v)) not in ("false", "undefined")]
|
|
559
|
+
take_relations(select)
|
|
560
|
+
dynamic += [mark(e) for e in select.extra]
|
|
561
|
+
else:
|
|
562
|
+
fields = model.scalars()
|
|
563
|
+
if omit is not None:
|
|
564
|
+
dropped = {k for k, v in omit.entries if txt(unwrap(v)) == "true"}
|
|
565
|
+
fields = [f for f in fields if f.name not in dropped]
|
|
566
|
+
if include is not None:
|
|
567
|
+
take_relations(include)
|
|
568
|
+
dynamic_inc = [mark(e) for e in include.extra]
|
|
569
|
+
if dynamic_inc:
|
|
570
|
+
self.notes.append("include has parts decided at run time: " + ", ".join(dynamic_inc))
|
|
571
|
+
elif args is not None and args.get("include") is not None:
|
|
572
|
+
self.notes.append("include decided at run time: " + mark_node(args.get("include")))
|
|
573
|
+
names = [f.column for f in fields]
|
|
574
|
+
for extra in sorted(need or ()): # key columns Prisma adds to tie the relation rows back
|
|
575
|
+
if extra not in names:
|
|
576
|
+
names.append(extra)
|
|
577
|
+
if select is not None:
|
|
578
|
+
for fld, _ in relations:
|
|
579
|
+
link = self.schema.link(model, fld)
|
|
580
|
+
if link is not None and link[0] in ("fk", "back"):
|
|
581
|
+
for a, _b in link[1]:
|
|
582
|
+
if a not in names:
|
|
583
|
+
names.append(a)
|
|
584
|
+
cols = [self.col(ref, c) for c in names] + dynamic
|
|
585
|
+
if not cols:
|
|
586
|
+
cols = [self.col(ref, model.fields[p].column) for p in model.pk if p in model.fields] or ["1"]
|
|
587
|
+
return cols, relations, counts
|
|
588
|
+
|
|
589
|
+
def tail(self, args, model: Model, ref: str | None, *, first: bool = False, unique: bool = False) -> str:
|
|
590
|
+
"""ORDER BY / LIMIT / OFFSET of a read."""
|
|
591
|
+
out = ""
|
|
592
|
+
order = args.get("orderBy") if args is not None else None
|
|
593
|
+
if order is not None and not o.is_undefined(order):
|
|
594
|
+
parts = self.order(order, model, ref)
|
|
595
|
+
if parts:
|
|
596
|
+
out += " ORDER BY " + ", ".join(parts)
|
|
597
|
+
take = args.get("take") if args is not None else None
|
|
598
|
+
if take is not None and not o.is_undefined(take):
|
|
599
|
+
out += f" LIMIT {o.value(take)}"
|
|
600
|
+
elif first or unique:
|
|
601
|
+
out += " LIMIT 1"
|
|
602
|
+
skip = args.get("skip") if args is not None else None
|
|
603
|
+
if skip is not None and not o.is_undefined(skip):
|
|
604
|
+
out += f" OFFSET {o.value(skip)}"
|
|
605
|
+
return out
|
|
606
|
+
|
|
607
|
+
def order(self, node: Node, model: Model, ref: str | None) -> list[str]:
|
|
608
|
+
node = unwrap(node)
|
|
609
|
+
items = o.array_items(node)
|
|
610
|
+
if items is None:
|
|
611
|
+
items = [node]
|
|
612
|
+
out = []
|
|
613
|
+
for it in items:
|
|
614
|
+
obj = self.obj(it)
|
|
615
|
+
if obj is None:
|
|
616
|
+
out.append(mark_node(it))
|
|
617
|
+
continue
|
|
618
|
+
for k, v in obj.entries:
|
|
619
|
+
fld = model.fields.get(k)
|
|
620
|
+
uv = unwrap(v)
|
|
621
|
+
if fld is None or fld.relation:
|
|
622
|
+
out.append(mark(f"{k}: {txt(uv)}"))
|
|
623
|
+
if fld is not None:
|
|
624
|
+
self.notes.append(f"ordered by relation {model.name}.{k} (a join Prisma adds)")
|
|
625
|
+
continue
|
|
626
|
+
direction, nulls = "", ""
|
|
627
|
+
sub = self.obj(uv) if uv is not None and uv.type == "object" else None
|
|
628
|
+
if sub is not None:
|
|
629
|
+
d = o.string_value(sub.get("sort"))
|
|
630
|
+
direction = d or ""
|
|
631
|
+
n = o.string_value(sub.get("nulls"))
|
|
632
|
+
nulls = f" NULLS {n.upper()}" if n in ("first", "last") else ""
|
|
633
|
+
else:
|
|
634
|
+
d = o.string_value(uv)
|
|
635
|
+
if d is None:
|
|
636
|
+
self.notes.append(f"sort direction of {k} decided at run time: {mark_node(uv)}")
|
|
637
|
+
direction = d or ""
|
|
638
|
+
out.append(self.col(ref, fld.column) + (" DESC" if direction == "desc" else "") + nulls)
|
|
639
|
+
out += [mark(e) for e in obj.extra]
|
|
640
|
+
return out
|
|
641
|
+
|
|
642
|
+
# -- reads -----------------------------------------------------------------------------
|
|
643
|
+
def strategy(self, args) -> str:
|
|
644
|
+
s = o.string_value(args.get("relationLoadStrategy")) if args is not None and args.get("relationLoadStrategy") is not None else None
|
|
645
|
+
if s in ("join", "query"):
|
|
646
|
+
return s
|
|
647
|
+
return "join" if self.schema.relation_joins and self.engine in ("postgres", "mysql") else "query"
|
|
648
|
+
|
|
649
|
+
def lateral(self, model: Model, ref: str, relations, depth: int) -> str:
|
|
650
|
+
"""`relationJoins`: each relation is a LATERAL join inside the one statement."""
|
|
651
|
+
out = ""
|
|
652
|
+
for fld, v in relations:
|
|
653
|
+
link = self.schema.link(model, fld)
|
|
654
|
+
target = self.schema.models[fld.type]
|
|
655
|
+
if link is None or depth > o.SETTINGS["orm_max_relation_depth"]:
|
|
656
|
+
self.lower(1, f"relation {model.name}.{fld.name} not followed")
|
|
657
|
+
continue
|
|
658
|
+
sub = self.obj(v) if v is not None and unwrap(v) is not None and unwrap(v).type in ("object", "identifier") else None
|
|
659
|
+
from_, iref = self._alias(target, ref)
|
|
660
|
+
more, join = self._join_pred(link, ref, iref)
|
|
661
|
+
cols, rels, _counts = self.columns(target, iref, sub)
|
|
662
|
+
w = self.where(sub.get("where"), target, iref) if sub is not None and sub.get("where") is not None else ""
|
|
663
|
+
inner = self.lateral(target, iref, rels, depth + 1) if rels else ""
|
|
664
|
+
tail = self.tail(sub, target, iref) if sub is not None else ""
|
|
665
|
+
out += (f" LEFT JOIN LATERAL (SELECT {', '.join(cols)} FROM {from_}{more}{inner} WHERE {join}"
|
|
666
|
+
f"{' AND ' + w if w else ''}{tail}) AS {self.q(fld.name)} ON TRUE")
|
|
667
|
+
return out
|
|
668
|
+
|
|
669
|
+
def load(self, model: Model, relations, depth: int, path: str) -> None:
|
|
670
|
+
"""Query strategy: one statement per relation, keyed by the parent rows' ids."""
|
|
671
|
+
for fld, v in relations:
|
|
672
|
+
if len(self.extra_sites) >= o.SETTINGS["orm_max_statements_per_call"] or depth > o.SETTINGS["orm_max_relation_depth"]:
|
|
673
|
+
self.lower(1, "more relations than the settings follow")
|
|
674
|
+
return
|
|
675
|
+
link = self.schema.link(model, fld)
|
|
676
|
+
target = self.schema.models[fld.type]
|
|
677
|
+
where_path = f"{path}.{fld.name}"
|
|
678
|
+
if link is None:
|
|
679
|
+
self.lower(1, f"relation {model.name}.{fld.name} could not be read from the schema")
|
|
680
|
+
continue
|
|
681
|
+
sub = self.obj(v) if v is not None and unwrap(v) is not None and unwrap(v).type in ("object", "identifier") else None
|
|
682
|
+
tref = self.table(target)
|
|
683
|
+
if link[0] == "m2m":
|
|
684
|
+
_, jt, own, other, _own_id, target_id = link
|
|
685
|
+
jref = self.q(jt)
|
|
686
|
+
cols, rels, counts = self.columns(target, tref, sub)
|
|
687
|
+
from_ = f"{tref} INNER JOIN {jref} ON {self.col(jref, other)} = {self.col(tref, target_id)}"
|
|
688
|
+
key = f"{self.col(jref, own)} IN ({mark('ids of the ' + model.name + ' rows')})"
|
|
689
|
+
cols = [self.col(jref, own)] + cols
|
|
690
|
+
ref = tref
|
|
691
|
+
else:
|
|
692
|
+
need = {b for _a, b in link[1]}
|
|
693
|
+
outer, self.qualify = self.qualify, False # does the nested where need qualified names?
|
|
694
|
+
if sub is not None and sub.get("where") is not None:
|
|
695
|
+
self.where(sub.get("where"), target, None)
|
|
696
|
+
ref = tref if self.qualify else None
|
|
697
|
+
self.qualify = outer
|
|
698
|
+
cols, rels, counts = self.columns(target, ref, sub, need=need)
|
|
699
|
+
from_ = tref
|
|
700
|
+
keys = [self.col(ref, b) for _a, b in link[1]]
|
|
701
|
+
parent = ", ".join(f"{model.name}.{a}" for a, _b in link[1])
|
|
702
|
+
lhs = keys[0] if len(keys) == 1 else "(" + ", ".join(keys) + ")"
|
|
703
|
+
key = f"{lhs} IN ({mark(parent + ' of the parent rows')})"
|
|
704
|
+
w = self.where(sub.get("where"), target, ref) if sub is not None and sub.get("where") is not None else ""
|
|
705
|
+
tail = self.tail(sub, target, ref) if sub is not None else ""
|
|
706
|
+
tail = re.sub(r" (?:LIMIT|OFFSET) (?:«[^»]*»|\S+)", "", tail) # take / skip are per parent row, not on this statement
|
|
707
|
+
count_joins = self.count_joins(target, ref or tref, counts) if counts else ""
|
|
708
|
+
if count_joins and ref is None:
|
|
709
|
+
self.lower(1, f"_count of {where_path} not shown")
|
|
710
|
+
count_joins = ""
|
|
711
|
+
sql = f"SELECT {', '.join(cols)} FROM {from_}{count_joins} WHERE {key}{' AND ' + w if w else ''}{tail}"
|
|
712
|
+
note = f"include {where_path}: one IN query per relation level"
|
|
713
|
+
if sub is not None and (sub.get("take") is not None or sub.get("skip") is not None):
|
|
714
|
+
note += " (take / skip apply per parent row; Prisma narrows the rows after this statement or with a window)"
|
|
715
|
+
self.extra_sites.append((sql, target.table, note))
|
|
716
|
+
if rels:
|
|
717
|
+
self.load(target, rels, depth + 1, where_path)
|
|
718
|
+
|
|
719
|
+
def count_joins(self, model: Model, ref: str, counts) -> str:
|
|
720
|
+
out = ""
|
|
721
|
+
for fld, _v in counts:
|
|
722
|
+
link = self.schema.link(model, fld)
|
|
723
|
+
target = self.schema.models[fld.type]
|
|
724
|
+
if link is None:
|
|
725
|
+
continue
|
|
726
|
+
alias = self.q(f"aggr_{fld.name}")
|
|
727
|
+
if link[0] == "m2m":
|
|
728
|
+
_, jt, own, _other, own_id, _tid = link
|
|
729
|
+
out += (f" LEFT JOIN (SELECT {self.q(own)}, COUNT(*) AS {self.q('_count')} FROM {self.q(jt)} GROUP BY {self.q(own)}) AS {alias}"
|
|
730
|
+
f" ON {self.col(alias, own)} = {self.col(ref, own_id)}")
|
|
731
|
+
else:
|
|
732
|
+
keys = ", ".join(self.q(b) for _a, b in link[1])
|
|
733
|
+
on = " AND ".join(f"{self.col(alias, b)} = {self.col(ref, a)}" for a, b in link[1])
|
|
734
|
+
out += f" LEFT JOIN (SELECT {keys}, COUNT(*) AS {self.q('_count')} FROM {self.table(target)} GROUP BY {keys}) AS {alias} ON {on}"
|
|
735
|
+
return out
|
|
736
|
+
|
|
737
|
+
def read(self, args, first: bool, unique: bool) -> str:
|
|
738
|
+
model = self.model
|
|
739
|
+
strategy = self.strategy(args)
|
|
740
|
+
|
|
741
|
+
def build(ref: str | None) -> str:
|
|
742
|
+
cols, relations, counts = self.columns(model, ref, args)
|
|
743
|
+
w = self.where(args.get("where"), model, ref) if args is not None and args.get("where") is not None else ""
|
|
744
|
+
w = self.spread_args(args, w)
|
|
745
|
+
cursor = args.get("cursor") if args is not None else None
|
|
746
|
+
if cursor is not None and not o.is_undefined(cursor):
|
|
747
|
+
cobj = self.obj(cursor)
|
|
748
|
+
cfields = [k for k in (cobj.keys() if cobj else []) if k in model.fields and not model.fields[k].relation]
|
|
749
|
+
if cfields:
|
|
750
|
+
w = (w + " AND " if w else "") + " AND ".join(
|
|
751
|
+
f"{self.col(ref, model.fields[k].column)} >= {o.value(cobj.get(k))}" for k in cfields)
|
|
752
|
+
self.notes.append("cursor pagination: the comparison follows the sort order")
|
|
753
|
+
else:
|
|
754
|
+
w = (w + " AND " if w else "") + mark("cursor: " + txt(cursor))
|
|
755
|
+
joins = ""
|
|
756
|
+
if (counts or (relations and strategy == "join")) and ref is None:
|
|
757
|
+
return "" # needs qualified names: built again below
|
|
758
|
+
if counts:
|
|
759
|
+
joins += self.count_joins(model, ref, counts)
|
|
760
|
+
cols = cols + [self.col(self.q(f"aggr_{fld.name}"), "_count") for fld, _ in counts]
|
|
761
|
+
if relations and strategy == "join":
|
|
762
|
+
joins += self.lateral(model, ref, relations, 1)
|
|
763
|
+
cols = cols + [f"{self.q(fld.name)}.*" for fld, _ in relations]
|
|
764
|
+
self.notes.append("relationJoins: relations are loaded by LATERAL joins in this statement")
|
|
765
|
+
elif relations:
|
|
766
|
+
self.load(model, relations, 1, model.name)
|
|
767
|
+
distinct = args.get("distinct") if args is not None else None
|
|
768
|
+
head = "SELECT "
|
|
769
|
+
if distinct is not None and not o.is_undefined(distinct):
|
|
770
|
+
names = [o.string_value(i) for i in (o.array_items(distinct) or [distinct])]
|
|
771
|
+
dcols = [self.col(ref, model.fields[n].column) for n in names if n and n in model.fields]
|
|
772
|
+
if self.schema.native_distinct and dcols and self.engine == "postgres":
|
|
773
|
+
head = f"SELECT DISTINCT ON ({', '.join(dcols)}) "
|
|
774
|
+
else:
|
|
775
|
+
self.notes.append("distinct is applied by Prisma in memory after this statement (no nativeDistinct)")
|
|
776
|
+
tail = self.tail(args, model, ref, first=first, unique=unique)
|
|
777
|
+
return f"{head}{', '.join(cols)} FROM {self.table(model)}{joins}{' WHERE ' + w if w else ''}{tail}"
|
|
778
|
+
|
|
779
|
+
return self._two_pass(build)
|
|
780
|
+
|
|
781
|
+
def _two_pass(self, build) -> str:
|
|
782
|
+
"""Unqualified column names when the statement reads one table; qualified when it has subqueries or joins."""
|
|
783
|
+
keep = (list(self.notes), self.level)
|
|
784
|
+
self.qualify, self.aliases, self.extra_sites = False, 0, []
|
|
785
|
+
sql = build(None)
|
|
786
|
+
if sql and not self.qualify:
|
|
787
|
+
return sql
|
|
788
|
+
self.notes, self.level = keep[0], keep[1]
|
|
789
|
+
self.aliases, self.extra_sites = 0, []
|
|
790
|
+
return build(self.table(self.model))
|
|
791
|
+
|
|
792
|
+
# -- writes ----------------------------------------------------------------------------
|
|
793
|
+
def assignments(self, node: Node | None, model: Model) -> tuple[list[tuple[str, str]], bool] | None:
|
|
794
|
+
"""[(column, value SQL)] of a `data` object and whether every part of it was read; None when it is not an
|
|
795
|
+
object literal here."""
|
|
796
|
+
obj = self.obj(node)
|
|
797
|
+
if obj is None:
|
|
798
|
+
return None
|
|
799
|
+
out: list[tuple[str, str]] = []
|
|
800
|
+
whole = True
|
|
801
|
+
if obj.maybe:
|
|
802
|
+
self.notes.append("columns set under a condition: " + ", ".join(dict.fromkeys(k for k, _v, _t in obj.maybe)))
|
|
803
|
+
for k, v in obj.entries + [(k, v) for k, v, _t in obj.maybe]:
|
|
804
|
+
fld = model.fields.get(k)
|
|
805
|
+
uv = unwrap(v)
|
|
806
|
+
if o.is_undefined(uv):
|
|
807
|
+
continue
|
|
808
|
+
if fld is None:
|
|
809
|
+
self.lower(1, f"`{k}` is not a field of {model.name}")
|
|
810
|
+
out.append((mark(k), mark_node(uv)))
|
|
811
|
+
continue
|
|
812
|
+
if fld.relation:
|
|
813
|
+
sub = self.obj(uv)
|
|
814
|
+
link = self.schema.link(model, fld)
|
|
815
|
+
conn = self.obj(sub.get("connect")) if sub is not None and sub.get("connect") is not None else None
|
|
816
|
+
target = self.schema.models[fld.type]
|
|
817
|
+
if conn is not None and link is not None and link[0] == "fk":
|
|
818
|
+
byref = {b: a for a, b in link[1]}
|
|
819
|
+
hit = [(byref[target.fields[ck].column], o.value(cv)) for ck, cv in conn.entries
|
|
820
|
+
if ck in target.fields and target.fields[ck].column in byref]
|
|
821
|
+
if len(hit) == len(link[1]):
|
|
822
|
+
out.extend(hit)
|
|
823
|
+
continue
|
|
824
|
+
for a, _b in link[1]:
|
|
825
|
+
out.append((a, mark(f"{fld.name} found by {', '.join(conn.keys())}")))
|
|
826
|
+
self.notes.append(f"connect {model.name}.{fld.name} by a non-key field: Prisma reads the {target.name} row first")
|
|
827
|
+
continue
|
|
828
|
+
self.lower(1, f"nested write on {model.name}.{fld.name}: its statements are not shown")
|
|
829
|
+
whole = False
|
|
830
|
+
continue
|
|
831
|
+
sub = self.obj(uv) if uv is not None and uv.type == "object" else None
|
|
832
|
+
col = fld.column
|
|
833
|
+
if sub is not None and len(sub.entries) == 1 and sub.entries[0][0] in ("increment", "decrement", "multiply", "divide", "set", "push"):
|
|
834
|
+
op, x = sub.entries[0]
|
|
835
|
+
qc = self.q(col)
|
|
836
|
+
expr = {"increment": f"{qc} + {o.value(x)}", "decrement": f"{qc} - {o.value(x)}", "multiply": f"{qc} * {o.value(x)}",
|
|
837
|
+
"divide": f"{qc} / {o.value(x)}", "set": o.value(x), "push": f"array_append({qc}, {o.value(x)})"}[op]
|
|
838
|
+
out.append((col, expr))
|
|
839
|
+
else:
|
|
840
|
+
out.append((col, o.value(uv)))
|
|
841
|
+
for e in obj.extra:
|
|
842
|
+
out.append((mark(e), mark(e)))
|
|
843
|
+
return out, whole
|
|
844
|
+
|
|
845
|
+
def returning(self, args, model: Model) -> str:
|
|
846
|
+
if self.engine == "mysql":
|
|
847
|
+
self.notes.append("MySQL has no RETURNING: Prisma reads the row back with a second statement")
|
|
848
|
+
return ""
|
|
849
|
+
cols, relations, counts = self.columns(model, None, args)
|
|
850
|
+
if relations and self.strategy(args) == "join":
|
|
851
|
+
ref = self.table(model)
|
|
852
|
+
rcols, _r, _c = self.columns(model, ref, args)
|
|
853
|
+
key = " AND ".join(f"{self.col(ref, model.fields[p].column)} = {mark('the written row')}" for p in model.pk if p in model.fields)
|
|
854
|
+
sql = (f"SELECT {', '.join(rcols + [self.q(f.name) + '.*' for f, _ in relations])} FROM {ref}"
|
|
855
|
+
f"{self.lateral(model, ref, relations, 1)}{' WHERE ' + key if key else ''}")
|
|
856
|
+
self.extra_sites.append((sql, model.table, "relationJoins: the written row is read back with its relations (LATERAL joins)"))
|
|
857
|
+
elif relations:
|
|
858
|
+
self.load(model, relations, 1, model.name)
|
|
859
|
+
return " RETURNING " + ", ".join(cols)
|
|
860
|
+
|
|
861
|
+
def insert(self, args, many: bool) -> str:
|
|
862
|
+
model = self.model
|
|
863
|
+
data = args.get("data") if args is not None else None
|
|
864
|
+
ud = unwrap(data)
|
|
865
|
+
rows = o.array_items(ud) if many else None
|
|
866
|
+
first = rows[0] if rows else ud
|
|
867
|
+
if many and rows is None and ud is not None and ud.type == "call_expression": # xs.map((x) => ({...}))
|
|
868
|
+
a = ud.child_by_field_name("arguments")
|
|
869
|
+
body = o.callback_body(a.named_children[0]) if a is not None and a.named_children else None
|
|
870
|
+
first = body if body is not None and body.type == "object" else None
|
|
871
|
+
got = self.assignments(first, model) if first is not None else None
|
|
872
|
+
if got is None or not got[0]:
|
|
873
|
+
sql = f"INSERT INTO {self.table(model)} ({mark('columns of ' + txt(ud))}) VALUES ({mark_node(ud)})"
|
|
874
|
+
else:
|
|
875
|
+
pairs = got[0]
|
|
876
|
+
sql = (f"INSERT INTO {self.table(model)} ({', '.join(self.q(c) for c, _ in pairs)}) "
|
|
877
|
+
f"VALUES ({', '.join(v for _, v in pairs)})")
|
|
878
|
+
if many:
|
|
879
|
+
self.notes.append("one statement inserts every row of the list")
|
|
880
|
+
skip = args.get("skipDuplicates") if args is not None else None
|
|
881
|
+
if skip is not None and txt(unwrap(skip)) != "false":
|
|
882
|
+
sql += " ON CONFLICT DO NOTHING" if self.engine != "mysql" else ""
|
|
883
|
+
if not many or self.op == "createManyAndReturn":
|
|
884
|
+
sql += self.returning(args, model)
|
|
885
|
+
return sql
|
|
886
|
+
|
|
887
|
+
def set_clause(self, node: Node | None) -> str:
|
|
888
|
+
got = self.assignments(node, self.model)
|
|
889
|
+
if got is None:
|
|
890
|
+
m = mark_node(unwrap(node))
|
|
891
|
+
return f"{mark('columns of ' + txt(unwrap(node)))} = {m}"
|
|
892
|
+
if not got[0]:
|
|
893
|
+
return ""
|
|
894
|
+
return ", ".join(f"{self.q(c)} = {v}" for c, v in got[0])
|
|
895
|
+
|
|
896
|
+
def write_where(self, args) -> str:
|
|
897
|
+
def build(ref):
|
|
898
|
+
return self.where(args.get("where"), self.model, ref) if args is not None and args.get("where") is not None else ""
|
|
899
|
+
self.qualify = False
|
|
900
|
+
w = build(None)
|
|
901
|
+
if self.qualify:
|
|
902
|
+
self.aliases = 0
|
|
903
|
+
w = build(self.table(self.model))
|
|
904
|
+
return self.spread_args(args, w)
|
|
905
|
+
|
|
906
|
+
def spread_args(self, args, w: str) -> str:
|
|
907
|
+
"""`findMany({ take, ...(last ? { cursor, skip: 1 } : {}) })`: parts of the arguments only known at run time.
|
|
908
|
+
They are kept, as run-time parts of the filter, so the statement does not look more fixed than it is."""
|
|
909
|
+
extra = (list(args.extra) + [t for _k, _v, t in args.maybe]) if args is not None else []
|
|
910
|
+
if not extra:
|
|
911
|
+
return w
|
|
912
|
+
self.notes.append("arguments spread in at run time may add filters, ordering or paging: " + ", ".join(mark(e) for e in extra))
|
|
913
|
+
return " AND ".join(([w] if w else []) + [mark(e) for e in extra])
|
|
914
|
+
|
|
915
|
+
# -- the call --------------------------------------------------------------------------
|
|
916
|
+
def run(self) -> list:
|
|
917
|
+
op, model = self.op, self.model
|
|
918
|
+
arg = unwrap(self.args[0]) if self.args else None
|
|
919
|
+
args = None
|
|
920
|
+
tbl = self.table(model)
|
|
921
|
+
if arg is not None:
|
|
922
|
+
args = self.obj(arg)
|
|
923
|
+
if args is None:
|
|
924
|
+
# the whole argument object comes from somewhere else: the table and the operation are still known
|
|
925
|
+
m = mark_node(arg)
|
|
926
|
+
self.lower(1, "the arguments are built elsewhere: only the table and the operation are known")
|
|
927
|
+
cols = ", ".join(self.q(f.column) for f in model.scalars())
|
|
928
|
+
sql = {
|
|
929
|
+
"count": f"SELECT COUNT(*) FROM {tbl} {m}",
|
|
930
|
+
"aggregate": f"SELECT {mark('aggregates')} FROM {tbl} {m}",
|
|
931
|
+
"groupBy": f"SELECT {mark('by')} FROM {tbl} {m}",
|
|
932
|
+
"create": f"INSERT INTO {tbl} ({mark('columns')}) VALUES ({m})",
|
|
933
|
+
"createMany": f"INSERT INTO {tbl} ({mark('columns')}) VALUES ({m})",
|
|
934
|
+
"createManyAndReturn": f"INSERT INTO {tbl} ({mark('columns')}) VALUES ({m})",
|
|
935
|
+
"update": f"UPDATE {tbl} SET {mark('columns')} = {m} WHERE {mark('where')}",
|
|
936
|
+
"updateMany": f"UPDATE {tbl} SET {mark('columns')} = {m} WHERE {mark('where')}",
|
|
937
|
+
"updateManyAndReturn": f"UPDATE {tbl} SET {mark('columns')} = {m} WHERE {mark('where')}",
|
|
938
|
+
"upsert": f"INSERT INTO {tbl} ({mark('columns')}) VALUES ({m}) ON CONFLICT ({mark('unique key')}) DO UPDATE SET {mark('columns')} = {m}",
|
|
939
|
+
"delete": f"DELETE FROM {tbl} WHERE {m}",
|
|
940
|
+
"deleteMany": f"DELETE FROM {tbl} WHERE {m}",
|
|
941
|
+
}.get(op, f"SELECT {cols} FROM {tbl} {m}")
|
|
942
|
+
if self.engine == "mysql" and op == "upsert":
|
|
943
|
+
sql = f"INSERT INTO {tbl} ({mark('columns')}) VALUES ({m}) ON DUPLICATE KEY UPDATE {mark('columns')} = {m}"
|
|
944
|
+
return [self.site(sql, model.table, arg)]
|
|
945
|
+
if op in READS:
|
|
946
|
+
sql = self.read(args, first=op.startswith("findFirst"), unique=op.startswith("findUnique"))
|
|
947
|
+
elif op == "count":
|
|
948
|
+
w = self.write_where(args)
|
|
949
|
+
sql = f"SELECT COUNT(*) FROM {tbl}{' WHERE ' + w if w else ''}"
|
|
950
|
+
if args is not None and (args.get("take") is not None or args.get("skip") is not None):
|
|
951
|
+
inner = f"SELECT 1 FROM {tbl}{' WHERE ' + w if w else ''}{self.tail(args, model, None)}"
|
|
952
|
+
sql = f"SELECT COUNT(*) FROM ({inner}) AS {self.q('sub')}"
|
|
953
|
+
elif op == "aggregate":
|
|
954
|
+
sql = f"SELECT {', '.join(self.aggregates(args) or ['COUNT(*)'])} FROM {tbl}"
|
|
955
|
+
w = self.write_where(args)
|
|
956
|
+
sql += (" WHERE " + w if w else "") + self.tail(args, model, None)
|
|
957
|
+
elif op == "groupBy":
|
|
958
|
+
by = args.get("by") if args is not None else None
|
|
959
|
+
names = [o.string_value(i) for i in (o.array_items(by) or ([by] if by is not None else []))]
|
|
960
|
+
bcols = [self.q(model.fields[n].column) if n and n in model.fields and not model.fields[n].relation else mark_node(by)
|
|
961
|
+
for n in names] or [mark("by")]
|
|
962
|
+
bcols = list(dict.fromkeys(bcols))
|
|
963
|
+
w = self.write_where(args)
|
|
964
|
+
sql = f"SELECT {', '.join(bcols + self.aggregates(args))} FROM {tbl}{' WHERE ' + w if w else ''} GROUP BY {', '.join(bcols)}"
|
|
965
|
+
having = args.get("having") if args is not None else None
|
|
966
|
+
if having is not None and not o.is_undefined(having):
|
|
967
|
+
sql += f" HAVING {mark('having: ' + txt(having))}"
|
|
968
|
+
sql += self.tail(args, model, None)
|
|
969
|
+
elif op in ("create", "createMany", "createManyAndReturn"):
|
|
970
|
+
sql = self.insert(args, many=op != "create")
|
|
971
|
+
elif op in ("update", "updateMany", "updateManyAndReturn"):
|
|
972
|
+
sets = self.set_clause(args.get("data") if args is not None else None)
|
|
973
|
+
w = self.write_where(args)
|
|
974
|
+
if not sets:
|
|
975
|
+
self.lower(1, "no column of the row is set here (nested writes only)")
|
|
976
|
+
sets = f"{mark('nested writes only')} = {mark('nested writes only')}"
|
|
977
|
+
sql = f"UPDATE {tbl} SET {sets}{' WHERE ' + w if w else ''}"
|
|
978
|
+
if op != "updateMany":
|
|
979
|
+
sql += self.returning(args, model)
|
|
980
|
+
elif op == "upsert":
|
|
981
|
+
w_obj = self.obj(args.get("where")) if args is not None and args.get("where") is not None else None
|
|
982
|
+
keys: list[str] = []
|
|
983
|
+
for k in (w_obj.keys() if w_obj else []):
|
|
984
|
+
if k in model.compound:
|
|
985
|
+
keys += [model.fields[c].column for c in model.compound[k] if c in model.fields]
|
|
986
|
+
elif k in model.fields and not model.fields[k].relation:
|
|
987
|
+
keys.append(model.fields[k].column)
|
|
988
|
+
got = self.assignments(args.get("create") if args is not None else None, model)
|
|
989
|
+
if got is None or not got[0]:
|
|
990
|
+
ins = f"INSERT INTO {tbl} ({mark('columns of create')}) VALUES ({mark_node(args.get('create') if args is not None else None)})"
|
|
991
|
+
else:
|
|
992
|
+
ins = f"INSERT INTO {tbl} ({', '.join(self.q(c) for c, _ in got[0])}) VALUES ({', '.join(v for _, v in got[0])})"
|
|
993
|
+
sets = self.set_clause(args.get("update") if args is not None else None)
|
|
994
|
+
conflict = ", ".join(self.q(k) for k in keys) or mark("unique key of where")
|
|
995
|
+
if self.engine == "mysql":
|
|
996
|
+
sql = ins + (f" ON DUPLICATE KEY UPDATE {sets}" if sets else "")
|
|
997
|
+
else:
|
|
998
|
+
sql = ins + f" ON CONFLICT ({conflict}) " + (f"DO UPDATE SET {sets}" if sets else "DO NOTHING")
|
|
999
|
+
self.lower(1, "written as a native upsert; when Prisma cannot use one it runs SELECT by the unique key, then INSERT or UPDATE")
|
|
1000
|
+
sql += self.returning(args, model)
|
|
1001
|
+
elif op in ("delete", "deleteMany"):
|
|
1002
|
+
w = self.write_where(args)
|
|
1003
|
+
sql = f"DELETE FROM {tbl}{' WHERE ' + w if w else ''}"
|
|
1004
|
+
if op == "delete":
|
|
1005
|
+
sql += self.returning(args, model)
|
|
1006
|
+
else:
|
|
1007
|
+
return []
|
|
1008
|
+
if not sql:
|
|
1009
|
+
return []
|
|
1010
|
+
sites = [self.site(sql, model.table, arg)]
|
|
1011
|
+
for extra_sql, table, note in self.extra_sites:
|
|
1012
|
+
sites.append(self.site(extra_sql, table, arg, extra=note))
|
|
1013
|
+
return sites
|
|
1014
|
+
|
|
1015
|
+
def aggregates(self, args) -> list[str]:
|
|
1016
|
+
out = []
|
|
1017
|
+
if args is None:
|
|
1018
|
+
return out
|
|
1019
|
+
for k, v in args.entries:
|
|
1020
|
+
uv = unwrap(v)
|
|
1021
|
+
if k == "_count":
|
|
1022
|
+
sub = self.obj(uv)
|
|
1023
|
+
if sub is None:
|
|
1024
|
+
out.append("COUNT(*)")
|
|
1025
|
+
else:
|
|
1026
|
+
for ck, _cv in sub.entries:
|
|
1027
|
+
fld = self.model.fields.get(ck)
|
|
1028
|
+
out.append("COUNT(*)" if ck == "_all" or fld is None else f"COUNT({self.q(fld.column)})")
|
|
1029
|
+
elif k in AGGREGATES:
|
|
1030
|
+
sub = self.obj(uv)
|
|
1031
|
+
if sub is None:
|
|
1032
|
+
out.append(f"{AGGREGATES[k]}({mark_node(uv)})")
|
|
1033
|
+
else:
|
|
1034
|
+
for ck, _cv in sub.entries:
|
|
1035
|
+
fld = self.model.fields.get(ck)
|
|
1036
|
+
if fld is not None:
|
|
1037
|
+
out.append(f"{AGGREGATES[k]}({self.q(fld.column)})")
|
|
1038
|
+
return out
|
|
1039
|
+
|
|
1040
|
+
def site(self, sql: str, table: str, arg: Node | None, extra: str | None = None):
|
|
1041
|
+
notes = ([extra] if extra else []) + ([] if extra else self.notes)
|
|
1042
|
+
if extra and self.level < 2:
|
|
1043
|
+
notes += [n for n in self.notes if n.startswith("receiver")]
|
|
1044
|
+
return o.make_site(self.f, self.call, self.sink, self.engine, sql, arg, library=NAME, table=table,
|
|
1045
|
+
operation=self.op, confidence=o.CONFIDENCE[self.level], notes=notes)
|