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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,697 @@
1
+ """Drizzle builder chains and relational queries as SQL sites.
2
+
3
+ Tables are read from their definitions (`export const users = pgTable("users", { id: serial("id"), ... })`): the
4
+ variable, the table name, each key's column name and the dialect. A chain is recognised by the table it names:
5
+ `db.select(...).from(users)`, `db.insert(users)`, `db.update(users)`, `db.delete(users)`, and
6
+ `db.query.users.findMany({...})`. Conditions are the operator helpers (`eq`, `and`, `or`, `inArray`, `isNull`,
7
+ `like`, `between`, `exists`, ...) and sql`...` fragments.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+
15
+ from tree_sitter import Node
16
+
17
+ from . import orm_ts as o
18
+ from .orm_ts import as_object, mark, mark_node, txt, unwrap
19
+ from .orm_ts_schema import climb, spine
20
+
21
+ NAME = "drizzle"
22
+ DEFINERS = {"pgTable": "postgres", "mysqlTable": "mysql", "sqliteTable": "sqlite", "singlestoreTable": "mysql",
23
+ "cockroachTable": "postgres", "gelTable": "postgres"}
24
+ _TABLE = re.compile(
25
+ r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:[\w$]+\.)?(pgTable|mysqlTable|sqliteTable|singlestoreTable|cockroachTable|"
26
+ r"gelTable|[\w$]*[sS]chema\.table|table)\s*(?:<[^>]*>)?\(\s*(['\"`])([\w.$-]+)\3\s*,\s*(?=\{)")
27
+ _COLUMN = re.compile(r"^\s*(?:['\"]?)([\w$]+)(?:['\"]?)\s*:\s*([\w.$]+)\s*(?:<[^>]*>)?\(\s*(?:(['\"`])([^'\"`]*)\3)?")
28
+ _COMMENT = re.compile(r"""("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)|//[^\n]*|/\*.*?\*/""", re.S)
29
+ _RELATIONS = re.compile(r"\brelations\(\s*([\w$.]+)\s*,")
30
+ PRE = re.compile(rb"\.\s*(?:select|selectDistinct|selectDistinctOn|insert|update|delete)\s*\(|\.query\s*\.\s*[\w$]+\s*\.\s*(?:findMany|findFirst)\s*\(")
31
+ ROOTS = {"select": "select", "selectDistinct": "select", "selectDistinctOn": "select", "insert": "insert", "update": "update",
32
+ "delete": "delete"}
33
+ COMPARE = {"eq": "=", "ne": "<>", "gt": ">", "gte": ">=", "lt": "<", "lte": "<=", "like": "LIKE", "notLike": "NOT LIKE",
34
+ "ilike": "ILIKE", "notIlike": "NOT ILIKE", "arrayContains": "@>", "arrayContained": "<@", "arrayOverlaps": "&&"}
35
+ AGG = {"count": "COUNT", "countDistinct": "COUNT", "sum": "SUM", "sumDistinct": "SUM", "avg": "AVG", "avgDistinct": "AVG",
36
+ "min": "MIN", "max": "MAX"}
37
+ JOINS = {"innerJoin": "INNER JOIN", "leftJoin": "LEFT JOIN", "rightJoin": "RIGHT JOIN", "fullJoin": "FULL JOIN",
38
+ "crossJoin": "CROSS JOIN", "innerJoinLateral": "INNER JOIN LATERAL", "leftJoinLateral": "LEFT JOIN LATERAL"}
39
+ TERMINAL = {"execute", "then", "all", "get", "run", "prepare", "catch", "finally", "iterator", "toSQL"}
40
+ NO_OP = {"$dynamic", "$withCache", "as", "getSQL", "$type"} | TERMINAL
41
+
42
+
43
+ class Table:
44
+ __slots__ = ("var", "name", "rel", "columns", "engine", "relations")
45
+
46
+ def __init__(self, var: str, name: str, rel: str, engine: str):
47
+ self.var, self.name, self.rel, self.engine = var, name, rel, engine
48
+ self.columns: dict[str, str] = {}
49
+ self.relations: dict[str, dict] = {} # name -> {kind, target var, fields, references}
50
+
51
+
52
+ def read_tables(rel: str, text: str) -> list[Table]:
53
+ from .schema_ts import _balanced, _split_top
54
+ out = []
55
+ for m in _TABLE.finditer(text):
56
+ end = _balanced(text, m.end(), "{", "}")
57
+ if end < 0:
58
+ continue
59
+ t = Table(m.group(1), m.group(4), rel, DEFINERS.get(m.group(2), ""))
60
+ body = _COMMENT.sub(lambda c: c.group(1) or " ", text[m.end() + 1: end - 1]) # a comment may hold commas
61
+ for part in _split_top(body):
62
+ cm = _COLUMN.match(part)
63
+ if cm:
64
+ key, _ctype, _q, db_name = cm.groups()
65
+ t.columns[key] = db_name if db_name and re.fullmatch(r"[\w$]+", db_name) else key
66
+ if t.columns:
67
+ out.append(t)
68
+ return out
69
+
70
+
71
+ class Library:
72
+ name = NAME
73
+
74
+ def __init__(self, ctx, root, files, stats):
75
+ self.ctx, self.stats = ctx, stats
76
+ self.active = True
77
+ self.tables: dict[str, list[Table]] = {}
78
+ self.relation_texts: list[tuple[str, str]] = []
79
+ self.maybe: list[str] = [] # files with builder-shaped calls in packages that do not list drizzle-orm
80
+ self.snake = False # drizzle({ casing: "snake_case" }): keys are sent snake_case
81
+
82
+ def wants(self, rel: str, src: bytes, deps) -> bool:
83
+ if (b"Table(" in src or b".table(" in src) and (b"drizzle-orm" in src or b".table(" in src):
84
+ text = src.decode("utf-8", "replace")
85
+ try:
86
+ for t in read_tables(rel, text):
87
+ self.tables.setdefault(t.var, []).append(t)
88
+ except Exception:
89
+ pass
90
+ if "relations(" in text:
91
+ self.relation_texts.append((rel, text))
92
+ elif b"relations(" in src and b"drizzle-orm" in src:
93
+ self.relation_texts.append((rel, src.decode("utf-8", "replace")))
94
+ if b"casing" in src and b"snake_case" in src and b"drizzle" in src:
95
+ self.snake = True
96
+ if not PRE.search(src):
97
+ return False
98
+ if "drizzle-orm" in deps or b"drizzle-orm" in src:
99
+ return True
100
+ self.maybe.append(rel) # a package that uses the schema of another: taken when tables were read
101
+ return False
102
+
103
+ def prepare(self, wanted) -> None:
104
+ from .schema_ts import _balanced, _split_top
105
+ if self.tables:
106
+ for rel in self.maybe:
107
+ wanted.setdefault(rel, set()).add(NAME)
108
+ if self.snake:
109
+ for ts in self.tables.values():
110
+ for t in ts:
111
+ t.columns = {k: (re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", v).lower() if v == k else v) for k, v in t.columns.items()}
112
+ for rel, text in self.relation_texts:
113
+ for m in _RELATIONS.finditer(text):
114
+ owner = self.table(m.group(1).split(".")[-1], rel)
115
+ arrow = text.find("=>", m.end())
116
+ brace = text.find("{", arrow) if arrow >= 0 else -1
117
+ if owner is None or brace < 0:
118
+ continue
119
+ end = _balanced(text, brace, "{", "}")
120
+ if end < 0:
121
+ continue
122
+ for part in _split_top(text[brace + 1: end - 1]):
123
+ pm = re.match(r"\s*([\w$]+)\s*:\s*(one|many)\(\s*([\w$.]+)\s*(?:,\s*\{([\s\S]*)\})?", part)
124
+ if not pm:
125
+ continue
126
+ body = pm.group(4) or ""
127
+ fields = re.search(r"fields\s*:\s*\[([^\]]*)\]", body)
128
+ refs = re.search(r"references\s*:\s*\[([^\]]*)\]", body)
129
+ owner.relations[pm.group(1)] = {
130
+ "kind": pm.group(2), "target": pm.group(3).split(".")[-1],
131
+ "fields": re.findall(r"[\w$]+\.([\w$]+)", fields.group(1)) if fields else [],
132
+ "references": re.findall(r"[\w$]+\.([\w$]+)", refs.group(1)) if refs else [],
133
+ "name": (re.search(r"relationName\s*:\s*['\"]([^'\"]+)", body) or [None, ""])[1]}
134
+
135
+ def table(self, var: str, rel: str) -> Table | None:
136
+ # `import { sites as sitesTable } from "../db/schema"`: the local alias stands for the exported table
137
+ var = self._alias.get(var, var) if rel == self._alias_rel else var
138
+ cands = self.tables.get(var)
139
+ if not cands:
140
+ return None
141
+ if len(cands) == 1 or len({c.name for c in cands}) == 1:
142
+ return cands[0]
143
+ a = rel.split("/")
144
+ scored = sorted(((next((i for i, (x, y) in enumerate(zip(a, c.rel.split("/"))) if x != y), 0), c) for c in cands),
145
+ key=lambda s: -s[0])
146
+ return scored[0][1] if scored[0][0] > scored[1][0] else None
147
+
148
+ def table_of(self, node: Node | None, rel: str) -> Table | None:
149
+ node = unwrap(node)
150
+ if node is None:
151
+ return None
152
+ if node.type == "identifier":
153
+ return self.table(txt(node), rel)
154
+ if node.type == "member_expression":
155
+ return self.table(txt(node.child_by_field_name("property")), rel)
156
+ return None
157
+
158
+ _alias: dict = {}
159
+ _alias_rel = ""
160
+
161
+ def sites(self, f) -> list:
162
+ self._alias_rel = f.rel
163
+ self._alias = {local: name for local, (_spec, name) in f.imports.items()
164
+ if name not in ("*", "default") and local != name and name in self.tables}
165
+ out = []
166
+ consumed: set[int] = set()
167
+ found = []
168
+ for call in f.calls:
169
+ fn = unwrap(call.child_by_field_name("function"))
170
+ if fn is None or fn.type != "member_expression":
171
+ continue
172
+ name = txt(fn.child_by_field_name("property"))
173
+ args_node = call.child_by_field_name("arguments")
174
+ if args_node is None or args_node.type != "arguments":
175
+ continue
176
+ args = [a for a in args_node.named_children if a.type != "comment"]
177
+ if name in ("findMany", "findFirst"):
178
+ holder = unwrap(fn.child_by_field_name("object"))
179
+ if holder is not None and holder.type == "member_expression" and \
180
+ txt(unwrap(holder.child_by_field_name("object"))).endswith(".query") and \
181
+ (b"drizzle" in f.src or self.table(txt(holder.child_by_field_name("property")), f.rel) is not None):
182
+ found.append(("query", call, call, args, txt(holder.child_by_field_name("property"))))
183
+ continue
184
+ if name not in ROOTS:
185
+ continue
186
+ top = climb(call)
187
+ _b, steps = spine(top)
188
+ idx = next((i for i, s in enumerate(steps) if s[2].id == call.id), None)
189
+ if idx is None:
190
+ continue
191
+ post = steps[idx + 1:]
192
+ if ROOTS[name] == "select":
193
+ from_step = next((s for s in post if s[0] == "from" and s[1]), None)
194
+ if from_step is None:
195
+ continue
196
+ target = from_step[1][0]
197
+ # a table of the schema, or a subquery / CTE held in a variable in a file that uses Drizzle
198
+ if self.table_of(target, f.rel) is None and not (b"drizzle" in f.src and unwrap(target).type in ("identifier", "call_expression")):
199
+ continue
200
+ else:
201
+ if not args or (self.table_of(args[0], f.rel) is None and not (b"drizzle-orm" in f.src)):
202
+ continue
203
+ if name == "delete" and self.table_of(args[0], f.rel) is None:
204
+ continue
205
+ if name in ("insert", "update") and self.table_of(args[0], f.rel) is None and \
206
+ not any(s[0] in ("values", "set") for s in post):
207
+ continue
208
+ found.append((ROOTS[name], call, top, args, name))
209
+ for kind, call, top, args, name in sorted(found, key=lambda r: (r[1].start_byte, -(r[2].end_byte - r[2].start_byte))):
210
+ self.stats.see(NAME, f.test)
211
+ if call.id in consumed:
212
+ self.stats.ok(NAME, f.test, 0)
213
+ continue
214
+ line = call.start_point[0] + 1
215
+ st = Statement(self, f, call, top, consumed)
216
+ try:
217
+ sql = st.relational(name, args) if kind == "query" else st.chain(kind, name, args)
218
+ except Skip as e:
219
+ self.stats.miss(NAME, f.test, str(e), f.rel, line)
220
+ continue
221
+ except Exception as e:
222
+ if os.environ.get("CODECOP_ORM_DEBUG"):
223
+ raise
224
+ self.stats.miss(NAME, f.test, f"internal error ({type(e).__name__})", f.rel, line)
225
+ continue
226
+ self.stats.ok(NAME, f.test, 1)
227
+ out.append(o.make_site(f, top, txt(call.child_by_field_name("function")), st.engine, sql, top, library=NAME,
228
+ table=st.main, operation=("query." + name) if kind == "query" else kind,
229
+ confidence=o.CONFIDENCE[st.level], notes=st.notes))
230
+ return out
231
+
232
+
233
+ class Skip(Exception):
234
+ pass
235
+
236
+
237
+ class Statement:
238
+ def __init__(self, lib: Library, f, root: Node, top: Node, consumed: set[int], parent: "Statement | None" = None):
239
+ self.lib, self.f, self.root, self.top, self.consumed, self.parent = lib, f, root, top, consumed, parent
240
+ self.engine = parent.engine if parent is not None else o.engine_of(f)
241
+ self.notes: list[str] = parent.notes if parent is not None else []
242
+ self._level = 2
243
+ self.main = ""
244
+ self.alias = ""
245
+ self.locals: dict[str, Table] = {} # callback parameters that stand for a table
246
+
247
+ @property
248
+ def level(self) -> int:
249
+ return self._level
250
+
251
+ def lower(self, level: int, note: str) -> None:
252
+ top = self
253
+ while top.parent is not None:
254
+ top = top.parent
255
+ top._level = min(top._level, level)
256
+ if note not in self.notes:
257
+ self.notes.append(note)
258
+
259
+ def q(self, name: str) -> str:
260
+ return o.quote(self.engine, name)
261
+
262
+ def tname(self, t: Table) -> str:
263
+ return o.qname(self.engine, t.name)
264
+
265
+ def use(self, t: Table) -> None:
266
+ if t.engine and self.parent is None and not self.main:
267
+ self.engine = t.engine
268
+ if not self.main:
269
+ self.main = t.name
270
+
271
+ # -- expressions ---------------------------------------------------------------------
272
+ def column(self, node: Node) -> str | None:
273
+ """`users.id` -> "users"."id" when `users` is a table (or a callback parameter standing for one)."""
274
+ if node.type != "member_expression":
275
+ return None
276
+ obj = unwrap(node.child_by_field_name("object"))
277
+ prop = txt(node.child_by_field_name("property"))
278
+ if obj is None:
279
+ return None
280
+ t = self.locals.get(txt(obj)) if obj.type == "identifier" else None
281
+ if t is None:
282
+ t = self.lib.table_of(obj, self.f.rel)
283
+ if t is None or prop not in t.columns:
284
+ return None
285
+ return f"{self.tname(t)}.{self.q(t.columns[prop])}"
286
+
287
+ def template(self, node: Node) -> str | None:
288
+ try:
289
+ res = self.f.resolve(node, self.root, 0)
290
+ except Exception:
291
+ res = None
292
+ if res is None or not res.text.strip():
293
+ return None
294
+ return self.columns_in(res.text.strip())
295
+
296
+ def columns_in(self, text: str) -> str:
297
+ def swap(m: re.Match) -> str: # ${users.id} inside sql`...` is a column, not a value
298
+ inner = m.group(1)
299
+ mm = re.fullmatch(r"([\w$]+)\.([\w$]+)", inner)
300
+ if mm:
301
+ t = self.locals.get(mm.group(1)) or self.lib.table(mm.group(1), self.f.rel)
302
+ if t is not None and mm.group(2) in t.columns:
303
+ return f"{self.tname(t)}.{self.q(t.columns[mm.group(2)])}"
304
+ t = self.lib.table(inner, self.f.rel) if re.fullmatch(r"[\w$]+", inner) else None
305
+ return self.tname(t) if t is not None else m.group(0)
306
+ return re.sub(r"«([^»]*)»", swap, text)
307
+
308
+ def sub(self, node: Node | None) -> tuple[str, str] | None:
309
+ node = unwrap(node)
310
+ if node is None or node.type != "call_expression":
311
+ return None
312
+ _b, steps = spine(node)
313
+ for name, args, call in steps:
314
+ if name in ROOTS:
315
+ st = Statement(self.lib, self.f, call, node, self.consumed, parent=self)
316
+ st.locals = dict(self.locals)
317
+ sql = st.chain(ROOTS[name], name, args)
318
+ self.consumed.add(call.id)
319
+ return sql, st.alias
320
+ return None
321
+
322
+ def expr(self, node: Node | None) -> str:
323
+ node = unwrap(node)
324
+ if node is None:
325
+ return mark("?")
326
+ lit = o.literal(node)
327
+ if lit is not None:
328
+ return lit
329
+ t = node.type
330
+ if t == "member_expression":
331
+ return self.column(node) or mark_node(node)
332
+ if t in ("arrow_function", "function_expression"):
333
+ body = o.callback_body(node)
334
+ return self.expr(body) if body is not None else mark_node(node)
335
+ if t == "call_expression":
336
+ args_node = node.child_by_field_name("arguments")
337
+ if args_node is not None and args_node.type == "template_string":
338
+ return self.template(node) or mark_node(node)
339
+ got = self.sub(node)
340
+ if got is not None:
341
+ return f"({got[0]})"
342
+ fn = unwrap(node.child_by_field_name("function"))
343
+ args = [a for a in args_node.named_children if a.type != "comment"] if args_node is not None else []
344
+ name = txt(fn) if fn is not None and fn.type == "identifier" else \
345
+ txt(fn.child_by_field_name("property")) if fn is not None and fn.type == "member_expression" else ""
346
+ if fn is not None and fn.type == "member_expression" and name in ("as", "mapWith", "$type"):
347
+ inner = self.expr(fn.child_by_field_name("object"))
348
+ alias = o.string_value(args[0]) if name == "as" and args else None
349
+ return inner + (f" AS {self.q(alias)}" if alias else "")
350
+ if name in COMPARE and len(args) == 2:
351
+ op = COMPARE[name]
352
+ if op.endswith("ILIKE") and self.engine == "mysql":
353
+ op = op.replace("ILIKE", "LIKE")
354
+ return f"{self.expr(args[0])} {op} {self.expr(args[1])}"
355
+ if name in ("and", "or"):
356
+ parts = []
357
+ for a in args:
358
+ ua = a if a.type == "spread_element" else unwrap(a)
359
+ if ua is None or o.is_undefined(ua):
360
+ continue
361
+ if ua.type == "spread_element":
362
+ held = o.list_items(self.f, ua.named_children[0] if ua.named_children else None, self.root)
363
+ if held is None:
364
+ parts.append(mark_node(ua))
365
+ else: # const conditions = [eq(...)]; if (x) conditions.push(...)
366
+ parts.extend(self.expr(i) for i in held[0])
367
+ parts.extend(mark("optional: " + txt(i)) for i in held[1])
368
+ elif ua.type in ("ternary_expression", "binary_expression", "identifier") and o.literal(ua) is None:
369
+ parts.append(mark("optional: " + txt(ua)) if ua.type != "identifier" else self.held(ua))
370
+ else:
371
+ parts.append(self.expr(ua))
372
+ if not parts:
373
+ return "TRUE"
374
+ return "(" + f" {name.upper()} ".join(parts) + ")"
375
+ if name == "not" and args:
376
+ return f"NOT ({self.expr(args[0])})"
377
+ if name in ("inArray", "notInArray") and len(args) == 2:
378
+ got = self.sub(args[1])
379
+ inner = got[0] if got is not None else o.in_list(args[1])
380
+ return f"{self.expr(args[0])} {'NOT IN' if name == 'notInArray' else 'IN'} ({inner})"
381
+ if name in ("isNull", "isNotNull") and args:
382
+ return f"{self.expr(args[0])} IS {'NOT ' if name == 'isNotNull' else ''}NULL"
383
+ if name in ("between", "notBetween") and len(args) == 3:
384
+ return f"{self.expr(args[0])} {'NOT ' if name == 'notBetween' else ''}BETWEEN {self.expr(args[1])} AND {self.expr(args[2])}"
385
+ if name in ("exists", "notExists") and args:
386
+ inner = self.expr(args[0])
387
+ return f"{'NOT ' if name == 'notExists' else ''}EXISTS {inner if inner.startswith('(') else '(' + inner + ')'}"
388
+ if name in ("asc", "desc") and args:
389
+ return self.expr(args[0]) + (" DESC" if name == "desc" else "")
390
+ if name in AGG:
391
+ inner = self.expr(args[0]) if args else "*"
392
+ return f"{AGG[name]}({'DISTINCT ' if name.endswith('Distinct') else ''}{inner})"
393
+ return mark_node(node)
394
+ if t == "identifier":
395
+ return self.held(node)
396
+ if t == "binary_expression":
397
+ typed = o.typed_template(self.f, node)
398
+ if typed:
399
+ return self.columns_in(typed[0]) + (f" AS {self.q(typed[1])}" if typed[1] else "")
400
+ return mark_node(node)
401
+
402
+ def held(self, node: Node) -> str:
403
+ """A name bound to a condition / fragment built just before: read it when it is one expression."""
404
+ try:
405
+ decl = self.f._decl(txt(node), self.root)
406
+ except Exception:
407
+ decl = None
408
+ if decl is not None and not decl[2] and decl[0].type == "variable_declarator":
409
+ value = unwrap(decl[0].child_by_field_name("value"))
410
+ if value is not None and value.type == "call_expression" and not (value.start_byte <= self.root.start_byte <= value.end_byte):
411
+ fn = unwrap(value.child_by_field_name("function"))
412
+ a = value.child_by_field_name("arguments")
413
+ name = txt(fn) if fn is not None and fn.type == "identifier" else ""
414
+ if name in COMPARE or name in ("and", "or", "not", "inArray", "isNull", "isNotNull", "between", "exists") or \
415
+ (a is not None and a.type == "template_string"):
416
+ return self.expr(value)
417
+ return mark_node(node)
418
+
419
+ def all_columns(self, t: Table) -> list[str]:
420
+ return [f"{self.tname(t)}.{self.q(c)}" for c in t.columns.values()]
421
+
422
+ def fields(self, node: Node | None) -> list[str] | None:
423
+ obj = as_object(self.f, node, self.root) if node is not None else None
424
+ if obj is None:
425
+ return None
426
+ out = []
427
+ for k, v in obj.entries:
428
+ uv = unwrap(v)
429
+ if uv is not None and uv.type == "object": # a nested selection: { team: { id: teams.id, name: teams.name } }
430
+ out.extend(self.fields(uv) or [mark_node(uv)])
431
+ continue
432
+ e = self.expr(uv)
433
+ needs_alias = uv is not None and uv.type == "call_expression" and " AS " not in e
434
+ out.append(e + (f" AS {self.q(k)}" if needs_alias else ""))
435
+ out += [mark(e) for e in obj.extra]
436
+ return out
437
+
438
+ def source(self, node: Node | None) -> tuple[str, Table | None]:
439
+ """(FROM text, table) of a `from` / join argument: a table, a subquery, or a builder held in a name."""
440
+ t = self.lib.table_of(node, self.f.rel)
441
+ if t is not None:
442
+ self.use(t)
443
+ return self.tname(t), t
444
+ got = self.sub(node)
445
+ if got is not None:
446
+ return f"({got[0]})" + (f" AS {self.q(got[1])}" if got[1] else ""), None
447
+ un = unwrap(node)
448
+ if un is not None and un.type == "identifier":
449
+ try:
450
+ decl = self.f._decl(txt(un), self.root)
451
+ except Exception:
452
+ decl = None
453
+ value = unwrap(decl[0].child_by_field_name("value")) if decl is not None and decl[0].type == "variable_declarator" else None
454
+ got = self.sub(value) if value is not None and not (value.start_byte <= self.root.start_byte <= value.end_byte) else None
455
+ if got is not None:
456
+ return f"({got[0]}) AS {self.q(got[1] or txt(un))}", None
457
+ raise Skip("the table object is not a pgTable / mysqlTable / sqliteTable definition that could be read")
458
+
459
+ # -- builder chains ------------------------------------------------------------------
460
+ def chain(self, kind: str, root_name: str, root_args: list[Node]) -> str:
461
+ _b, steps = spine(self.top)
462
+ idx = next(i for i, s in enumerate(steps) if s[2].id == self.root.id)
463
+ pre, post = steps[:idx], steps[idx + 1:]
464
+ if any(s[0] in ("with", "$with") for s in pre):
465
+ self.notes.append("the statement starts with a WITH clause that is not shown")
466
+ cols: list[str] | None = None
467
+ froms: list[str] = []
468
+ from_tables: list[Table] = []
469
+ joins: list[str] = []
470
+ wheres: list[str] = []
471
+ groups: list[str] = []
472
+ havings: list[str] = []
473
+ orders: list[str] = []
474
+ sets: list[str] = []
475
+ limit = offset = ""
476
+ values: Node | None = None
477
+ assigns: list[str] = []
478
+ conflict = ""
479
+ returning: list[str] | None = None
480
+ lock = ""
481
+ target: Table | None = None
482
+ executed = False
483
+ distinct = "DISTINCT " if root_name == "selectDistinct" else ""
484
+ if kind == "select":
485
+ if root_args:
486
+ first = root_args[1] if root_name == "selectDistinctOn" and len(root_args) > 1 else root_args[0]
487
+ if root_name == "selectDistinctOn":
488
+ on = o.array_items(root_args[0]) or []
489
+ distinct = f"DISTINCT ON ({', '.join(self.expr(i) for i in on)}) "
490
+ first = root_args[1] if len(root_args) > 1 else None
491
+ cols = self.fields(first) if first is not None else None
492
+ if cols is None and first is not None:
493
+ cols = [mark_node(first)]
494
+ else:
495
+ target = self.lib.table_of(root_args[0], self.f.rel) if root_args else None
496
+ if target is None:
497
+ raise Skip("table chosen at run time")
498
+ self.use(target)
499
+ for name, args, call in post:
500
+ if name in NO_OP:
501
+ executed = executed or name in TERMINAL
502
+ if name == "as" and args and call.id == post[-1][2].id:
503
+ self.alias = o.string_value(args[0]) or ""
504
+ continue
505
+ if name == "from" and args:
506
+ text, t = self.source(args[0])
507
+ froms.append(text)
508
+ if t is not None:
509
+ from_tables.append(t)
510
+ elif name in JOINS and args:
511
+ text, t = self.source(args[0])
512
+ if t is not None:
513
+ from_tables.append(t)
514
+ joins.append(f" {JOINS[name]} {text}" + (f" ON {self.expr(args[1])}" if len(args) > 1 else ""))
515
+ elif name == "where" and args:
516
+ w = self.expr(args[0])
517
+ wheres.append(w[1:-1] if w.startswith("(") and w.endswith(")") and " OR " not in w and w.count("(") == 1 else w)
518
+ elif name == "having" and args:
519
+ havings.append(self.expr(args[0]))
520
+ elif name == "groupBy":
521
+ for a in args:
522
+ groups.extend(self.expr(i) for i in (o.array_items(a) or [a]))
523
+ elif name == "orderBy":
524
+ for a in args:
525
+ ua = unwrap(a)
526
+ if ua is not None and ua.type in ("arrow_function", "function_expression"):
527
+ ua = o.callback_body(ua)
528
+ orders.extend(self.expr(i) for i in (o.array_items(ua) or [ua]))
529
+ elif name == "limit" and args:
530
+ limit = o.value(args[0])
531
+ elif name == "offset" and args:
532
+ offset = o.value(args[0])
533
+ elif name == "for" and args:
534
+ lock = f" FOR {(o.string_value(args[0]) or 'update').upper()}"
535
+ elif name in ("union", "unionAll", "intersect", "except") and args:
536
+ got = self.sub(args[0])
537
+ sets.append(f" {'UNION ALL' if name == 'unionAll' else name.upper()} {got[0] if got else 'SELECT * FROM ' + mark_node(args[0])}")
538
+ elif name == "values" and args:
539
+ values = args[0]
540
+ elif name == "select" and kind == "insert" and args:
541
+ values = args[0]
542
+ elif name == "set" and args:
543
+ self.assign(args[0], target, assigns)
544
+ elif name in ("onConflictDoUpdate", "onConflictDoNothing", "onDuplicateKeyUpdate"):
545
+ conflict = self.on_conflict(name, args, target)
546
+ elif name == "returning":
547
+ returning = (self.fields(args[0]) if args else None) or (self.plain_columns(target) if target else ["*"])
548
+ else:
549
+ self.lower(1, f"step .{name}() is not translated")
550
+ if not executed and self.parent is None:
551
+ p = self.top.parent
552
+ while p is not None and p.type in ("parenthesized_expression",):
553
+ p = p.parent
554
+ if p is None or p.type != "await_expression":
555
+ self.lower(1, "the builder is not awaited in this expression: it is continued, passed on or used as a subquery elsewhere")
556
+ where = (" WHERE " + " AND ".join(wheres)) if wheres else ""
557
+ ret = (" RETURNING " + ", ".join(returning)) if returning else ""
558
+ if kind == "select":
559
+ if not froms:
560
+ raise Skip("no table in from()")
561
+ if cols is None:
562
+ cols = [c for t in from_tables for c in self.all_columns(t)] or ["*"]
563
+ return (f"SELECT {distinct}{', '.join(cols)} FROM {', '.join(froms)}{''.join(joins)}{where}"
564
+ + (" GROUP BY " + ", ".join(groups) if groups else "") + (" HAVING " + " AND ".join(havings) if havings else "")
565
+ + "".join(sets) + (" ORDER BY " + ", ".join(orders) if orders else "")
566
+ + (f" LIMIT {limit}" if limit else "") + (f" OFFSET {offset}" if offset else "") + lock)
567
+ tbl = self.tname(target)
568
+ if kind == "insert":
569
+ uv = unwrap(values)
570
+ got = self.sub(uv) if uv is not None else None
571
+ if got is not None:
572
+ return f"INSERT INTO {tbl} {got[0]}{conflict}{ret}"
573
+ rows = o.array_items(uv)
574
+ first = rows[0] if rows else uv
575
+ if rows is None and uv is not None and uv.type == "call_expression": # xs.map((x) => ({...}))
576
+ a = uv.child_by_field_name("arguments")
577
+ cb = o.callback_body(a.named_children[0]) if a is not None and a.type == "arguments" and a.named_children else None
578
+ first = cb if cb is not None and cb.type == "object" else uv
579
+ obj = as_object(self.f, first, self.root) if first is not None else None
580
+ if obj is None or not (obj.entries or obj.extra):
581
+ return f"INSERT INTO {tbl} ({mark('columns of ' + txt(uv))}) VALUES ({mark_node(uv)}){conflict}{ret}"
582
+ pairs = obj.entries + [(k, v) for k, v, _t in obj.maybe]
583
+ names = [self.q(target.columns.get(k, k)) for k, _ in pairs] + [mark(e) for e in obj.extra]
584
+ vals = [self.expr(v) for _, v in pairs] + [mark(e) for e in obj.extra]
585
+ return f"INSERT INTO {tbl} ({', '.join(names)}) VALUES ({', '.join(vals)}){conflict}{ret}"
586
+ if kind == "update":
587
+ if not assigns:
588
+ assigns = [f"{mark('columns')} = {mark('values')}"]
589
+ return f"UPDATE {tbl} SET {', '.join(assigns)}{where}{ret}"
590
+ return f"DELETE FROM {tbl}{where}{ret}"
591
+
592
+ def plain_columns(self, t: Table) -> list[str]:
593
+ return [self.q(c) for c in t.columns.values()]
594
+
595
+ def assign(self, node: Node, target: Table, out: list[str]) -> None:
596
+ obj = as_object(self.f, node, self.root)
597
+ if obj is None:
598
+ out.append(f"{mark('columns of ' + txt(node))} = {mark_node(node)}")
599
+ return
600
+ if obj.maybe:
601
+ self.notes.append("columns set under a condition: " + ", ".join(dict.fromkeys(k for k, _v, _t in obj.maybe)))
602
+ for k, v in obj.entries + [(k, v) for k, v, _t in obj.maybe]:
603
+ if o.is_undefined(v):
604
+ continue
605
+ out.append(f"{self.q(target.columns.get(k, k))} = {self.expr(v)}")
606
+ out.extend(f"{mark(e)} = {mark(e)}" for e in obj.extra)
607
+
608
+ def on_conflict(self, name: str, args: list[Node], target: Table) -> str:
609
+ obj = as_object(self.f, args[0], self.root) if args else None
610
+ sets: list[str] = []
611
+ if obj is not None and obj.get("set") is not None:
612
+ self.assign(obj.get("set"), target, sets)
613
+ if name == "onDuplicateKeyUpdate":
614
+ return " ON DUPLICATE KEY UPDATE " + (", ".join(sets) or f"{mark('columns')} = {mark('values')}")
615
+ tnode = unwrap(obj.get("target")) if obj is not None and obj.get("target") is not None else None
616
+ cols = []
617
+ for it in (o.array_items(tnode) or ([tnode] if tnode is not None else [])):
618
+ c = self.column(unwrap(it)) if unwrap(it) is not None else None
619
+ cols.append(c.split(".")[-1] if c else mark_node(it))
620
+ tgt = f" ({', '.join(cols)})" if cols else ""
621
+ if name == "onConflictDoNothing":
622
+ return f" ON CONFLICT{tgt} DO NOTHING"
623
+ return f" ON CONFLICT{tgt} DO UPDATE SET " + (", ".join(sets) or f"{mark('columns')} = {mark('values')}")
624
+
625
+ # -- relational queries: db.query.users.findMany({ where, with, columns, orderBy, limit }) --------------
626
+ def relational(self, accessor: str, args: list[Node]) -> str:
627
+ t = self.lib.table(accessor, self.f.rel)
628
+ if t is None:
629
+ raise Skip("db.query.<name>: no table of that name in the schema")
630
+ self.use(t)
631
+ obj = as_object(self.f, args[0], self.root) if args else None
632
+ if args and obj is None:
633
+ self.lower(1, "the options are built elsewhere: only the table and the operation are known")
634
+ return f"SELECT {', '.join(self.all_columns(t))} FROM {self.tname(t)} {mark_node(args[0])}"
635
+ fn = unwrap(self.root.child_by_field_name("function"))
636
+ first = txt(fn.child_by_field_name("property")) == "findFirst"
637
+ return self._relational(t, obj, first, None, 1)
638
+
639
+ def _callback(self, node: Node | None, t: Table) -> Node | None:
640
+ """`(users, { eq }) => eq(users.id, 1)`: the first parameter stands for the table."""
641
+ un = unwrap(node)
642
+ if un is not None and un.type in ("arrow_function", "function_expression"):
643
+ from .typescript import params_of
644
+ params = params_of(un)
645
+ if params and params[0].type == "identifier":
646
+ self.locals[txt(params[0])] = t
647
+ return o.callback_body(un)
648
+ return un
649
+
650
+ def _relational(self, t: Table, obj, first: bool, join: str | None, depth: int) -> str:
651
+ cols = self.all_columns(t)
652
+ if obj is not None and obj.get("columns") is not None:
653
+ cobj = as_object(self.f, obj.get("columns"), self.root)
654
+ if cobj is not None:
655
+ picked = [k for k, v in cobj.entries if txt(unwrap(v)) == "true"]
656
+ dropped = {k for k, v in cobj.entries if txt(unwrap(v)) == "false"}
657
+ keys = picked or [k for k in t.columns if k not in dropped]
658
+ cols = [f"{self.tname(t)}.{self.q(t.columns[k])}" for k in keys if k in t.columns]
659
+ laterals = ""
660
+ with_obj = as_object(self.f, obj.get("with"), self.root) if obj is not None and obj.get("with") is not None else None
661
+ for k, v in (with_obj.entries if with_obj is not None else []):
662
+ rel = t.relations.get(k)
663
+ target = self.lib.table(rel["target"], t.rel) if rel else None
664
+ if rel is None or target is None or depth > o.SETTINGS["orm_max_relation_depth"]:
665
+ self.lower(1, f"relation `{k}` of {t.name} could not be read from relations()")
666
+ continue
667
+ if rel["fields"] and rel["references"]:
668
+ on = " AND ".join(f"{self.tname(target)}.{self.q(target.columns.get(b, b))} = {self.tname(t)}.{self.q(t.columns.get(a, a))}"
669
+ for a, b in zip(rel["fields"], rel["references"]))
670
+ else: # the key is on the other side: its `one(...)` back to this table
671
+ back = next((r for r in target.relations.values() if r["target"] == t.var and r["fields"]
672
+ and (not rel.get("name") or r.get("name") == rel.get("name"))), None)
673
+ if back is None:
674
+ self.lower(1, f"relation `{k}` of {t.name}: the key columns are not stated")
675
+ continue
676
+ on = " AND ".join(f"{self.tname(target)}.{self.q(target.columns.get(a, a))} = {self.tname(t)}.{self.q(t.columns.get(b, b))}"
677
+ for a, b in zip(back["fields"], back["references"]))
678
+ sub_obj = as_object(self.f, v, self.root) if unwrap(v) is not None and unwrap(v).type == "object" else None
679
+ inner = self._relational(target, sub_obj, rel["kind"] == "one", on, depth + 1)
680
+ laterals += f" LEFT JOIN LATERAL ({inner}) AS {self.q(k)} ON TRUE"
681
+ cols.append(f"{self.q(k)}.*")
682
+ if laterals:
683
+ self.notes.append("relational query: `with` relations are LATERAL joins in this statement")
684
+ wheres = [join] if join else []
685
+ if obj is not None and obj.get("where") is not None:
686
+ wheres.append(self.expr(self._callback(obj.get("where"), t)))
687
+ sql = f"SELECT {', '.join(cols)} FROM {self.tname(t)}{laterals}" + (" WHERE " + " AND ".join(wheres) if wheres else "")
688
+ if obj is not None and obj.get("orderBy") is not None:
689
+ body = self._callback(obj.get("orderBy"), t)
690
+ sql += " ORDER BY " + ", ".join(self.expr(i) for i in (o.array_items(body) or [body]))
691
+ if obj is not None and obj.get("limit") is not None:
692
+ sql += f" LIMIT {o.value(obj.get('limit'))}"
693
+ elif first:
694
+ sql += " LIMIT 1"
695
+ if obj is not None and obj.get("offset") is not None:
696
+ sql += f" OFFSET {o.value(obj.get('offset'))}"
697
+ return sql