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,1067 @@
|
|
|
1
|
+
"""TypeORM repository and entity-manager calls, and simple `createQueryBuilder` chains, as SQL sites.
|
|
2
|
+
|
|
3
|
+
Entities are read from their decorators: `@Entity` (table, schema), the column decorators (`name`), the relation
|
|
4
|
+
decorators with `@JoinColumn` / `@JoinTable`, `@DeleteDateColumn` (soft delete), and columns inherited from a base
|
|
5
|
+
class. A call is tied to its entity through the repository's type (`Repository<User>` on a constructor
|
|
6
|
+
parameter, a field, a function parameter or a variable), `getRepository(User)`, `manager.find(User, ...)` or the
|
|
7
|
+
entity class itself (`User.find`).
|
|
8
|
+
|
|
9
|
+
`find*` with `relations` is written as TypeORM runs it by default: one statement with LEFT JOINs. `save`,
|
|
10
|
+
`remove` and `softRemove` decide between statements at run time (they read the row first) and are counted, not
|
|
11
|
+
written.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
|
|
19
|
+
from tree_sitter import Node, Parser
|
|
20
|
+
|
|
21
|
+
from . import orm_ts as o
|
|
22
|
+
from .orm_ts import as_object, mark, mark_node, txt, unwrap
|
|
23
|
+
from .orm_ts_schema import climb, spine
|
|
24
|
+
|
|
25
|
+
NAME = "typeorm"
|
|
26
|
+
FINDS = {"find", "findBy", "findOne", "findOneBy", "findOneOrFail", "findOneByOrFail", "findAndCount", "findAndCountBy",
|
|
27
|
+
"count", "countBy", "exists", "exist", "existsBy", "sum", "average", "minimum", "maximum"}
|
|
28
|
+
WRITES = {"insert", "update", "delete", "softDelete", "restore", "upsert", "increment", "decrement"}
|
|
29
|
+
RUN_TIME = {"save": "save: TypeORM reads the row, then inserts or updates (decided at run time)",
|
|
30
|
+
"remove": "remove: the entity object decides the DELETE at run time",
|
|
31
|
+
"softRemove": "softRemove: the entity object decides the UPDATE at run time",
|
|
32
|
+
"recover": "recover: the entity object decides the UPDATE at run time"}
|
|
33
|
+
METHODS = FINDS | WRITES | set(RUN_TIME)
|
|
34
|
+
BY = {"findBy", "findOneBy", "findOneByOrFail", "findAndCountBy", "countBy", "existsBy"}
|
|
35
|
+
COLUMN_DECORATORS = {"Column", "PrimaryColumn", "PrimaryGeneratedColumn", "CreateDateColumn", "UpdateDateColumn",
|
|
36
|
+
"DeleteDateColumn", "VersionColumn", "ObjectIdColumn", "ViewColumn"}
|
|
37
|
+
RELATION_DECORATORS = {"ManyToOne", "OneToOne", "OneToMany", "ManyToMany"}
|
|
38
|
+
RECEIVER = re.compile(r"[rR]epository|[rR]epo\b|[mM]anager|\bem\b|queryRunner|[dD]ataSource", re.I)
|
|
39
|
+
PRE = re.compile(rb"\.\s*(?:find|findBy|findOne|findOneBy|findOneOrFail|findOneByOrFail|findAndCount|findAndCountBy|count|countBy|"
|
|
40
|
+
rb"exists|exist|existsBy|insert|update|delete|softDelete|restore|upsert|increment|decrement|save|remove|"
|
|
41
|
+
rb"softRemove|createQueryBuilder)\s*[(<]")
|
|
42
|
+
REPO_TYPE = re.compile(r"\b(\w*Repository)\s*<\s*([A-Za-z_][\w$]*)")
|
|
43
|
+
PLAIN_REPOS = {"Repository", "TreeRepository", "MongoRepository"}
|
|
44
|
+
OPERATORS = {"LessThan": "<", "LessThanOrEqual": "<=", "MoreThan": ">", "MoreThanOrEqual": ">=", "Equal": "="}
|
|
45
|
+
QB_TERMINAL = {"getMany", "getOne", "getOneOrFail", "getRawMany", "getRawOne", "getManyAndCount", "getCount", "execute",
|
|
46
|
+
"getExists", "stream", "getRawAndEntities", "getSql", "getQuery", "getQueryAndParameters"}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _snake(name: str) -> str:
|
|
50
|
+
return re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", name).lower()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Entity:
|
|
54
|
+
def __init__(self, cls: str, rel: str):
|
|
55
|
+
self.cls, self.rel = cls, rel
|
|
56
|
+
self.table = ""
|
|
57
|
+
self.schema = ""
|
|
58
|
+
self.is_entity = False
|
|
59
|
+
self.base = ""
|
|
60
|
+
self.columns: dict[str, str] = {} # property -> column
|
|
61
|
+
self.pk: list[str] = []
|
|
62
|
+
self.deleted_at = "" # property of the @DeleteDateColumn
|
|
63
|
+
self.relations: dict[str, dict] = {} # property -> {kind, target, join_column, inverse, join_table}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def read_entities(rel: str, src: bytes) -> list[Entity]:
|
|
67
|
+
from .typescript import call_args, language_for, object_pairs
|
|
68
|
+
|
|
69
|
+
def dec_parts(dec: Node) -> tuple[str, list[Node], dict[str, Node]]:
|
|
70
|
+
inner = dec.named_children[0] if dec.named_children else None
|
|
71
|
+
if inner is None:
|
|
72
|
+
return "", [], {}
|
|
73
|
+
if inner.type != "call_expression":
|
|
74
|
+
return txt(inner), [], {}
|
|
75
|
+
args = [unwrap(a) for a in call_args(inner)]
|
|
76
|
+
kw: dict[str, Node] = {}
|
|
77
|
+
for a in args:
|
|
78
|
+
if a is not None and a.type == "object":
|
|
79
|
+
kw.update(object_pairs(a))
|
|
80
|
+
return txt(inner.child_by_field_name("function")), [a for a in args if a is not None], kw
|
|
81
|
+
|
|
82
|
+
def decorators(node: Node) -> list[Node]:
|
|
83
|
+
out = [c for c in node.children if c.type == "decorator"]
|
|
84
|
+
prev = node.prev_named_sibling
|
|
85
|
+
while prev is not None and prev.type in ("decorator", "comment"):
|
|
86
|
+
if prev.type == "decorator":
|
|
87
|
+
out.append(prev)
|
|
88
|
+
prev = prev.prev_named_sibling
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
def target_of(args: list[Node]) -> str:
|
|
92
|
+
"""`() => User`, `(type) => User`, `"User"`, `User`."""
|
|
93
|
+
if not args:
|
|
94
|
+
return ""
|
|
95
|
+
a = args[0]
|
|
96
|
+
s = o.string_value(a)
|
|
97
|
+
if s is not None:
|
|
98
|
+
return s
|
|
99
|
+
body = o.callback_body(a)
|
|
100
|
+
return txt(body if body is not None else a).split(".")[-1].strip()
|
|
101
|
+
|
|
102
|
+
tree = Parser(language_for(rel)).parse(src)
|
|
103
|
+
out: list[Entity] = []
|
|
104
|
+
stack = [tree.root_node]
|
|
105
|
+
while stack:
|
|
106
|
+
node = stack.pop()
|
|
107
|
+
if node.type not in ("class_declaration", "abstract_class_declaration"):
|
|
108
|
+
if node.type in ("program", "export_statement", "statement_block"):
|
|
109
|
+
stack.extend(node.children)
|
|
110
|
+
continue
|
|
111
|
+
ent = Entity(txt(node.child_by_field_name("name")), rel)
|
|
112
|
+
decs = [c for c in node.children if c.type == "decorator"]
|
|
113
|
+
if node.parent is not None and node.parent.type == "export_statement":
|
|
114
|
+
decs += [c for c in node.parent.children if c.type == "decorator"]
|
|
115
|
+
for d in decs:
|
|
116
|
+
name, args, kw = dec_parts(d)
|
|
117
|
+
if name in ("Entity", "ViewEntity", "ChildEntity"):
|
|
118
|
+
ent.is_entity = True
|
|
119
|
+
tname = o.string_value(args[0]) if args and args[0].type in ("string", "template_string") else o.string_value(kw.get("name"))
|
|
120
|
+
ent.table = tname or ""
|
|
121
|
+
ent.schema = o.string_value(kw.get("schema")) or ""
|
|
122
|
+
for c in node.children:
|
|
123
|
+
if c.type == "class_heritage":
|
|
124
|
+
m = re.search(r"extends\s+([A-Za-z_][\w$]*)", txt(c))
|
|
125
|
+
ent.base = m.group(1) if m else ""
|
|
126
|
+
body = node.child_by_field_name("body")
|
|
127
|
+
for member in (body.named_children if body is not None else ()):
|
|
128
|
+
if member.type != "public_field_definition":
|
|
129
|
+
continue
|
|
130
|
+
prop = txt(member.child_by_field_name("name"))
|
|
131
|
+
relation, join_column, join_table = None, None, None
|
|
132
|
+
for d in decorators(member):
|
|
133
|
+
name, dargs, dkw = dec_parts(d)
|
|
134
|
+
if name in COLUMN_DECORATORS:
|
|
135
|
+
ent.columns[prop] = o.string_value(dkw.get("name")) or prop
|
|
136
|
+
if name.startswith("Primary") or txt(dkw.get("primary")) == "true":
|
|
137
|
+
ent.pk.append(prop)
|
|
138
|
+
if name == "DeleteDateColumn":
|
|
139
|
+
ent.deleted_at = prop
|
|
140
|
+
elif name in RELATION_DECORATORS:
|
|
141
|
+
inverse = ""
|
|
142
|
+
for a in dargs[1:]:
|
|
143
|
+
b = o.callback_body(a)
|
|
144
|
+
if b is not None and b.type == "member_expression":
|
|
145
|
+
inverse = txt(b.child_by_field_name("property"))
|
|
146
|
+
relation = {"kind": name, "target": target_of(dargs), "inverse": inverse}
|
|
147
|
+
elif name == "JoinColumn":
|
|
148
|
+
join_column = {"name": o.string_value(dkw.get("name")) or "",
|
|
149
|
+
"referenced": o.string_value(dkw.get("referencedColumnName")) or ""}
|
|
150
|
+
elif name == "JoinTable":
|
|
151
|
+
jc = as_object(None, dkw.get("joinColumn"), None) if dkw.get("joinColumn") is not None else None
|
|
152
|
+
ic = as_object(None, dkw.get("inverseJoinColumn"), None) if dkw.get("inverseJoinColumn") is not None else None
|
|
153
|
+
join_table = {"name": o.string_value(dkw.get("name")) or "",
|
|
154
|
+
"own": o.string_value(jc.get("name")) if jc and jc.get("name") is not None else "",
|
|
155
|
+
"other": o.string_value(ic.get("name")) if ic and ic.get("name") is not None else ""}
|
|
156
|
+
if relation is not None:
|
|
157
|
+
relation["join_column"] = join_column
|
|
158
|
+
relation["join_table"] = join_table
|
|
159
|
+
ent.relations[prop] = relation
|
|
160
|
+
if ent.is_entity or ent.columns or ent.relations:
|
|
161
|
+
out.append(ent)
|
|
162
|
+
return out
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class Library:
|
|
166
|
+
name = NAME
|
|
167
|
+
|
|
168
|
+
def __init__(self, ctx, root, files, stats):
|
|
169
|
+
self.ctx, self.stats = ctx, stats
|
|
170
|
+
self.active = True
|
|
171
|
+
self.by_class: dict[str, list[Entity]] = {}
|
|
172
|
+
self._deps_ok: dict[int, bool] = {}
|
|
173
|
+
|
|
174
|
+
def wants(self, rel: str, src: bytes, deps) -> bool:
|
|
175
|
+
if b"@Entity(" in src or b"Column(" in src and b"typeorm" in src:
|
|
176
|
+
try:
|
|
177
|
+
for e in read_entities(rel, src):
|
|
178
|
+
self.by_class.setdefault(e.cls, []).append(e)
|
|
179
|
+
except Exception:
|
|
180
|
+
pass
|
|
181
|
+
if not ("typeorm" in deps or "@nestjs/typeorm" in deps or b"typeorm" in src):
|
|
182
|
+
return False
|
|
183
|
+
return bool(PRE.search(src))
|
|
184
|
+
|
|
185
|
+
def prepare(self, wanted) -> None:
|
|
186
|
+
# columns and relations inherited from base classes
|
|
187
|
+
def fill(e: Entity, seen: set) -> None:
|
|
188
|
+
if not e.base or e.cls in seen:
|
|
189
|
+
return
|
|
190
|
+
seen.add(e.cls)
|
|
191
|
+
for base in self.by_class.get(e.base, [])[:1]:
|
|
192
|
+
fill(base, seen)
|
|
193
|
+
e.columns = {**base.columns, **e.columns}
|
|
194
|
+
e.relations = {**base.relations, **e.relations}
|
|
195
|
+
e.pk = e.pk or list(base.pk)
|
|
196
|
+
e.deleted_at = e.deleted_at or base.deleted_at
|
|
197
|
+
for ents in self.by_class.values():
|
|
198
|
+
for e in ents:
|
|
199
|
+
fill(e, set())
|
|
200
|
+
for ents in self.by_class.values():
|
|
201
|
+
for e in ents:
|
|
202
|
+
if e.is_entity and not e.table:
|
|
203
|
+
e.table = _snake(e.cls)
|
|
204
|
+
|
|
205
|
+
def entity(self, name: str, rel: str) -> Entity | None:
|
|
206
|
+
cands = [e for e in self.by_class.get(name, []) if e.is_entity]
|
|
207
|
+
if len(cands) == 1:
|
|
208
|
+
return cands[0]
|
|
209
|
+
if cands:
|
|
210
|
+
d = os.path.dirname(rel)
|
|
211
|
+
near = [e for e in cands if os.path.dirname(e.rel) == d]
|
|
212
|
+
return near[0] if len(near) == 1 else None
|
|
213
|
+
return None
|
|
214
|
+
|
|
215
|
+
# -- which entity a receiver stands for --------------------------------------------------
|
|
216
|
+
def entity_name(self, f, recv: Node | None, call: Node, depth: int = 0) -> str | None:
|
|
217
|
+
recv = unwrap(recv)
|
|
218
|
+
if recv is None or depth > 4:
|
|
219
|
+
return None
|
|
220
|
+
if recv.type == "call_expression": # x.getRepository(User) / getRepository(User) / x.withRepository(...)
|
|
221
|
+
fn = unwrap(recv.child_by_field_name("function"))
|
|
222
|
+
name = txt(fn.child_by_field_name("property")) if fn is not None and fn.type == "member_expression" else txt(fn)
|
|
223
|
+
args = recv.child_by_field_name("arguments")
|
|
224
|
+
first = unwrap(args.named_children[0]) if args is not None and args.type == "arguments" and args.named_children else None
|
|
225
|
+
if name in ("getRepository", "getTreeRepository", "getMongoRepository", "getCustomRepository") and first is not None:
|
|
226
|
+
return txt(first) if first.type == "identifier" else None
|
|
227
|
+
if name == "extend" and fn is not None and fn.type == "member_expression":
|
|
228
|
+
return self.entity_name(f, fn.child_by_field_name("object"), call, depth + 1)
|
|
229
|
+
return None
|
|
230
|
+
if recv.type == "member_expression" and txt(recv.child_by_field_name("object")) == "this":
|
|
231
|
+
prop = txt(recv.child_by_field_name("property"))
|
|
232
|
+
cls = f._enclosing(call, ("class_declaration", "class", "abstract_class_declaration"))
|
|
233
|
+
if cls is None:
|
|
234
|
+
return None
|
|
235
|
+
body = cls.child_by_field_name("body")
|
|
236
|
+
for member in (body.named_children if body is not None else ()):
|
|
237
|
+
if member.type == "method_definition" and txt(member.child_by_field_name("name")) == "constructor":
|
|
238
|
+
params = member.child_by_field_name("parameters")
|
|
239
|
+
for p in (params.named_children if params is not None else ()):
|
|
240
|
+
pat = p.child_by_field_name("pattern")
|
|
241
|
+
if pat is not None and txt(pat) == prop:
|
|
242
|
+
return self._typed(txt(p.child_by_field_name("type")))
|
|
243
|
+
elif member.type == "public_field_definition" and txt(member.child_by_field_name("name")) == prop:
|
|
244
|
+
got = self._typed(txt(member.child_by_field_name("type")))
|
|
245
|
+
if got:
|
|
246
|
+
return got
|
|
247
|
+
value = member.child_by_field_name("value")
|
|
248
|
+
return self.entity_name(f, value, call, depth + 1) if value is not None else None
|
|
249
|
+
return None
|
|
250
|
+
if recv.type == "identifier":
|
|
251
|
+
name = txt(recv)
|
|
252
|
+
if self.by_class.get(name) and any(e.is_entity for e in self.by_class[name]):
|
|
253
|
+
return name # active record: User.find(...)
|
|
254
|
+
for func in f._scopes(call):
|
|
255
|
+
params = func.child_by_field_name("parameters")
|
|
256
|
+
for p in (params.named_children if params is not None else ()):
|
|
257
|
+
pat = p.child_by_field_name("pattern")
|
|
258
|
+
if pat is not None and txt(pat) == name:
|
|
259
|
+
return self._typed(txt(p.child_by_field_name("type")))
|
|
260
|
+
try:
|
|
261
|
+
decl = f._decl(name, call)
|
|
262
|
+
except Exception:
|
|
263
|
+
decl = None
|
|
264
|
+
if decl is not None and decl[0].type == "variable_declarator":
|
|
265
|
+
got = self._typed(txt(decl[0].child_by_field_name("type")))
|
|
266
|
+
if got:
|
|
267
|
+
return got
|
|
268
|
+
return self.entity_name(f, decl[0].child_by_field_name("value"), call, depth + 1)
|
|
269
|
+
return None
|
|
270
|
+
|
|
271
|
+
def _typed(self, type_text: str) -> str | None:
|
|
272
|
+
"""The entity of `Repository<User>`; a project's own `XRepository<User>` wrapper is remembered as one."""
|
|
273
|
+
m = REPO_TYPE.search(type_text)
|
|
274
|
+
if not m:
|
|
275
|
+
return None
|
|
276
|
+
if m.group(1) not in PLAIN_REPOS:
|
|
277
|
+
self.wrapper = m.group(1)
|
|
278
|
+
return m.group(2)
|
|
279
|
+
|
|
280
|
+
def sites(self, f) -> list:
|
|
281
|
+
out = []
|
|
282
|
+
qb_roots = []
|
|
283
|
+
for call in f.calls:
|
|
284
|
+
fn = unwrap(call.child_by_field_name("function"))
|
|
285
|
+
if fn is None or fn.type != "member_expression":
|
|
286
|
+
continue
|
|
287
|
+
method = txt(fn.child_by_field_name("property"))
|
|
288
|
+
args_node = call.child_by_field_name("arguments")
|
|
289
|
+
if args_node is None or args_node.type != "arguments":
|
|
290
|
+
continue
|
|
291
|
+
if method == "createQueryBuilder":
|
|
292
|
+
qb_roots.append(call)
|
|
293
|
+
continue
|
|
294
|
+
if method not in METHODS:
|
|
295
|
+
continue
|
|
296
|
+
recv = unwrap(fn.child_by_field_name("object"))
|
|
297
|
+
recv_text = txt(recv)
|
|
298
|
+
if "createQueryBuilder" in recv_text and any(s[0] == "createQueryBuilder" for s in spine(recv)[1]):
|
|
299
|
+
continue # .update() / .delete() / .insert() of a query builder: read with its chain below
|
|
300
|
+
args = [a for a in args_node.named_children if a.type != "comment"]
|
|
301
|
+
self.wrapper = ""
|
|
302
|
+
ent_name = self.entity_name(f, recv, call)
|
|
303
|
+
wrapper = self.wrapper
|
|
304
|
+
manager = False
|
|
305
|
+
if ent_name is None and args and unwrap(args[0]) is not None and unwrap(args[0]).type == "identifier" \
|
|
306
|
+
and self.by_class.get(txt(unwrap(args[0]))) and re.search(r"[mM]anager|\bem\b|queryRunner|[dD]ataSource|\btx\b|trx", recv_text):
|
|
307
|
+
ent_name, args, manager = txt(unwrap(args[0])), args[1:], True # manager.find(User, {...})
|
|
308
|
+
if ent_name is None and not RECEIVER.search(recv_text.split("(")[0][-60:]):
|
|
309
|
+
continue # not a repository by anything that can be seen: not counted
|
|
310
|
+
self.stats.see(NAME, f.test)
|
|
311
|
+
line = call.start_point[0] + 1
|
|
312
|
+
if method in RUN_TIME:
|
|
313
|
+
self.stats.miss(NAME, f.test, RUN_TIME[method], f.rel, line)
|
|
314
|
+
continue
|
|
315
|
+
if ent_name is None:
|
|
316
|
+
self.stats.miss(NAME, f.test, "the repository's entity type is not visible here", f.rel, line)
|
|
317
|
+
continue
|
|
318
|
+
ent = self.entity(ent_name, f.rel)
|
|
319
|
+
if ent is None:
|
|
320
|
+
reason = "entity is not a static @Entity (tables built at run time)" if not self.by_class.get(ent_name) \
|
|
321
|
+
else "entity name is defined more than once"
|
|
322
|
+
self.stats.miss(NAME, f.test, reason, f.rel, line)
|
|
323
|
+
continue
|
|
324
|
+
try:
|
|
325
|
+
made = Call(self, f, call, ent, method, args, txt(fn), wrapper).run()
|
|
326
|
+
except Exception as e:
|
|
327
|
+
if os.environ.get("CODECOP_ORM_DEBUG"):
|
|
328
|
+
raise
|
|
329
|
+
self.stats.miss(NAME, f.test, f"internal error ({type(e).__name__})", f.rel, line)
|
|
330
|
+
continue
|
|
331
|
+
if not made:
|
|
332
|
+
self.stats.miss(NAME, f.test, "arguments could not be read", f.rel, line)
|
|
333
|
+
continue
|
|
334
|
+
self.stats.ok(NAME, f.test, len(made))
|
|
335
|
+
out.extend(made)
|
|
336
|
+
for call in qb_roots:
|
|
337
|
+
self.stats.see(NAME, f.test)
|
|
338
|
+
line = call.start_point[0] + 1
|
|
339
|
+
try:
|
|
340
|
+
site = Builder(self, f, call).run()
|
|
341
|
+
except Skip as e:
|
|
342
|
+
self.stats.miss(NAME, f.test, str(e), f.rel, line)
|
|
343
|
+
continue
|
|
344
|
+
except Exception as e:
|
|
345
|
+
if os.environ.get("CODECOP_ORM_DEBUG"):
|
|
346
|
+
raise
|
|
347
|
+
self.stats.miss(NAME, f.test, f"internal error ({type(e).__name__})", f.rel, line)
|
|
348
|
+
continue
|
|
349
|
+
self.stats.ok(NAME, f.test, 1)
|
|
350
|
+
out.append(site)
|
|
351
|
+
return out
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class Skip(Exception):
|
|
355
|
+
pass
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
class Base:
|
|
359
|
+
"""What repository calls and query builders share: names, where objects."""
|
|
360
|
+
|
|
361
|
+
lib: Library
|
|
362
|
+
f: object
|
|
363
|
+
engine: str
|
|
364
|
+
notes: list[str]
|
|
365
|
+
level: int
|
|
366
|
+
|
|
367
|
+
def q(self, name: str) -> str:
|
|
368
|
+
return o.quote(self.engine, name)
|
|
369
|
+
|
|
370
|
+
def table(self, ent: Entity) -> str:
|
|
371
|
+
return (self.q(ent.schema) + "." if ent.schema and ent.schema != "public" else "") + self.q(ent.table)
|
|
372
|
+
|
|
373
|
+
def lower(self, level: int, note: str) -> None:
|
|
374
|
+
self.level = min(self.level, level)
|
|
375
|
+
if note not in self.notes:
|
|
376
|
+
self.notes.append(note)
|
|
377
|
+
|
|
378
|
+
def col(self, ref: str | None, ent: Entity, prop: str) -> str:
|
|
379
|
+
column = ent.columns.get(prop)
|
|
380
|
+
if column is None:
|
|
381
|
+
rel = ent.relations.get(prop)
|
|
382
|
+
if rel is not None and rel["kind"] in ("ManyToOne", "OneToOne"):
|
|
383
|
+
column = self.fk(ent, prop)
|
|
384
|
+
else:
|
|
385
|
+
self.lower(1, f"`{prop}` is not a column of {ent.cls}")
|
|
386
|
+
return mark(prop)
|
|
387
|
+
return f"{ref}.{self.q(column)}" if ref else self.q(column)
|
|
388
|
+
|
|
389
|
+
def fk(self, ent: Entity, prop: str) -> str:
|
|
390
|
+
rel = ent.relations[prop]
|
|
391
|
+
jc = rel.get("join_column") or {}
|
|
392
|
+
return jc.get("name") or prop + "Id"
|
|
393
|
+
|
|
394
|
+
def target(self, ent: Entity, prop: str) -> Entity | None:
|
|
395
|
+
rel = ent.relations.get(prop)
|
|
396
|
+
return self.lib.entity(rel["target"], ent.rel) if rel else None
|
|
397
|
+
|
|
398
|
+
def join_on(self, ent: Entity, ref: str, prop: str, alias: str) -> tuple[str, Entity] | None:
|
|
399
|
+
"""(`JOIN ... ON ...` text without the join keyword, target entity) for a relation of `ent`."""
|
|
400
|
+
rel = ent.relations.get(prop)
|
|
401
|
+
target = self.target(ent, prop)
|
|
402
|
+
if rel is None or target is None:
|
|
403
|
+
return None
|
|
404
|
+
a = self.q(alias)
|
|
405
|
+
tpk = target.columns.get(target.pk[0], target.pk[0]) if target.pk else "id"
|
|
406
|
+
opk = ent.columns.get(ent.pk[0], ent.pk[0]) if ent.pk else "id"
|
|
407
|
+
if rel["kind"] == "ManyToOne" or (rel["kind"] == "OneToOne" and rel.get("join_column") is not None):
|
|
408
|
+
ref_col = (rel.get("join_column") or {}).get("referenced") or tpk
|
|
409
|
+
return f"{self.table(target)} AS {a} ON {a}.{self.q(target.columns.get(ref_col, ref_col))} = {ref}.{self.q(self.fk(ent, prop))}", target
|
|
410
|
+
if rel["kind"] in ("OneToMany", "OneToOne"):
|
|
411
|
+
inv = rel.get("inverse")
|
|
412
|
+
if not inv or inv not in target.relations:
|
|
413
|
+
return None
|
|
414
|
+
return f"{self.table(target)} AS {a} ON {a}.{self.q(self.fk(target, inv))} = {ref}.{self.q(opk)}", target
|
|
415
|
+
jt = rel.get("join_table")
|
|
416
|
+
if rel["kind"] == "ManyToMany" and jt is not None and jt.get("name") and jt.get("own") and jt.get("other"):
|
|
417
|
+
j = self.q(alias + "_join")
|
|
418
|
+
return (f"{self.q(jt['name'])} AS {j} ON {j}.{self.q(jt['own'])} = {ref}.{self.q(opk)} "
|
|
419
|
+
f"LEFT JOIN {self.table(target)} AS {a} ON {a}.{self.q(tpk)} = {j}.{self.q(jt['other'])}"), target
|
|
420
|
+
return None
|
|
421
|
+
|
|
422
|
+
def op_value(self, colref: str, v: Node) -> str:
|
|
423
|
+
"""`column <operator> value` for a where value: a literal, an expression, or a find operator call."""
|
|
424
|
+
uv = unwrap(v)
|
|
425
|
+
if uv is None or o.is_undefined(uv):
|
|
426
|
+
return ""
|
|
427
|
+
lit = o.literal(uv)
|
|
428
|
+
if lit == "NULL":
|
|
429
|
+
return f"{colref} IS NULL"
|
|
430
|
+
if lit is not None:
|
|
431
|
+
return f"{colref} = {lit}"
|
|
432
|
+
if uv.type == "call_expression":
|
|
433
|
+
fn = unwrap(uv.child_by_field_name("function"))
|
|
434
|
+
name = txt(fn) if fn is not None and fn.type == "identifier" else ""
|
|
435
|
+
a = uv.child_by_field_name("arguments")
|
|
436
|
+
args = [x for x in a.named_children if x.type != "comment"] if a is not None and a.type == "arguments" else []
|
|
437
|
+
if name == "IsNull":
|
|
438
|
+
return f"{colref} IS NULL"
|
|
439
|
+
if name == "In" and args:
|
|
440
|
+
return f"{colref} IN ({o.in_list(args[0])})"
|
|
441
|
+
if name == "Not" and args:
|
|
442
|
+
inner = self.op_value(colref, args[0])
|
|
443
|
+
if inner.endswith(" IS NULL"):
|
|
444
|
+
return f"{colref} IS NOT NULL"
|
|
445
|
+
m = re.match(re.escape(colref) + r" = (.+)$", inner)
|
|
446
|
+
return f"{colref} <> {m.group(1)}" if m else f"NOT ({inner})"
|
|
447
|
+
if name in OPERATORS and args:
|
|
448
|
+
return f"{colref} {OPERATORS[name]} {o.value(args[0])}"
|
|
449
|
+
if name in ("Like", "ILike") and args:
|
|
450
|
+
return f"{colref} {'ILIKE' if name == 'ILike' and self.engine != 'mysql' else 'LIKE'} {o.value(args[0])}"
|
|
451
|
+
if name == "Between" and len(args) == 2:
|
|
452
|
+
return f"{colref} BETWEEN {o.value(args[0])} AND {o.value(args[1])}"
|
|
453
|
+
if name == "Any" and args:
|
|
454
|
+
return f"{colref} = ANY({o.value(args[0])})"
|
|
455
|
+
if name == "ArrayContains" and args:
|
|
456
|
+
return f"{colref} @> {o.value(args[0])}"
|
|
457
|
+
if name == "ArrayOverlap" and args:
|
|
458
|
+
return f"{colref} && {o.value(args[0])}"
|
|
459
|
+
if name == "And" and args:
|
|
460
|
+
return " AND ".join(p for p in (self.op_value(colref, x) for x in args) if p)
|
|
461
|
+
if name in ("Raw", "Or"):
|
|
462
|
+
return mark(f"{colref} {txt(uv)}")
|
|
463
|
+
return f"{colref} = {mark_node(uv)}"
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
class Call(Base):
|
|
467
|
+
def __init__(self, lib: Library, f, call: Node, ent: Entity, method: str, args: list[Node], sink: str, wrapper: str = ""):
|
|
468
|
+
self.lib, self.f, self.call, self.ent, self.method, self.args, self.sink = lib, f, call, ent, method, args, sink
|
|
469
|
+
self.engine = o.engine_of(f)
|
|
470
|
+
self.notes: list[str] = []
|
|
471
|
+
self.level = 2
|
|
472
|
+
self.scope: list[str] = []
|
|
473
|
+
self.scope_column: tuple[str, str] | None = None # (column, value) a wrapper's leading argument stands for
|
|
474
|
+
# a project's own repository wrapper (`TenantRepository<User>`) that takes a scope before the usual arguments
|
|
475
|
+
lead = unwrap(args[0]) if args else None
|
|
476
|
+
if wrapper and lead is not None and lead.type in ("identifier", "member_expression") and (
|
|
477
|
+
len(args) > 1 or method in FINDS - BY - {"sum", "average", "minimum", "maximum"}):
|
|
478
|
+
parts = txt(lead).split(".")
|
|
479
|
+
name = parts[-1]
|
|
480
|
+
if len(parts) > 1 and name in ("id", "uuid"): # `workspace.id` stands for the workspace's id, not this table's
|
|
481
|
+
name = parts[-2] + name[0].upper() + name[1:]
|
|
482
|
+
self.args = args[1:]
|
|
483
|
+
if name in ent.columns:
|
|
484
|
+
self.scope.append(f"{self.q(ent.columns[name])} = {mark_node(lead)}")
|
|
485
|
+
self.scope_column = (self.q(ent.columns[name]), mark_node(lead))
|
|
486
|
+
what = "set" if method in ("insert", "upsert") else "filter"
|
|
487
|
+
self.lower(1, f"`{wrapper}` is the project's wrapper: its leading argument `{txt(lead)}` is taken to {what} the column of that name")
|
|
488
|
+
else:
|
|
489
|
+
self.scope.append(mark(f"scope: {txt(lead)}"))
|
|
490
|
+
self.lower(1, f"`{wrapper}` is the project's wrapper: what it does with its leading argument `{txt(lead)}` is not known")
|
|
491
|
+
elif wrapper:
|
|
492
|
+
self.lower(1, f"`{wrapper}` is the project's wrapper around a repository: taken to pass its arguments on unchanged")
|
|
493
|
+
self.joins: list[str] = []
|
|
494
|
+
self.join_cols: list[str] = []
|
|
495
|
+
self.aliases: dict[str, tuple[str, Entity]] = {}
|
|
496
|
+
self.ref = ""
|
|
497
|
+
|
|
498
|
+
def obj(self, node):
|
|
499
|
+
return as_object(self.f, node, self.call)
|
|
500
|
+
|
|
501
|
+
def joined(self, ent: Entity, ref: str, path: str, prop: str, select: bool) -> tuple[str, Entity] | None:
|
|
502
|
+
key = f"{path}.{prop}"
|
|
503
|
+
if key in self.aliases:
|
|
504
|
+
return self.aliases[key]
|
|
505
|
+
alias = (path + "__" + prop).replace(".", "_")
|
|
506
|
+
got = self.join_on(ent, ref, prop, alias)
|
|
507
|
+
if got is None:
|
|
508
|
+
self.lower(1, f"relation {ent.cls}.{prop} could not be read from the entity")
|
|
509
|
+
return None
|
|
510
|
+
self.joins.append(f" LEFT JOIN {got[0]}")
|
|
511
|
+
self.aliases[key] = (self.q(alias), got[1])
|
|
512
|
+
if select:
|
|
513
|
+
self.join_cols += [f"{self.q(alias)}.{self.q(c)}" for c in got[1].columns.values()]
|
|
514
|
+
return self.aliases[key]
|
|
515
|
+
|
|
516
|
+
def where(self, node: Node | None, ent: Entity, ref: str | None, path: str) -> str:
|
|
517
|
+
node = unwrap(node)
|
|
518
|
+
if node is None or o.is_undefined(node):
|
|
519
|
+
return ""
|
|
520
|
+
items = o.array_items(node)
|
|
521
|
+
if items is not None: # an array of conditions is OR
|
|
522
|
+
parts = [p for p in (self.where(i, ent, ref, path) for i in items) if p]
|
|
523
|
+
return "(" + " OR ".join(f"({p})" for p in parts) + ")" if parts else ""
|
|
524
|
+
obj = self.obj(node)
|
|
525
|
+
if obj is None:
|
|
526
|
+
return mark_node(node)
|
|
527
|
+
preds = []
|
|
528
|
+
for k, v in obj.entries:
|
|
529
|
+
uv = unwrap(v)
|
|
530
|
+
if k in ent.relations and uv is not None and uv.type in ("object", "identifier") and self.obj(uv) is not None:
|
|
531
|
+
self.need_ref = True
|
|
532
|
+
base = ref or self.q(ent.cls)
|
|
533
|
+
got = self.joined(ent, base, path, k, select=False)
|
|
534
|
+
if got is None:
|
|
535
|
+
preds.append(mark(f"{k}: {txt(uv)}"))
|
|
536
|
+
else:
|
|
537
|
+
p = self.where(uv, got[1], got[0], f"{path}.{k}")
|
|
538
|
+
preds.append(p)
|
|
539
|
+
continue
|
|
540
|
+
preds.append(self.op_value(self.col(ref, ent, k), v))
|
|
541
|
+
preds += [mark(e) for e in obj.extra]
|
|
542
|
+
preds += [mark("optional: " + text) for _k, _v, text in obj.maybe]
|
|
543
|
+
return " AND ".join(p for p in preds if p)
|
|
544
|
+
|
|
545
|
+
def relations(self, node: Node | None, ent: Entity, ref: str, path: str) -> None:
|
|
546
|
+
node = unwrap(node)
|
|
547
|
+
if node is None:
|
|
548
|
+
return
|
|
549
|
+
items = o.array_items(node)
|
|
550
|
+
if items is not None:
|
|
551
|
+
for it in items:
|
|
552
|
+
s = o.string_value(it)
|
|
553
|
+
if s is None:
|
|
554
|
+
self.lower(1, f"a relation is named at run time: {mark_node(it)}")
|
|
555
|
+
continue
|
|
556
|
+
cur_ent, cur_ref, cur_path = ent, ref, path
|
|
557
|
+
for part in s.split("."):
|
|
558
|
+
got = self.joined(cur_ent, cur_ref, cur_path, part, select=True)
|
|
559
|
+
if got is None:
|
|
560
|
+
break
|
|
561
|
+
cur_ref, cur_ent, cur_path = got[0], got[1], f"{cur_path}.{part}"
|
|
562
|
+
return
|
|
563
|
+
obj = self.obj(node)
|
|
564
|
+
if obj is None:
|
|
565
|
+
self.lower(1, f"relations decided at run time: {mark_node(node)}")
|
|
566
|
+
return
|
|
567
|
+
for k, v in obj.entries:
|
|
568
|
+
if txt(unwrap(v)) == "false":
|
|
569
|
+
continue
|
|
570
|
+
got = self.joined(ent, ref, path, k, select=True)
|
|
571
|
+
uv = unwrap(v)
|
|
572
|
+
if got is not None and uv is not None and uv.type == "object":
|
|
573
|
+
self.relations(uv, got[1], got[0], f"{path}.{k}")
|
|
574
|
+
|
|
575
|
+
def select_cols(self, node: Node | None, ent: Entity, ref: str | None) -> list[str]:
|
|
576
|
+
node = unwrap(node)
|
|
577
|
+
names: list[str] | None = None
|
|
578
|
+
if node is not None:
|
|
579
|
+
items = o.array_items(node)
|
|
580
|
+
if items is not None:
|
|
581
|
+
names = [s for s in (o.string_value(i) for i in items) if s]
|
|
582
|
+
else:
|
|
583
|
+
obj = self.obj(node)
|
|
584
|
+
if obj is not None:
|
|
585
|
+
names = [k for k, v in obj.entries if k in ent.columns and txt(unwrap(v)) != "false"]
|
|
586
|
+
else:
|
|
587
|
+
return [mark_node(node)]
|
|
588
|
+
if names is None:
|
|
589
|
+
names = list(ent.columns)
|
|
590
|
+
return [self.col(ref, ent, n) for n in names] or ["1"]
|
|
591
|
+
|
|
592
|
+
def order(self, node: Node | None, ent: Entity, ref: str | None) -> list[str]:
|
|
593
|
+
obj = self.obj(node)
|
|
594
|
+
if obj is None:
|
|
595
|
+
return [mark_node(node)] if node is not None else []
|
|
596
|
+
out = []
|
|
597
|
+
for k, v in obj.entries:
|
|
598
|
+
uv = unwrap(v)
|
|
599
|
+
if k not in ent.columns:
|
|
600
|
+
out.append(mark(f"{k}: {txt(uv)}"))
|
|
601
|
+
continue
|
|
602
|
+
d = o.string_value(uv)
|
|
603
|
+
sub = self.obj(uv) if uv is not None and uv.type == "object" else None
|
|
604
|
+
if sub is not None:
|
|
605
|
+
d = o.string_value(sub.get("direction"))
|
|
606
|
+
elif d is None and uv is not None and uv.type != "number":
|
|
607
|
+
self.notes.append(f"sort direction of {k} decided at run time: {mark_node(uv)}")
|
|
608
|
+
desc = (d or "").upper() == "DESC" or txt(uv) == "-1"
|
|
609
|
+
out.append(self.col(ref, ent, k) + (" DESC" if desc else ""))
|
|
610
|
+
return out
|
|
611
|
+
|
|
612
|
+
def criteria(self, node: Node | None) -> str:
|
|
613
|
+
"""The WHERE of update / delete: an id, a list of ids, or a where object."""
|
|
614
|
+
ent = self.ent
|
|
615
|
+
node = unwrap(node)
|
|
616
|
+
if node is None:
|
|
617
|
+
return ""
|
|
618
|
+
pk = self.q(ent.columns.get(ent.pk[0], ent.pk[0])) if ent.pk else self.q("id")
|
|
619
|
+
if node.type in ("string", "number", "template_string"):
|
|
620
|
+
return f"{pk} = {o.value(node)}"
|
|
621
|
+
if node.type == "array":
|
|
622
|
+
return f"{pk} IN ({o.in_list(node)})"
|
|
623
|
+
obj = self.obj(node)
|
|
624
|
+
if obj is not None:
|
|
625
|
+
return self.where(node, ent, None, ent.cls)
|
|
626
|
+
if node.type in ("identifier", "member_expression"):
|
|
627
|
+
last = txt(node).split(".")[-1]
|
|
628
|
+
if re.search(r"(?:^id|Id|_id|^uuid|Uuid)$", last):
|
|
629
|
+
self.lower(1, f"the criteria `{txt(node)}` is taken to be the primary key value, by its name")
|
|
630
|
+
return f"{pk} = {mark_node(node)}"
|
|
631
|
+
if re.search(r"(?:^ids|Ids|_ids)$", last):
|
|
632
|
+
self.lower(1, f"the criteria `{txt(node)}` is taken to be a list of primary key values, by its name")
|
|
633
|
+
return f"{pk} IN ({mark_node(node)})"
|
|
634
|
+
self.lower(1, "the criteria is a value built elsewhere: an id, a list of ids or a where object")
|
|
635
|
+
return mark("criteria: " + txt(node))
|
|
636
|
+
return mark_node(node)
|
|
637
|
+
|
|
638
|
+
def soft(self, w: str, options) -> str:
|
|
639
|
+
ent = self.ent
|
|
640
|
+
if ent.deleted_at and not (options is not None and options.get("withDeleted") is not None and txt(unwrap(options.get("withDeleted"))) != "false"):
|
|
641
|
+
ref = self.ref + "." if self.ref else ""
|
|
642
|
+
return (w + " AND " if w else "") + f"{ref}{self.q(ent.columns[ent.deleted_at])} IS NULL"
|
|
643
|
+
return w
|
|
644
|
+
|
|
645
|
+
def run(self) -> list:
|
|
646
|
+
ent, m = self.ent, self.method
|
|
647
|
+
tbl = self.table(ent)
|
|
648
|
+
arg = self.args[0] if self.args else None
|
|
649
|
+
sites = []
|
|
650
|
+
if m in FINDS:
|
|
651
|
+
options = None
|
|
652
|
+
where_node = None
|
|
653
|
+
if m in BY:
|
|
654
|
+
where_node = arg
|
|
655
|
+
elif m in ("sum", "average", "minimum", "maximum"):
|
|
656
|
+
where_node = self.args[1] if len(self.args) > 1 else None
|
|
657
|
+
elif arg is not None:
|
|
658
|
+
options = self.obj(arg)
|
|
659
|
+
if options is None:
|
|
660
|
+
self.lower(1, "the options are built elsewhere: only the table and the operation are known")
|
|
661
|
+
cols = ", ".join(self.q(c) for c in ent.columns.values()) or "*"
|
|
662
|
+
head = "COUNT(*)" if m.startswith("count") else cols
|
|
663
|
+
return [self.site(f"SELECT {head} FROM {tbl} {mark_node(arg)}", arg)]
|
|
664
|
+
where_node = options.get("where")
|
|
665
|
+
self.need_ref = False
|
|
666
|
+
rel_node = options.get("relations") if options is not None else None
|
|
667
|
+
|
|
668
|
+
def build(ref: str | None) -> tuple[str, str, list[str], list[str]]:
|
|
669
|
+
self.joins, self.join_cols, self.aliases = [], [], {}
|
|
670
|
+
if rel_node is not None:
|
|
671
|
+
self.relations(rel_node, ent, ref or self.q(ent.cls), ent.cls)
|
|
672
|
+
w = self.where(where_node, ent, ref, ent.cls)
|
|
673
|
+
cols = self.select_cols(options.get("select") if options is not None else None, ent, ref)
|
|
674
|
+
order = self.order(options.get("order"), ent, ref) if options is not None and options.get("order") is not None else []
|
|
675
|
+
return w, "".join(self.joins), cols + self.join_cols, order
|
|
676
|
+
|
|
677
|
+
keep = (list(self.notes), self.level)
|
|
678
|
+
w, joins, cols, order = build(None)
|
|
679
|
+
if joins or self.need_ref:
|
|
680
|
+
self.notes, self.level = keep[0], keep[1]
|
|
681
|
+
self.ref = self.q(ent.cls)
|
|
682
|
+
w, joins, cols, order = build(self.ref)
|
|
683
|
+
tbl = f"{tbl} AS {self.ref}"
|
|
684
|
+
w = " AND ".join([(self.ref + "." if self.ref else "") + s if not s.startswith("«") else s for s in self.scope] + ([w] if w else []))
|
|
685
|
+
w = self.soft(w, options)
|
|
686
|
+
if options is not None and (options.extra or options.maybe):
|
|
687
|
+
extra = list(options.extra) + [t for _k, _v, t in options.maybe]
|
|
688
|
+
self.notes.append("options spread in at run time may add filters, relations, ordering or paging")
|
|
689
|
+
w = " AND ".join(([w] if w else []) + [mark(e) for e in extra])
|
|
690
|
+
where = f" WHERE {w}" if w else ""
|
|
691
|
+
tail = (" ORDER BY " + ", ".join(order)) if order else ""
|
|
692
|
+
take = options.get("take") if options is not None else None
|
|
693
|
+
skip = options.get("skip") if options is not None else None
|
|
694
|
+
limit = ""
|
|
695
|
+
if take is not None and not o.is_undefined(take):
|
|
696
|
+
limit += f" LIMIT {o.value(take)}"
|
|
697
|
+
elif m.startswith("findOne"):
|
|
698
|
+
limit += " LIMIT 1"
|
|
699
|
+
if skip is not None and not o.is_undefined(skip):
|
|
700
|
+
limit += f" OFFSET {o.value(skip)}"
|
|
701
|
+
if joins and (take is not None or skip is not None):
|
|
702
|
+
self.notes.append("with take / skip and joined relations TypeORM first selects the distinct ids, then the rows")
|
|
703
|
+
if joins:
|
|
704
|
+
self.notes.append("relations are loaded by LEFT JOINs in this statement")
|
|
705
|
+
count_sql = f"SELECT COUNT(1) FROM {tbl}{joins}{where}"
|
|
706
|
+
if m in ("count", "countBy"):
|
|
707
|
+
return [self.site(count_sql, arg)]
|
|
708
|
+
if m in ("exists", "exist", "existsBy"):
|
|
709
|
+
return [self.site(f"SELECT 1 FROM {tbl}{joins}{where} LIMIT 1", arg)]
|
|
710
|
+
if m in ("sum", "average", "minimum", "maximum"):
|
|
711
|
+
fn = {"sum": "SUM", "average": "AVG", "minimum": "MIN", "maximum": "MAX"}[m]
|
|
712
|
+
prop = o.string_value(arg)
|
|
713
|
+
c = self.col(None, ent, prop) if prop else mark_node(arg)
|
|
714
|
+
return [self.site(f"SELECT {fn}({c}) FROM {tbl}{where}", arg)]
|
|
715
|
+
sites.append(self.site(f"SELECT {', '.join(cols)} FROM {tbl}{joins}{where}{tail}{limit}", arg))
|
|
716
|
+
if m.startswith("findAndCount"):
|
|
717
|
+
sites.append(self.site(count_sql, arg, extra="findAndCount: the second statement counts the rows"))
|
|
718
|
+
return sites
|
|
719
|
+
if m == "insert":
|
|
720
|
+
ua = unwrap(arg)
|
|
721
|
+
rows = o.array_items(ua)
|
|
722
|
+
first = rows[0] if rows else ua
|
|
723
|
+
obj = self.obj(first) if first is not None else None
|
|
724
|
+
if obj is None or not (obj.entries or obj.extra):
|
|
725
|
+
return [self.site(f"INSERT INTO {tbl} ({mark('columns of ' + txt(ua))}) VALUES ({mark_node(ua)})", arg)]
|
|
726
|
+
names = [self.col(None, ent, k) for k, _ in obj.entries] + [mark(e) for e in obj.extra]
|
|
727
|
+
vals = [o.value(v) for _, v in obj.entries] + [mark(e) for e in obj.extra]
|
|
728
|
+
if self.scope_column is not None and self.scope_column[0] not in names: # the wrapper writes its scope into the row
|
|
729
|
+
names.append(self.scope_column[0])
|
|
730
|
+
vals.append(self.scope_column[1])
|
|
731
|
+
return [self.site(f"INSERT INTO {tbl} ({', '.join(names)}) VALUES ({', '.join(vals)})", arg)]
|
|
732
|
+
if m == "upsert":
|
|
733
|
+
ua = unwrap(arg)
|
|
734
|
+
rows = o.array_items(ua)
|
|
735
|
+
first = rows[0] if rows else ua
|
|
736
|
+
obj = self.obj(first) if first is not None else None
|
|
737
|
+
conflict_node = unwrap(self.args[1]) if len(self.args) > 1 else None
|
|
738
|
+
cobj = self.obj(conflict_node) if conflict_node is not None and conflict_node.type == "object" else None
|
|
739
|
+
paths = o.array_items(cobj.get("conflictPaths") if cobj is not None else conflict_node)
|
|
740
|
+
keys = [self.col(None, ent, s) for s in (o.string_value(p) for p in (paths or [])) if s]
|
|
741
|
+
target = ", ".join(keys) or mark("conflict paths")
|
|
742
|
+
if obj is None or not obj.entries:
|
|
743
|
+
ins = f"INSERT INTO {tbl} ({mark('columns of ' + txt(ua))}) VALUES ({mark_node(ua)})"
|
|
744
|
+
sets = f"{mark('columns')} = {mark('EXCLUDED')}"
|
|
745
|
+
else:
|
|
746
|
+
names = [self.col(None, ent, k) for k, _ in obj.entries]
|
|
747
|
+
vals = [o.value(v) for _, v in obj.entries]
|
|
748
|
+
if self.scope_column is not None and self.scope_column[0] not in names:
|
|
749
|
+
names.append(self.scope_column[0])
|
|
750
|
+
vals.append(self.scope_column[1])
|
|
751
|
+
ins = f"INSERT INTO {tbl} ({', '.join(names)}) VALUES ({', '.join(vals)})"
|
|
752
|
+
sets = ", ".join(f"{n} = EXCLUDED.{n}" for n in names if n not in keys) or f"{names[0]} = EXCLUDED.{names[0]}"
|
|
753
|
+
if self.engine == "mysql":
|
|
754
|
+
sets = re.sub(r"EXCLUDED\.(`[^`]+`)", r"VALUES(\1)", sets)
|
|
755
|
+
return [self.site(f"{ins} ON DUPLICATE KEY UPDATE {sets}", arg)]
|
|
756
|
+
return [self.site(f"{ins} ON CONFLICT ({target}) DO UPDATE SET {sets}", arg)]
|
|
757
|
+
arg = self.args[0] if self.args else None
|
|
758
|
+
w = " AND ".join(self.scope + ([self.criteria(arg)] if arg is not None and self.criteria(arg) else []))
|
|
759
|
+
if m in ("update", "increment", "decrement"):
|
|
760
|
+
if m == "update":
|
|
761
|
+
obj = self.obj(self.args[1]) if len(self.args) > 1 else None
|
|
762
|
+
if obj is None:
|
|
763
|
+
part = unwrap(self.args[1]) if len(self.args) > 1 else None
|
|
764
|
+
sets = f"{mark('columns of ' + txt(part))} = {mark_node(part)}"
|
|
765
|
+
else:
|
|
766
|
+
if obj.maybe:
|
|
767
|
+
self.notes.append("columns set under a condition: " + ", ".join(dict.fromkeys(k for k, _v, _t in obj.maybe)))
|
|
768
|
+
pairs = [f"{self.col(None, ent, k)} = {self._set_value(v)}"
|
|
769
|
+
for k, v in obj.entries + [(k, v) for k, v, _t in obj.maybe] if not o.is_undefined(v)]
|
|
770
|
+
pairs += [f"{mark(e)} = {mark(e)}" for e in obj.extra]
|
|
771
|
+
sets = ", ".join(pairs) or f"{mark('no column')} = {mark('no column')}"
|
|
772
|
+
else:
|
|
773
|
+
prop = o.string_value(self.args[1]) if len(self.args) > 1 else None
|
|
774
|
+
c = self.col(None, ent, prop) if prop else mark("column")
|
|
775
|
+
sets = f"{c} = {c} {'+' if m == 'increment' else '-'} {o.value(self.args[2]) if len(self.args) > 2 else '1'}"
|
|
776
|
+
return [self.site(f"UPDATE {tbl} SET {sets}{' WHERE ' + w if w else ''}", arg)]
|
|
777
|
+
if m == "delete":
|
|
778
|
+
return [self.site(f"DELETE FROM {tbl}{' WHERE ' + w if w else ''}", arg)]
|
|
779
|
+
if m in ("softDelete", "restore"):
|
|
780
|
+
if not ent.deleted_at:
|
|
781
|
+
self.lower(1, f"{ent.cls} has no @DeleteDateColumn that could be read")
|
|
782
|
+
dcol = mark("delete date column")
|
|
783
|
+
else:
|
|
784
|
+
dcol = self.q(ent.columns[ent.deleted_at])
|
|
785
|
+
if m == "softDelete":
|
|
786
|
+
return [self.site(f"UPDATE {tbl} SET {dcol} = CURRENT_TIMESTAMP WHERE {(w + ' AND ') if w else ''}{dcol} IS NULL", arg)]
|
|
787
|
+
return [self.site(f"UPDATE {tbl} SET {dcol} = NULL{' WHERE ' + w if w else ''}", arg)]
|
|
788
|
+
return []
|
|
789
|
+
|
|
790
|
+
def _set_value(self, v: Node) -> str:
|
|
791
|
+
uv = unwrap(v)
|
|
792
|
+
body = o.callback_body(uv)
|
|
793
|
+
if body is not None: # () => "counter + 1": raw SQL
|
|
794
|
+
s = o.string_value(body)
|
|
795
|
+
return s if s is not None else mark_node(body)
|
|
796
|
+
return o.value(uv)
|
|
797
|
+
|
|
798
|
+
def site(self, sql: str, arg: Node | None, extra: str | None = None):
|
|
799
|
+
notes = ([extra] if extra else []) + self.notes
|
|
800
|
+
return o.make_site(self.f, self.call, self.sink, self.engine, sql, arg, library=NAME, table=self.ent.table,
|
|
801
|
+
operation=self.method, confidence=o.CONFIDENCE[self.level], notes=notes)
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
class Builder(Base):
|
|
805
|
+
"""`repo.createQueryBuilder("u").leftJoinAndSelect("u.posts", "p").where("u.id = :id", { id }).getMany()`."""
|
|
806
|
+
|
|
807
|
+
def __init__(self, lib: Library, f, root: Node):
|
|
808
|
+
self.lib, self.f, self.root = lib, f, root
|
|
809
|
+
self.engine = o.engine_of(f)
|
|
810
|
+
self.notes: list[str] = []
|
|
811
|
+
self.level = 2
|
|
812
|
+
self.aliases: dict[str, Entity | None] = {}
|
|
813
|
+
|
|
814
|
+
def text(self, s: str) -> str:
|
|
815
|
+
"""A SQL string of the builder: `alias.prop` -> `"alias"."column"`, `:name` -> «name»."""
|
|
816
|
+
def swap(m: re.Match) -> str:
|
|
817
|
+
alias, prop = m.group(1), m.group(2)
|
|
818
|
+
ent = self.aliases.get(alias)
|
|
819
|
+
if alias not in self.aliases:
|
|
820
|
+
return m.group(0)
|
|
821
|
+
column = ent.columns.get(prop, self.fk(ent, prop) if prop in ent.relations and ent.relations[prop]["kind"] in ("ManyToOne", "OneToOne") else prop) if ent else prop
|
|
822
|
+
return f"{self.q(alias)}.{self.q(column)}"
|
|
823
|
+
s = re.sub(r"(?<![\w\".])([A-Za-z_]\w*)\.([A-Za-z_]\w*)\b(?!\s*\()", swap, s)
|
|
824
|
+
s = re.sub(r"\(\s*:\.\.\.(\w+)\s*\)", lambda m: "(" + mark(m.group(1)) + ")", s)
|
|
825
|
+
s = re.sub(r":\.\.\.(\w+)", lambda m: mark(m.group(1)), s)
|
|
826
|
+
s = re.sub(r"(?<![:\w]):([A-Za-z_]\w*)", lambda m: mark(m.group(1)), s)
|
|
827
|
+
return " ".join(s.split())
|
|
828
|
+
|
|
829
|
+
def string(self, node: Node | None) -> str | None:
|
|
830
|
+
s = o.string_value(node)
|
|
831
|
+
if s is not None:
|
|
832
|
+
return s
|
|
833
|
+
try:
|
|
834
|
+
res = self.f.resolve(node, self.root, 0) if node is not None else None
|
|
835
|
+
except Exception:
|
|
836
|
+
res = None
|
|
837
|
+
return res.text if res is not None and res.text else None
|
|
838
|
+
|
|
839
|
+
def cond(self, args: list[Node]) -> str:
|
|
840
|
+
if not args:
|
|
841
|
+
return mark("?")
|
|
842
|
+
first = unwrap(args[0])
|
|
843
|
+
s = self.string(first) if first is not None and first.type in ("string", "template_string", "identifier") else None
|
|
844
|
+
if s is not None and first.type != "identifier":
|
|
845
|
+
return self.text(s)
|
|
846
|
+
ent = self.aliases.get(self.main)
|
|
847
|
+
obj = as_object(self.f, first, self.root) if first is not None else None
|
|
848
|
+
if obj is not None and ent is not None:
|
|
849
|
+
ref = self.q(self.main)
|
|
850
|
+
preds = [self.op_value(self.col(ref, ent, k), v) for k, v in obj.entries] + [mark(e) for e in obj.extra]
|
|
851
|
+
return " AND ".join(p for p in preds if p) or "TRUE"
|
|
852
|
+
return mark_node(first)
|
|
853
|
+
|
|
854
|
+
def run(self):
|
|
855
|
+
top = climb(self.root)
|
|
856
|
+
base, steps = spine(top)
|
|
857
|
+
idx = next(i for i, s in enumerate(steps) if s[2].id == self.root.id)
|
|
858
|
+
root_args, post = steps[idx][1], steps[idx + 1:]
|
|
859
|
+
fn = unwrap(self.root.child_by_field_name("function"))
|
|
860
|
+
recv = unwrap(fn.child_by_field_name("object"))
|
|
861
|
+
ent_name = self.lib.entity_name(self.f, recv, self.root)
|
|
862
|
+
alias = ""
|
|
863
|
+
if root_args and unwrap(root_args[0]).type == "identifier" and self.lib.by_class.get(txt(unwrap(root_args[0]))):
|
|
864
|
+
ent_name = txt(unwrap(root_args[0])) # manager.createQueryBuilder(User, "u")
|
|
865
|
+
alias = o.string_value(root_args[1]) if len(root_args) > 1 else ""
|
|
866
|
+
elif root_args:
|
|
867
|
+
alias = o.string_value(root_args[0]) or ""
|
|
868
|
+
kind = "select"
|
|
869
|
+
from_node = None
|
|
870
|
+
for name, args, _c in post:
|
|
871
|
+
if name in ("update", "delete", "insert", "softDelete", "restore"):
|
|
872
|
+
kind = name
|
|
873
|
+
if name == "update" and args and unwrap(args[0]).type == "identifier":
|
|
874
|
+
from_node = args[0]
|
|
875
|
+
elif name in ("from", "into") and args:
|
|
876
|
+
from_node = args[0]
|
|
877
|
+
if len(args) > 1 and o.string_value(args[1]):
|
|
878
|
+
alias = o.string_value(args[1])
|
|
879
|
+
raw_table = ""
|
|
880
|
+
if from_node is not None:
|
|
881
|
+
u = unwrap(from_node)
|
|
882
|
+
if u.type == "identifier":
|
|
883
|
+
ent_name = txt(u)
|
|
884
|
+
elif o.string_value(u):
|
|
885
|
+
raw_table, ent_name = o.string_value(u), None
|
|
886
|
+
else:
|
|
887
|
+
raise Skip("query builder: the table is chosen at run time")
|
|
888
|
+
ent = self.lib.entity(ent_name, self.f.rel) if ent_name else None
|
|
889
|
+
if ent is None and not raw_table:
|
|
890
|
+
if ent_name and not self.lib.by_class.get(ent_name):
|
|
891
|
+
raise Skip("entity is not a static @Entity (tables built at run time)")
|
|
892
|
+
raise Skip("query builder: the entity is not visible here")
|
|
893
|
+
self.main = alias or (ent.cls if ent else raw_table)
|
|
894
|
+
self.aliases[self.main] = ent
|
|
895
|
+
tbl = self.table(ent) if ent else o.qname(self.engine, raw_table)
|
|
896
|
+
ref = self.q(self.main)
|
|
897
|
+
cols: list[str] = []
|
|
898
|
+
explicit = False
|
|
899
|
+
joins: list[str] = []
|
|
900
|
+
wheres: list[str] = []
|
|
901
|
+
groups: list[str] = []
|
|
902
|
+
havings: list[str] = []
|
|
903
|
+
orders: list[str] = []
|
|
904
|
+
sets: list[str] = []
|
|
905
|
+
values: Node | None = None
|
|
906
|
+
limit = offset = ""
|
|
907
|
+
terminal = ""
|
|
908
|
+
with_deleted = False
|
|
909
|
+
returning = ""
|
|
910
|
+
|
|
911
|
+
def select(args: list[Node], reset: bool) -> None:
|
|
912
|
+
nonlocal explicit
|
|
913
|
+
if reset:
|
|
914
|
+
cols.clear()
|
|
915
|
+
explicit = True
|
|
916
|
+
if not args:
|
|
917
|
+
return
|
|
918
|
+
first = unwrap(args[0])
|
|
919
|
+
items = o.array_items(first)
|
|
920
|
+
alias2 = o.string_value(args[1]) if len(args) > 1 else None
|
|
921
|
+
for it in (items if items is not None else [first]):
|
|
922
|
+
s = self.string(it)
|
|
923
|
+
if s is None:
|
|
924
|
+
cols.append(mark_node(it))
|
|
925
|
+
continue
|
|
926
|
+
s = s.strip()
|
|
927
|
+
if s in self.aliases and self.aliases[s] is not None: # select("u"): every column of the alias
|
|
928
|
+
cols.extend(f"{self.q(s)}.{self.q(c)}" for c in self.aliases[s].columns.values())
|
|
929
|
+
else:
|
|
930
|
+
cols.append(self.text(s) + (f" AS {self.q(alias2)}" if alias2 and items is None else ""))
|
|
931
|
+
|
|
932
|
+
def join(kind_sql: str, args: list[Node], sel: bool) -> None:
|
|
933
|
+
if not args:
|
|
934
|
+
return
|
|
935
|
+
target = unwrap(args[0])
|
|
936
|
+
a2 = o.string_value(args[1]) if len(args) > 1 else ""
|
|
937
|
+
cond = self.string(args[2]) if len(args) > 2 else None
|
|
938
|
+
s = o.string_value(target)
|
|
939
|
+
if s and "." in s and s.split(".")[0] in self.aliases and self.aliases[s.split(".")[0]] is not None:
|
|
940
|
+
owner_alias, prop = s.split(".", 1)
|
|
941
|
+
owner = self.aliases[owner_alias]
|
|
942
|
+
got = self.join_on(owner, self.q(owner_alias), prop, a2 or prop)
|
|
943
|
+
if got is None:
|
|
944
|
+
self.lower(1, f"relation {owner.cls}.{prop} could not be read from the entity")
|
|
945
|
+
self.aliases[a2 or prop] = None
|
|
946
|
+
joins.append(f" {kind_sql} {mark(s)} AS {self.q(a2 or prop)} ON {mark('relation ' + s)}")
|
|
947
|
+
return
|
|
948
|
+
self.aliases[a2 or prop] = got[1]
|
|
949
|
+
joins.append(f" {kind_sql} {got[0]}" + (f" AND {self.text(cond)}" if cond else ""))
|
|
950
|
+
if sel:
|
|
951
|
+
cols.extend(f"{self.q(a2 or prop)}.{self.q(c)}" for c in got[1].columns.values())
|
|
952
|
+
return
|
|
953
|
+
ent2 = self.lib.entity(txt(target), self.f.rel) if target is not None and target.type == "identifier" else None
|
|
954
|
+
if ent2 is not None:
|
|
955
|
+
self.aliases[a2] = ent2
|
|
956
|
+
joins.append(f" {kind_sql} {self.table(ent2)} AS {self.q(a2)} ON {self.text(cond) if cond else 'TRUE'}")
|
|
957
|
+
if sel:
|
|
958
|
+
cols.extend(f"{self.q(a2)}.{self.q(c)}" for c in ent2.columns.values())
|
|
959
|
+
elif s:
|
|
960
|
+
self.aliases[a2] = None
|
|
961
|
+
joins.append(f" {kind_sql} {o.qname(self.engine, s)} AS {self.q(a2)} ON {self.text(cond) if cond else 'TRUE'}")
|
|
962
|
+
else:
|
|
963
|
+
joins.append(f" {kind_sql} {mark_node(target)} AS {self.q(a2 or 'j')} ON {self.text(cond) if cond else 'TRUE'}")
|
|
964
|
+
|
|
965
|
+
for name, args, _c in post:
|
|
966
|
+
if name in ("select", "addSelect"):
|
|
967
|
+
select(args, name == "select")
|
|
968
|
+
elif name in ("leftJoin", "innerJoin", "leftJoinAndSelect", "innerJoinAndSelect", "leftJoinAndMapOne", "leftJoinAndMapMany",
|
|
969
|
+
"innerJoinAndMapOne", "innerJoinAndMapMany"):
|
|
970
|
+
jargs = args[1:] if "AndMap" in name else args
|
|
971
|
+
join("INNER JOIN" if name.startswith("inner") else "LEFT JOIN", jargs, "AndSelect" in name or "AndMap" in name)
|
|
972
|
+
elif name in ("where", "andWhere"):
|
|
973
|
+
if name == "where":
|
|
974
|
+
wheres.clear()
|
|
975
|
+
wheres.append(self.cond(args))
|
|
976
|
+
elif name == "orWhere":
|
|
977
|
+
p = self.cond(args)
|
|
978
|
+
if wheres:
|
|
979
|
+
wheres[-1] = f"({wheres[-1]} OR {p})"
|
|
980
|
+
else:
|
|
981
|
+
wheres.append(p)
|
|
982
|
+
elif name in ("groupBy", "addGroupBy") and args:
|
|
983
|
+
s = self.string(args[0])
|
|
984
|
+
groups.append(self.text(s) if s else mark_node(args[0]))
|
|
985
|
+
elif name in ("having", "andHaving"):
|
|
986
|
+
havings.append(self.cond(args))
|
|
987
|
+
elif name in ("orderBy", "addOrderBy") and args:
|
|
988
|
+
s = self.string(args[0])
|
|
989
|
+
d = o.string_value(args[1]) if len(args) > 1 else ""
|
|
990
|
+
if len(args) > 1 and d is None:
|
|
991
|
+
self.notes.append(f"sort direction decided at run time: {mark_node(args[1])}")
|
|
992
|
+
orders.append((self.text(s) if s else mark_node(args[0])) + (" DESC" if (d or "").upper() == "DESC" else ""))
|
|
993
|
+
elif name in ("take", "limit") and args:
|
|
994
|
+
limit = o.value(args[0])
|
|
995
|
+
elif name in ("skip", "offset") and args:
|
|
996
|
+
offset = o.value(args[0])
|
|
997
|
+
elif name == "set" and args:
|
|
998
|
+
obj = as_object(self.f, args[0], self.root)
|
|
999
|
+
if obj is None:
|
|
1000
|
+
sets.append(f"{mark('columns of ' + txt(args[0]))} = {mark_node(args[0])}")
|
|
1001
|
+
else:
|
|
1002
|
+
for k, v in obj.entries:
|
|
1003
|
+
body = o.callback_body(v)
|
|
1004
|
+
raw = o.string_value(body) if body is not None else None
|
|
1005
|
+
c = self.q(ent.columns.get(k, k)) if ent else self.q(k)
|
|
1006
|
+
sets.append(f"{c} = {raw if raw is not None else o.value(v)}")
|
|
1007
|
+
sets.extend(f"{mark(e)} = {mark(e)}" for e in obj.extra)
|
|
1008
|
+
elif name == "values" and args:
|
|
1009
|
+
values = args[0]
|
|
1010
|
+
elif name == "withDeleted":
|
|
1011
|
+
with_deleted = True
|
|
1012
|
+
elif name == "returning" and args:
|
|
1013
|
+
s = self.string(args[0])
|
|
1014
|
+
returning = " RETURNING " + (s if s else mark_node(args[0]))
|
|
1015
|
+
elif name in QB_TERMINAL:
|
|
1016
|
+
terminal = name
|
|
1017
|
+
elif name in ("update", "delete", "insert", "from", "into", "softDelete", "restore", "setParameter", "setParameters",
|
|
1018
|
+
"setLock", "cache", "printSql", "useTransaction", "distinct", "comment", "setFindOptions", "orIgnore",
|
|
1019
|
+
"onConflict", "orUpdate", "updateEntity", "callListeners", "clone", "then", "catch", "finally", "map"):
|
|
1020
|
+
if name in ("setFindOptions", "onConflict", "orUpdate", "orIgnore"):
|
|
1021
|
+
self.lower(1, f"step .{name}() is not translated")
|
|
1022
|
+
else:
|
|
1023
|
+
self.lower(1, f"step .{name}() is not translated")
|
|
1024
|
+
if not terminal:
|
|
1025
|
+
self.lower(1, "the builder is not executed in this expression: it is continued or passed on elsewhere")
|
|
1026
|
+
if ent is not None and ent.deleted_at and not with_deleted and kind == "select" \
|
|
1027
|
+
and ent.columns[ent.deleted_at] not in " ".join(wheres):
|
|
1028
|
+
wheres.append(f"{ref}.{self.q(ent.columns[ent.deleted_at])} IS NULL")
|
|
1029
|
+
where = (" WHERE " + " AND ".join(f"({w})" if " OR " in w and not w.startswith("(") else w for w in wheres)) if wheres else ""
|
|
1030
|
+
if kind == "select":
|
|
1031
|
+
if not explicit and ent is not None:
|
|
1032
|
+
cols = [f"{ref}.{self.q(c)}" for c in ent.columns.values()] + cols
|
|
1033
|
+
if terminal == "getCount":
|
|
1034
|
+
cols = ["COUNT(1)"]
|
|
1035
|
+
if not cols:
|
|
1036
|
+
cols = ["*"]
|
|
1037
|
+
sql = (f"SELECT {', '.join(dict.fromkeys(cols))} FROM {tbl} AS {ref}{''.join(joins)}{where}"
|
|
1038
|
+
+ (" GROUP BY " + ", ".join(groups) if groups else "") + (" HAVING " + " AND ".join(havings) if havings else "")
|
|
1039
|
+
+ (" ORDER BY " + ", ".join(orders) if orders else "")
|
|
1040
|
+
+ (f" LIMIT {limit}" if limit else "") + (f" OFFSET {offset}" if offset else ""))
|
|
1041
|
+
if terminal == "getManyAndCount":
|
|
1042
|
+
self.notes.append("getManyAndCount also runs a COUNT of the same statement")
|
|
1043
|
+
elif kind == "update":
|
|
1044
|
+
if not sets:
|
|
1045
|
+
sets = [f"{mark('columns')} = {mark('values')}"]
|
|
1046
|
+
sql = f"UPDATE {tbl} SET {', '.join(sets)}{self._plain(where, ref)}{returning}"
|
|
1047
|
+
elif kind == "delete":
|
|
1048
|
+
sql = f"DELETE FROM {tbl}{self._plain(where, ref)}{returning}"
|
|
1049
|
+
elif kind in ("softDelete", "restore"):
|
|
1050
|
+
dcol = self.q(ent.columns[ent.deleted_at]) if ent is not None and ent.deleted_at else mark("delete date column")
|
|
1051
|
+
sql = f"UPDATE {tbl} SET {dcol} = {'CURRENT_TIMESTAMP' if kind == 'softDelete' else 'NULL'}{self._plain(where, ref)}"
|
|
1052
|
+
else:
|
|
1053
|
+
uv = unwrap(values)
|
|
1054
|
+
rows = o.array_items(uv)
|
|
1055
|
+
first = rows[0] if rows else uv
|
|
1056
|
+
obj = as_object(self.f, first, self.root) if first is not None else None
|
|
1057
|
+
if obj is None or not obj.entries:
|
|
1058
|
+
sql = f"INSERT INTO {tbl} ({mark('columns of ' + txt(uv))}) VALUES ({mark_node(uv)}){returning}"
|
|
1059
|
+
else:
|
|
1060
|
+
names = [self.q(ent.columns.get(k, k)) if ent else self.q(k) for k, _ in obj.entries]
|
|
1061
|
+
sql = f"INSERT INTO {tbl} ({', '.join(names)}) VALUES ({', '.join(o.value(v) for _, v in obj.entries)}){returning}"
|
|
1062
|
+
return o.make_site(self.f, top, txt(fn), self.engine, sql, top, library=NAME, table=ent.table if ent else raw_table,
|
|
1063
|
+
operation="queryBuilder." + kind, confidence=o.CONFIDENCE[self.level], notes=self.notes)
|
|
1064
|
+
|
|
1065
|
+
def _plain(self, where: str, ref: str) -> str:
|
|
1066
|
+
"""UPDATE / DELETE name the table, not the alias."""
|
|
1067
|
+
return where.replace(ref + ".", "")
|