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,565 @@
|
|
|
1
|
+
"""ent (entgo.io): the SQL a read chain stands for.
|
|
2
|
+
|
|
3
|
+
ent generates one package per entity (`ent/<entity>/<entity>.go`) holding the table and column names as constants
|
|
4
|
+
(`Table = "projects"`, `FieldOwnerID = "owner_id"`, `Columns`, and per edge `<Edge>Table`,
|
|
5
|
+
`<Edge>Column`, `<Edge>InverseTable`, `<Edge>PrimaryKey`), and one predicate function per field and operator in
|
|
6
|
+
`where.go` (`OwnerIDEQ`, `NameIn`, `CreatedAtGTE`, `DeletedAtIsNil`, `NameContains`). So a chain
|
|
7
|
+
|
|
8
|
+
s.db.Project.Query().Where(project.OwnerIDEQ(o), project.SlugEQ(k)).Only(ctx)
|
|
9
|
+
|
|
10
|
+
is translated from the names alone, without running ent:
|
|
11
|
+
|
|
12
|
+
SELECT "projects"."id", ... FROM "projects"
|
|
13
|
+
WHERE "projects"."owner_id" = $1 AND "projects"."slug" = $2 LIMIT 2
|
|
14
|
+
|
|
15
|
+
What is translated: `<client>.<Entity>.Query()` with Where (field predicates, And, Or, Not, Has<Edge>), Order
|
|
16
|
+
(`ent.Asc/Desc(field)`, `<entity>.By<Field>(sql.OrderDesc())`), Limit, Offset, Select, Unique; the terminals All,
|
|
17
|
+
Only (LIMIT 2, as ent asks for two rows to tell "one" from "several"), First (LIMIT 1), Count, Exist, IDs, OnlyID,
|
|
18
|
+
FirstID and their X forms; `<Entity>.Get(ctx, id)`; each `With<Edge>()` eager load as the extra statement ent runs
|
|
19
|
+
for it (one IN over the keys of the rows the first statement returned); a builder kept in a variable and narrowed
|
|
20
|
+
under an `if` (`q = q.Where(...)`), whose predicates are written as optional `AND («...»)` parts.
|
|
21
|
+
|
|
22
|
+
What is not, and is counted with its reason: graph traversals (`Query<Edge>()` on a query), GroupBy / Aggregate,
|
|
23
|
+
Modify, predicates written as `func(s *sql.Selector)`, an entity the generated code does not name. A predicate whose
|
|
24
|
+
field is not found is a «run-time part». Values are placeholders (`$n`, or `?` when the repository opens ent on
|
|
25
|
+
SQLite or MySQL). Confidence is "high" for a chain read whole, "medium" when a part was left as a run-time part.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import os
|
|
31
|
+
import re
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
|
|
34
|
+
from tree_sitter import Node
|
|
35
|
+
|
|
36
|
+
from .go import FUNC_DECL, GoFile, _strip_parens, _txt, _walk, call_args, callee_name
|
|
37
|
+
|
|
38
|
+
GENERATED = "Code generated by ent, DO NOT EDIT."
|
|
39
|
+
CONST = re.compile(r"^\s*(\w+)\s*=\s*\"([^\"]*)\"", re.M)
|
|
40
|
+
LIST = re.compile(r"(\w+)\s*=\s*\[\]string\{([^}]*)\}", re.S)
|
|
41
|
+
OPS = ("EqualFold", "ContainsFold", "Contains", "HasPrefix", "HasSuffix", "NotNil", "IsNil", "NotIn", "In", "NEQ", "GTE", "LTE",
|
|
42
|
+
"EQ", "GT", "LT")
|
|
43
|
+
TERMINAL_LIMIT = {"Only": 2, "OnlyX": 2, "OnlyID": 2, "OnlyIDX": 2, "First": 1, "FirstX": 1, "FirstID": 1, "FirstIDX": 1}
|
|
44
|
+
TERMINALS = {"All", "AllX", "Only", "OnlyX", "First", "FirstX", "Count", "CountX", "Exist", "ExistX", "IDs", "IDsX", "OnlyID",
|
|
45
|
+
"OnlyIDX", "FirstID", "FirstIDX", "Strings", "StringsX", "Ints", "IntsX", "String", "StringX", "Int", "IntX", "Scan", "ScanX"}
|
|
46
|
+
GETS = {"Get", "GetX"}
|
|
47
|
+
WRITE_BUILD = {"Create", "CreateBulk", "MapCreateBulk", "Update", "UpdateOne", "UpdateOneID", "Delete", "DeleteOne",
|
|
48
|
+
"DeleteOneID"}
|
|
49
|
+
WRITE_TERMINALS = {"Save", "SaveX", "Exec", "ExecX"}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Entity:
|
|
54
|
+
name: str # the Go type: APIKey
|
|
55
|
+
package: str # apikey
|
|
56
|
+
table: str
|
|
57
|
+
fields: dict[str, str] # CamelName -> column (ID -> id)
|
|
58
|
+
columns: list[str]
|
|
59
|
+
edges: dict[str, dict] = field(default_factory=dict) # Edge -> {table, column, inverse, pk}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Schema:
|
|
63
|
+
"""The entities of the ent packages in the repository, read from the generated constants."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, ctx):
|
|
66
|
+
self.by_package: dict[str, Entity] = {}
|
|
67
|
+
self.by_name: dict[str, Entity] = {}
|
|
68
|
+
self.dialect = "postgres"
|
|
69
|
+
texts: dict[str, str] = {}
|
|
70
|
+
for rel, gf in ctx.files.items():
|
|
71
|
+
if not rel.endswith(".go"):
|
|
72
|
+
continue
|
|
73
|
+
head = gf.src[:400].decode("utf-8", "replace")
|
|
74
|
+
if GENERATED not in head:
|
|
75
|
+
continue
|
|
76
|
+
pkg = os.path.basename(os.path.dirname(rel))
|
|
77
|
+
if os.path.basename(rel) == f"{pkg}.go":
|
|
78
|
+
texts[rel] = gf.src.decode("utf-8", "replace")
|
|
79
|
+
for rel, text in texts.items():
|
|
80
|
+
consts = dict(CONST.findall(text))
|
|
81
|
+
if "Table" not in consts:
|
|
82
|
+
continue
|
|
83
|
+
pkg = os.path.basename(os.path.dirname(rel))
|
|
84
|
+
fields = {k[len("Field"):]: v for k, v in consts.items() if k.startswith("Field")}
|
|
85
|
+
lists = {k: re.findall(r"\b(\w+)\b|\"([^\"]*)\"", body) for k, body in LIST.findall(text)}
|
|
86
|
+
|
|
87
|
+
def names(key: str) -> list[str]:
|
|
88
|
+
out = []
|
|
89
|
+
for ident, lit in lists.get(key) or []:
|
|
90
|
+
out.append(lit if lit else consts.get(ident, ""))
|
|
91
|
+
return [x for x in out if x]
|
|
92
|
+
cols = names("Columns") or list(fields.values())
|
|
93
|
+
edges: dict[str, dict] = {}
|
|
94
|
+
for k, v in consts.items():
|
|
95
|
+
if k.startswith("Edge") and k != "Edge":
|
|
96
|
+
e = k[len("Edge"):]
|
|
97
|
+
edges[e] = {"name": v, "table": consts.get(f"{e}Table", ""), "column": consts.get(f"{e}Column", ""),
|
|
98
|
+
"inverse": consts.get(f"{e}InverseTable", ""), "pk": names(f"{e}PrimaryKey")}
|
|
99
|
+
ent = Entity(name="", package=pkg, table=consts["Table"], fields=fields, columns=cols, edges=edges)
|
|
100
|
+
self.by_package[pkg] = ent
|
|
101
|
+
# the client's field for each entity is its Go type name; the package is that name in lower case
|
|
102
|
+
for rel, gf in ctx.files.items():
|
|
103
|
+
if os.path.basename(rel) != "client.go":
|
|
104
|
+
continue
|
|
105
|
+
text = gf.src.decode("utf-8", "replace")
|
|
106
|
+
if GENERATED not in text[:400]:
|
|
107
|
+
continue
|
|
108
|
+
for name, _ in re.findall(r"^\s*(\w+)\s+\*(\w+)Client\s*$", text, re.M):
|
|
109
|
+
ent = self.by_package.get(name.lower())
|
|
110
|
+
if ent is not None:
|
|
111
|
+
ent.name = name
|
|
112
|
+
self.by_name[name] = ent
|
|
113
|
+
if re.search(r"dialect\.(?:SQLite|MySQL)\b", text):
|
|
114
|
+
self.dialect = "sqlite" if "dialect.SQLite" in text else "mysql"
|
|
115
|
+
for ent in self.by_package.values():
|
|
116
|
+
if not ent.name:
|
|
117
|
+
self.by_name.setdefault(ent.package.capitalize(), ent)
|
|
118
|
+
# the driver the repository opens ent with decides the placeholders
|
|
119
|
+
for gf in ctx.files.values():
|
|
120
|
+
text = gf.src.decode("utf-8", "replace") if b"ent.Open" in gf.src or b"entsql.OpenDB" in gf.src else ""
|
|
121
|
+
m = re.search(r"(?:ent\.Open|entsql\.OpenDB)\s*\(\s*(?:dialect\.)?\"?(\w+)", text)
|
|
122
|
+
if m:
|
|
123
|
+
word = m.group(1).lower()
|
|
124
|
+
self.dialect = "sqlite" if word.startswith("sqlite") else "mysql" if word.startswith("mysql") else "postgres"
|
|
125
|
+
break
|
|
126
|
+
|
|
127
|
+
def __bool__(self) -> bool:
|
|
128
|
+
return bool(self.by_package)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class Untranslated(Exception):
|
|
132
|
+
pass
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Sql:
|
|
136
|
+
"""One statement as it is built: the placeholders are numbered in the order ent binds them."""
|
|
137
|
+
|
|
138
|
+
def __init__(self, ent: Entity, dialect: str):
|
|
139
|
+
self.ent, self.dialect = ent, dialect
|
|
140
|
+
self.where: list[str] = []
|
|
141
|
+
self.order: list[str] = []
|
|
142
|
+
self.limit = ""
|
|
143
|
+
self.offset = ""
|
|
144
|
+
self.select: list[str] = []
|
|
145
|
+
self.n = 0
|
|
146
|
+
self.notes: list[str] = []
|
|
147
|
+
self.partial = False
|
|
148
|
+
|
|
149
|
+
def q(self, name: str) -> str:
|
|
150
|
+
return f'"{name}"' if self.dialect == "postgres" else f"`{name}`" if self.dialect == "mysql" else name
|
|
151
|
+
|
|
152
|
+
def col(self, column: str, table: str = "") -> str:
|
|
153
|
+
return f"{self.q(table or self.ent.table)}.{self.q(column)}"
|
|
154
|
+
|
|
155
|
+
def ph(self) -> str:
|
|
156
|
+
self.n += 1
|
|
157
|
+
return f"${self.n}" if self.dialect == "postgres" else "?"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _pkg_of(gf: GoFile, alias: str, schema: Schema) -> Entity | None:
|
|
161
|
+
path = gf.imports.get(alias)
|
|
162
|
+
if path is None:
|
|
163
|
+
return None
|
|
164
|
+
return schema.by_package.get(path.rstrip("/").split("/")[-1])
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _field(ent: Entity, camel: str) -> str | None:
|
|
168
|
+
return ent.fields.get(camel)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _predicate(node: Node, s: Sql, gf: GoFile, schema: Schema, ent: Entity) -> str:
|
|
172
|
+
"""A predicate call as SQL; an unknown one is a run-time part."""
|
|
173
|
+
node = _strip_parens(node)
|
|
174
|
+
if node is None or node.type != "call_expression":
|
|
175
|
+
s.partial = True
|
|
176
|
+
return f"«{_txt(node)[:80] if node is not None else ''}»"
|
|
177
|
+
name, recv, _ = callee_name(node.child_by_field_name("function"))
|
|
178
|
+
args = call_args(node)
|
|
179
|
+
target = _pkg_of(gf, _txt(recv), schema) if recv is not None and recv.type == "identifier" else None
|
|
180
|
+
if target is None:
|
|
181
|
+
s.partial = True
|
|
182
|
+
return f"«{_txt(node)[:80]}»"
|
|
183
|
+
if name in ("And", "Or"):
|
|
184
|
+
parts = [_predicate(a, s, gf, schema, target) for a in args]
|
|
185
|
+
joined = f" {name.upper()} ".join(parts)
|
|
186
|
+
return f"({joined})" if len(parts) > 1 else joined
|
|
187
|
+
if name == "Not" and args:
|
|
188
|
+
return f"NOT ({_predicate(args[0], s, gf, schema, target)})"
|
|
189
|
+
if name.startswith("Has"):
|
|
190
|
+
return _has_edge(name, args, s, gf, schema, target)
|
|
191
|
+
for op in ("",) + OPS:
|
|
192
|
+
camel = name[: len(name) - len(op)] if op and name.endswith(op) else (name if not op else None)
|
|
193
|
+
if camel is None:
|
|
194
|
+
continue
|
|
195
|
+
column = _field(target, camel)
|
|
196
|
+
if column is None:
|
|
197
|
+
continue
|
|
198
|
+
c = s.col(column, target.table)
|
|
199
|
+
if op in ("", "EQ"):
|
|
200
|
+
return f"{c} = {s.ph()}"
|
|
201
|
+
if op == "NEQ":
|
|
202
|
+
return f"{c} <> {s.ph()}"
|
|
203
|
+
if op in ("GT", "GTE", "LT", "LTE"):
|
|
204
|
+
return f"{c} {dict(GT='>', GTE='>=', LT='<', LTE='<=')[op]} {s.ph()}"
|
|
205
|
+
if op in ("In", "NotIn"):
|
|
206
|
+
listed = ", ".join(s.ph() for a in args if a.type != "variadic_argument") if args and not any(
|
|
207
|
+
a.type == "variadic_argument" for a in args) else f"«{_txt(args[0])[:60] if args else ''}»"
|
|
208
|
+
return f"{c} {'NOT IN' if op == 'NotIn' else 'IN'} ({listed})"
|
|
209
|
+
if op == "IsNil":
|
|
210
|
+
return f"{c} IS NULL"
|
|
211
|
+
if op == "NotNil":
|
|
212
|
+
return f"{c} IS NOT NULL"
|
|
213
|
+
if op in ("Contains", "HasPrefix", "HasSuffix"):
|
|
214
|
+
return f"{c} LIKE {s.ph()}"
|
|
215
|
+
if op == "EqualFold":
|
|
216
|
+
return f"{c} ILIKE {s.ph()}" if s.dialect == "postgres" else f"lower({c}) = lower({s.ph()})"
|
|
217
|
+
if op == "ContainsFold":
|
|
218
|
+
return f"{c} ILIKE {s.ph()}" if s.dialect == "postgres" else f"lower({c}) LIKE lower({s.ph()})"
|
|
219
|
+
s.partial = True
|
|
220
|
+
return f"«{_txt(node)[:80]}»"
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _has_edge(name: str, args: list[Node], s: Sql, gf: GoFile, schema: Schema, ent: Entity) -> str:
|
|
224
|
+
"""Has<Edge>() / Has<Edge>With(preds...): an EXISTS on the edge's table (or a NOT NULL foreign key)."""
|
|
225
|
+
edge = name[len("Has"):]
|
|
226
|
+
with_ = edge.endswith("With")
|
|
227
|
+
if with_:
|
|
228
|
+
edge = edge[: -len("With")]
|
|
229
|
+
e = ent.edges.get(edge)
|
|
230
|
+
if e is None or not e["table"]:
|
|
231
|
+
s.partial = True
|
|
232
|
+
return f"«{name}(...)»"
|
|
233
|
+
id_col = ent.fields.get("ID", "id")
|
|
234
|
+
if e["pk"]: # many to many: through the join table
|
|
235
|
+
s.partial = s.partial or with_
|
|
236
|
+
return (f"EXISTS (SELECT 1 FROM {s.q(e['table'])} WHERE {s.col(e['pk'][0], e['table'])} = {s.col(id_col)})"
|
|
237
|
+
if not with_ else f"«{name}(...)»")
|
|
238
|
+
if e["table"] == ent.table: # the foreign key is in this table
|
|
239
|
+
if not with_:
|
|
240
|
+
return f"{s.col(e['column'])} IS NOT NULL"
|
|
241
|
+
s.partial = True
|
|
242
|
+
return f"«{name}(...)»"
|
|
243
|
+
inner = ""
|
|
244
|
+
if with_:
|
|
245
|
+
target = schema.by_package.get(next((p for p, x in schema.by_package.items() if x.table == e["table"]), ""))
|
|
246
|
+
if target is not None:
|
|
247
|
+
inner = "".join(" AND " + _predicate(a, s, gf, schema, target) for a in args)
|
|
248
|
+
return f"EXISTS (SELECT 1 FROM {s.q(e['table'])} WHERE {s.col(e['column'], e['table'])} = {s.col(id_col)}{inner})"
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _order(node: Node, s: Sql, gf: GoFile, schema: Schema) -> str:
|
|
252
|
+
"""ent.Desc(pkg.FieldX), ent.Asc(...), pkg.ByX(sql.OrderDesc())."""
|
|
253
|
+
node = _strip_parens(node)
|
|
254
|
+
if node is None or node.type != "call_expression":
|
|
255
|
+
s.partial = True
|
|
256
|
+
return f"«{_txt(node)[:60] if node is not None else ''}»"
|
|
257
|
+
name, recv, _ = callee_name(node.child_by_field_name("function"))
|
|
258
|
+
args = call_args(node)
|
|
259
|
+
if name in ("Asc", "Desc"):
|
|
260
|
+
out = []
|
|
261
|
+
for a in args:
|
|
262
|
+
if a.type == "selector_expression":
|
|
263
|
+
target = _pkg_of(gf, _txt(a.child_by_field_name("operand")), schema)
|
|
264
|
+
fld = _txt(a.child_by_field_name("field"))
|
|
265
|
+
col = _field(target, fld[len("Field"):]) if target is not None and fld.startswith("Field") else None
|
|
266
|
+
if col:
|
|
267
|
+
out.append(f"{s.col(col, target.table)}{' DESC' if name == 'Desc' else ''}")
|
|
268
|
+
continue
|
|
269
|
+
s.partial = True
|
|
270
|
+
out.append(f"«{_txt(a)[:60]}»")
|
|
271
|
+
return ", ".join(out)
|
|
272
|
+
if name.startswith("By") and recv is not None:
|
|
273
|
+
target = _pkg_of(gf, _txt(recv), schema)
|
|
274
|
+
col = _field(target, name[2:]) if target is not None else None
|
|
275
|
+
if col:
|
|
276
|
+
desc = any("OrderDesc" in _txt(a) for a in args)
|
|
277
|
+
return f"{s.col(col, target.table)}{' DESC' if desc else ''}"
|
|
278
|
+
s.partial = True
|
|
279
|
+
return f"«{_txt(node)[:60]}»"
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _builder_ops(gf: GoFile, root: Node, call: Node, schema: Schema, depth: int = 0) -> tuple[Entity, list, bool] | None:
|
|
283
|
+
"""(entity, ops from the Query() call outwards, whether some ops are conditional) for the chain's root: a
|
|
284
|
+
`<x>.<Entity>` selector, or a variable the builder was assigned to earlier in the function."""
|
|
285
|
+
if root is None or depth > 4:
|
|
286
|
+
return None
|
|
287
|
+
if root.type == "selector_expression":
|
|
288
|
+
fld = root.child_by_field_name("field")
|
|
289
|
+
ent = schema.by_name.get(_txt(fld)) if fld is not None else None
|
|
290
|
+
return (ent, [], False) if ent is not None else None
|
|
291
|
+
if root.type != "identifier":
|
|
292
|
+
return None
|
|
293
|
+
name = _txt(root)
|
|
294
|
+
func = gf._enclosing(call, FUNC_DECL)
|
|
295
|
+
if func is None:
|
|
296
|
+
return None
|
|
297
|
+
base = None
|
|
298
|
+
extra: list = []
|
|
299
|
+
conditional = False
|
|
300
|
+
from .orm_go import chain_of
|
|
301
|
+
for n in _walk(func):
|
|
302
|
+
if n.start_byte >= call.start_byte:
|
|
303
|
+
break
|
|
304
|
+
if n.type == "expression_statement" and base is not None and n.named_children:
|
|
305
|
+
# `upd.SetName(x)` on its own line: an ent builder's setters change the builder they are called on
|
|
306
|
+
value = _strip_parens(n.named_children[0])
|
|
307
|
+
if value is not None and value.type == "call_expression":
|
|
308
|
+
vroot, vops = chain_of(value)
|
|
309
|
+
if vroot is not None and vroot.type == "identifier" and _txt(vroot) == name and vops \
|
|
310
|
+
and not any(op in WRITE_TERMINALS or op in TERMINALS for op, _a, _c in vops):
|
|
311
|
+
under_if = any(p.type in ("if_statement", "for_statement", "expression_switch_statement")
|
|
312
|
+
for p in _ancestors(n, func))
|
|
313
|
+
extra += [(op, a, c, under_if) for op, a, c in vops]
|
|
314
|
+
conditional = conditional or under_if
|
|
315
|
+
continue
|
|
316
|
+
if n.type not in ("short_var_declaration", "assignment_statement"):
|
|
317
|
+
continue
|
|
318
|
+
left, right = n.child_by_field_name("left"), n.child_by_field_name("right")
|
|
319
|
+
if left is None or right is None or [_txt(x) for x in left.named_children] != [name] or not right.named_children:
|
|
320
|
+
continue
|
|
321
|
+
value = _strip_parens(right.named_children[0])
|
|
322
|
+
if value is None or value.type != "call_expression":
|
|
323
|
+
continue
|
|
324
|
+
vroot, vops = chain_of(value)
|
|
325
|
+
under_if = any(p.type == "if_statement" for p in _ancestors(n, func))
|
|
326
|
+
if vroot is not None and vroot.type == "identifier" and _txt(vroot) == name and base is not None:
|
|
327
|
+
extra += [(op, a, c, under_if) for op, a, c in vops]
|
|
328
|
+
conditional = conditional or under_if
|
|
329
|
+
else:
|
|
330
|
+
got = _builder_ops(gf, vroot, value, schema, depth + 1)
|
|
331
|
+
if got is not None:
|
|
332
|
+
base = (got[0], got[1] + [(op, a, c, False) for op, a, c in vops])
|
|
333
|
+
extra = []
|
|
334
|
+
if base is None:
|
|
335
|
+
return None
|
|
336
|
+
return base[0], base[1] + extra, conditional
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _ancestors(n: Node, top: Node):
|
|
340
|
+
p = n.parent
|
|
341
|
+
while p is not None and p.id != top.id:
|
|
342
|
+
yield p
|
|
343
|
+
p = p.parent
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _setter_column(ent: Entity, op: str) -> tuple[str, str] | None:
|
|
347
|
+
"""(column, how) for a builder setter: SetName / SetNillableName -> (name, set), AddCount -> (count, add),
|
|
348
|
+
ClearName -> (name, clear), SetOwnerID / SetOwner -> the edge's foreign key column when this table holds it."""
|
|
349
|
+
for prefix, how in (("SetNillable", "set"), ("SetOrClear", "set"), ("Set", "set"), ("Add", "add"), ("Clear", "clear")):
|
|
350
|
+
if not op.startswith(prefix) or len(op) == len(prefix):
|
|
351
|
+
continue
|
|
352
|
+
camel = op[len(prefix):]
|
|
353
|
+
col = ent.fields.get(camel)
|
|
354
|
+
if col is not None:
|
|
355
|
+
return col, how
|
|
356
|
+
for edge in (camel[:-2] if camel.endswith("ID") else "", camel):
|
|
357
|
+
e = ent.edges.get(edge) if edge else None
|
|
358
|
+
if e is not None and e["table"] == ent.table and e["column"] and not e["pk"]:
|
|
359
|
+
return e["column"], "clear" if how == "clear" else "set"
|
|
360
|
+
return None
|
|
361
|
+
return None
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _write(schema: Schema, gf: GoFile, ent: Entity, chain: list) -> list[tuple[str, str, str, list[str]]]: # noqa: C901
|
|
365
|
+
"""INSERT / UPDATE / DELETE for `<client>.<Entity>.Create()...Save(ctx)` and the other write builders."""
|
|
366
|
+
start = chain[0][0]
|
|
367
|
+
s = Sql(ent, schema.dialect)
|
|
368
|
+
id_col = ent.fields.get("ID", "id")
|
|
369
|
+
sets: list[tuple[str, str]] = [] # (column, SQL after `col = `)
|
|
370
|
+
optional: list[str] = []
|
|
371
|
+
notes: list[str] = []
|
|
372
|
+
conflict = ""
|
|
373
|
+
for op, args, _c, cond in chain[1:-1]:
|
|
374
|
+
if op == "Where":
|
|
375
|
+
parts = [_predicate(a, s, gf, schema, ent) for a in args]
|
|
376
|
+
s.where += [f"(«{p}»)" if cond and not p.startswith("«") else p for p in parts]
|
|
377
|
+
continue
|
|
378
|
+
got = _setter_column(ent, op)
|
|
379
|
+
if got is not None:
|
|
380
|
+
col, how = got
|
|
381
|
+
if cond:
|
|
382
|
+
optional.append(col)
|
|
383
|
+
continue
|
|
384
|
+
value = "NULL" if how == "clear" else (f"{s.q(col)} + {s.ph()}" if how == "add" else s.ph())
|
|
385
|
+
sets = [x for x in sets if x[0] != col] + [(col, value)]
|
|
386
|
+
continue
|
|
387
|
+
if op == "OnConflict" or op.startswith("OnConflict"):
|
|
388
|
+
conflict = " ON CONFLICT «" + "".join(_txt(a)[:40] for a in args) + "»" if args else " ON CONFLICT"
|
|
389
|
+
continue
|
|
390
|
+
if op in ("UpdateNewValues", "Ignore", "DoNothing", "UpdateAll"):
|
|
391
|
+
conflict = (conflict or " ON CONFLICT") + (" DO NOTHING" if op in ("Ignore", "DoNothing") else " DO UPDATE SET «the new values»")
|
|
392
|
+
continue
|
|
393
|
+
if op.startswith(("Add", "Remove", "Clear", "Set")) and op.endswith(("IDs", "s")) and not op.startswith("Set"):
|
|
394
|
+
notes.append(f"{op}: the edge rows ent writes in its own statements are not shown")
|
|
395
|
+
continue
|
|
396
|
+
if op in ("Mutation", "SetInput", "Schema", "Comment"):
|
|
397
|
+
notes.append(f"{op}(...) not read")
|
|
398
|
+
s.partial = True
|
|
399
|
+
continue
|
|
400
|
+
notes.append(f"{op}(...) not read")
|
|
401
|
+
s.partial = True
|
|
402
|
+
if optional:
|
|
403
|
+
notes.append("setters under an if are optional: " + ", ".join(dict.fromkeys(optional)))
|
|
404
|
+
for col in dict.fromkeys(optional):
|
|
405
|
+
if col not in [c for c, _ in sets]:
|
|
406
|
+
sets.append((col, f"{s.ph()} /* optional */"))
|
|
407
|
+
table = s.q(ent.table)
|
|
408
|
+
returning = f" RETURNING {s.q(id_col)}" if schema.dialect == "postgres" else ""
|
|
409
|
+
if start in ("Create", "CreateBulk", "MapCreateBulk"):
|
|
410
|
+
if start != "Create":
|
|
411
|
+
s.partial = True
|
|
412
|
+
notes.append(f"{start}: one row per builder; the fields each builder sets are not read here")
|
|
413
|
+
return [(f"INSERT INTO {table} («columns») VALUES («rows»){returning}", "insert", ent.table, notes)]
|
|
414
|
+
if not sets:
|
|
415
|
+
s.partial = True
|
|
416
|
+
notes.append("no setter in the chain: the fields are set elsewhere")
|
|
417
|
+
return [(f"INSERT INTO {table} («columns») VALUES («values»){conflict}{returning}", "insert", ent.table, notes)]
|
|
418
|
+
cols = ", ".join(s.q(c) for c, _ in sets)
|
|
419
|
+
vals = ", ".join(v.replace(" /* optional */", "") for _, v in sets)
|
|
420
|
+
notes.append("fields with a default in the schema are added by ent when not set")
|
|
421
|
+
return [(f"INSERT INTO {table} ({cols}) VALUES ({vals}){conflict}{returning}", "insert", ent.table,
|
|
422
|
+
notes + (["partly a run-time part"] if s.partial else []))]
|
|
423
|
+
if start in ("Update", "UpdateOne", "UpdateOneID"):
|
|
424
|
+
if not sets:
|
|
425
|
+
s.partial = True
|
|
426
|
+
set_sql = "«the fields set at run time» = " + s.ph()
|
|
427
|
+
else:
|
|
428
|
+
set_sql = ", ".join(f"{s.q(c)} = {v}" for c, v in sets)
|
|
429
|
+
if start == "UpdateOneID" or start == "UpdateOne":
|
|
430
|
+
s.where.insert(0, f"{s.col(id_col)} = {s.ph()}")
|
|
431
|
+
where = (" WHERE " + " AND ".join(s.where)) if s.where else ""
|
|
432
|
+
ret = f" RETURNING {_columns(ent, s)}" if start != "Update" and schema.dialect == "postgres" else ""
|
|
433
|
+
if start != "Update":
|
|
434
|
+
notes.append(f"{start}: ent updates the row by its id and returns it")
|
|
435
|
+
return [(f"UPDATE {table} SET {set_sql}{where}{ret}", "update", ent.table,
|
|
436
|
+
notes + (["partly a run-time part"] if s.partial else []))]
|
|
437
|
+
# deletes
|
|
438
|
+
if start in ("DeleteOne", "DeleteOneID"):
|
|
439
|
+
s.where.insert(0, f"{s.col(id_col)} = {s.ph()}")
|
|
440
|
+
where = (" WHERE " + " AND ".join(s.where)) if s.where else ""
|
|
441
|
+
return [(f"DELETE FROM {table}{where}", "delete", ent.table, notes + (["partly a run-time part"] if s.partial else []))]
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _columns(ent: Entity, s: Sql) -> str:
|
|
445
|
+
cols = s.select or [s.col(c) for c in ent.columns]
|
|
446
|
+
return ", ".join(cols)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def translate(schema: Schema, gf: GoFile, call: Node, root: Node, ops: list) -> list[tuple[str, str, str, list[str]]]:
|
|
450
|
+
"""[(sql, operation, target, notes)] for one terminal call of a chain; raises Untranslated with the reason."""
|
|
451
|
+
terminal = ops[-1][0]
|
|
452
|
+
if terminal in GETS:
|
|
453
|
+
got = _builder_ops(gf, root, call, schema)
|
|
454
|
+
if got is None:
|
|
455
|
+
raise Untranslated("the entity of the client is not known")
|
|
456
|
+
ent = got[0]
|
|
457
|
+
s = Sql(ent, schema.dialect)
|
|
458
|
+
s.where.append(f"{s.col(ent.fields.get('ID', 'id'))} = {s.ph()}")
|
|
459
|
+
return [(f"SELECT {_columns(ent, s)} FROM {s.q(ent.table)} WHERE {s.where[0]} LIMIT 2", "select", ent.table,
|
|
460
|
+
["Get: ent reads the row by its id and asks for two rows"])]
|
|
461
|
+
chain = [(op, a, c, False) for op, a, c in ops]
|
|
462
|
+
if chain and chain[0][0] in WRITE_BUILD:
|
|
463
|
+
got = _builder_ops(gf, root, call, schema)
|
|
464
|
+
if got is None:
|
|
465
|
+
raise Untranslated("the entity of the client is not known")
|
|
466
|
+
return _write(schema, gf, got[0], chain)
|
|
467
|
+
if chain and chain[0][0] != "Query" and root is not None and root.type == "identifier":
|
|
468
|
+
got = _builder_ops(gf, root, call, schema)
|
|
469
|
+
if got is not None and got[1] and got[1][0][0] in WRITE_BUILD:
|
|
470
|
+
return _write(schema, gf, got[0], [(op, a, c, cond) for op, a, c, cond in got[1]] + chain)
|
|
471
|
+
if chain and chain[0][0] == "Query":
|
|
472
|
+
got = _builder_ops(gf, root, call, schema)
|
|
473
|
+
if got is None:
|
|
474
|
+
raise Untranslated("the entity of the client is not known")
|
|
475
|
+
ent, before, conditional = got
|
|
476
|
+
chain = chain[1:]
|
|
477
|
+
else:
|
|
478
|
+
got = _builder_ops(gf, root, call, schema)
|
|
479
|
+
if got is None:
|
|
480
|
+
raise Untranslated("the builder is not a <client>.<Entity>.Query() the function assigns")
|
|
481
|
+
ent, before, conditional = got
|
|
482
|
+
if not before or before[0][0] != "Query":
|
|
483
|
+
raise Untranslated("the builder is not a <client>.<Entity>.Query() the function assigns")
|
|
484
|
+
chain = before[1:] + chain
|
|
485
|
+
s = Sql(ent, schema.dialect)
|
|
486
|
+
eager: list[tuple[str, list]] = []
|
|
487
|
+
unique = None
|
|
488
|
+
for op, args, _c, cond in chain[:-1]:
|
|
489
|
+
if op == "Where":
|
|
490
|
+
parts = [_predicate(a, s, gf, schema, ent) for a in args]
|
|
491
|
+
if cond:
|
|
492
|
+
s.where += [f"(«{p}»)" if not p.startswith("«") else p for p in parts]
|
|
493
|
+
s.notes.append("a Where under an if is an optional part")
|
|
494
|
+
else:
|
|
495
|
+
s.where += parts
|
|
496
|
+
elif op == "Order":
|
|
497
|
+
s.order += [_order(a, s, gf, schema) for a in args]
|
|
498
|
+
elif op in ("Limit", "Offset"):
|
|
499
|
+
v = _txt(args[0]) if args else ""
|
|
500
|
+
text = v if re.fullmatch(r"\d+", v) else f"«{v[:40]}»"
|
|
501
|
+
if op == "Limit":
|
|
502
|
+
s.limit = text
|
|
503
|
+
else:
|
|
504
|
+
s.offset = text
|
|
505
|
+
elif op == "Select":
|
|
506
|
+
for a in args:
|
|
507
|
+
if a.type == "selector_expression":
|
|
508
|
+
target = _pkg_of(gf, _txt(a.child_by_field_name("operand")), schema)
|
|
509
|
+
fld = _txt(a.child_by_field_name("field"))
|
|
510
|
+
col = _field(target, fld[len("Field"):]) if target is not None and fld.startswith("Field") else None
|
|
511
|
+
if col:
|
|
512
|
+
s.select.append(s.col(col, target.table))
|
|
513
|
+
continue
|
|
514
|
+
s.partial = True
|
|
515
|
+
s.select.append(f"«{_txt(a)[:40]}»")
|
|
516
|
+
elif op == "Unique":
|
|
517
|
+
unique = _txt(args[0]) if args else "true"
|
|
518
|
+
elif op.startswith("With") and op[4:] in ent.edges:
|
|
519
|
+
eager.append((op[4:], args))
|
|
520
|
+
elif op in ("ForUpdate", "ForShare"):
|
|
521
|
+
s.notes.append(f"{op}: a locking read")
|
|
522
|
+
elif op.startswith("Query") and op != "Query":
|
|
523
|
+
raise Untranslated("a graph traversal (Query<Edge>) is not translated")
|
|
524
|
+
elif op in ("GroupBy", "Aggregate", "Modify"):
|
|
525
|
+
raise Untranslated(f"{op} is not translated")
|
|
526
|
+
else:
|
|
527
|
+
s.partial = True
|
|
528
|
+
s.notes.append(f"{op}(...) not read")
|
|
529
|
+
where = (" WHERE " + " AND ".join(s.where)) if s.where else ""
|
|
530
|
+
order = (" ORDER BY " + ", ".join(s.order)) if s.order else ""
|
|
531
|
+
limit = s.limit or (str(TERMINAL_LIMIT[terminal]) if terminal in TERMINAL_LIMIT else "")
|
|
532
|
+
tail = order + (f" LIMIT {limit}" if limit else "") + (f" OFFSET {s.offset}" if s.offset else "")
|
|
533
|
+
table = s.q(ent.table)
|
|
534
|
+
id_col = s.col(ent.fields.get("ID", "id"))
|
|
535
|
+
if terminal.startswith("Count"):
|
|
536
|
+
sql = f"SELECT COUNT(*) FROM {table}{where}"
|
|
537
|
+
elif terminal.startswith("Exist"):
|
|
538
|
+
sql = f"SELECT 1 FROM {table}{where} LIMIT 1"
|
|
539
|
+
elif terminal.startswith(("IDs", "OnlyID", "FirstID")):
|
|
540
|
+
sql = f"SELECT {id_col} FROM {table}{where}{tail}"
|
|
541
|
+
else:
|
|
542
|
+
distinct = "DISTINCT " if unique == "true" else ""
|
|
543
|
+
sql = f"SELECT {distinct}{_columns(ent, s)} FROM {table}{where}{tail}"
|
|
544
|
+
notes = list(dict.fromkeys(s.notes))
|
|
545
|
+
if terminal in ("Only", "OnlyX", "OnlyID", "OnlyIDX") and not s.limit:
|
|
546
|
+
notes.append("Only: ent asks for two rows to tell one from several")
|
|
547
|
+
out = [(sql, "select", ent.table, notes + (["partly a run-time part"] if s.partial else []))]
|
|
548
|
+
for edge, eargs in eager:
|
|
549
|
+
e = ent.edges[edge]
|
|
550
|
+
target = next((x for x in schema.by_package.values() if x.table == (e["inverse"] if e["table"] == ent.table or e["pk"] else e["table"])), None)
|
|
551
|
+
if target is None:
|
|
552
|
+
continue
|
|
553
|
+
es = Sql(target, schema.dialect)
|
|
554
|
+
if e["pk"]:
|
|
555
|
+
sqlx = (f"SELECT {_columns(target, es)}, {es.col(e['pk'][0], e['table'])} FROM {es.q(target.table)} JOIN {es.q(e['table'])} "
|
|
556
|
+
f"ON {es.col(e['pk'][1], e['table'])} = {es.col(target.fields.get('ID', 'id'))} "
|
|
557
|
+
f"WHERE {es.col(e['pk'][0], e['table'])} IN («ids of the {ent.table} rows»)")
|
|
558
|
+
elif e["table"] == ent.table:
|
|
559
|
+
sqlx = f"SELECT {_columns(target, es)} FROM {es.q(target.table)} WHERE {es.col(target.fields.get('ID', 'id'))} IN («{e['column']} of the {ent.table} rows»)"
|
|
560
|
+
else:
|
|
561
|
+
sqlx = f"SELECT {_columns(target, es)} FROM {es.q(target.table)} WHERE {es.col(e['column'])} IN («ids of the {ent.table} rows»)"
|
|
562
|
+
if eargs:
|
|
563
|
+
sqlx += " AND («the With" + edge + " options»)"
|
|
564
|
+
out.append((sqlx, "select", target.table, [f"With{edge}: the eager load ent runs after the first statement"]))
|
|
565
|
+
return out
|