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,861 @@
1
+ """Kysely builder chains (`db.selectFrom("t").where(...).select(...).execute()`) as SQL sites.
2
+
3
+ A chain starts at `selectFrom` / `insertInto` / `updateTable` / `deleteFrom` and is read step by step. Steps that
4
+ continue it through a variable (`qb = qb.where(...)`) are read too: unconditional ones join the statement,
5
+ conditional ones become run-time parts. A builder used as an argument of another chain is its subquery and is
6
+ written inside it, not as a site of its own. Expression-builder callbacks are read where they are simple
7
+ (`eb("a", "=", v)`, `eb.and([...])`, `eb.or([...])`, `eb.exists(...)`, `eb.ref`, `eb.fn.count`); anything else
8
+ is a run-time part.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import re
15
+
16
+ from tree_sitter import Node
17
+
18
+ from . import orm_ts as o
19
+ from .orm_ts import mark, mark_node, txt, unwrap
20
+ from .orm_ts_schema import climb, spine
21
+
22
+ NAME = "kysely"
23
+ ROOTS = {"selectFrom": "select", "insertInto": "insert", "replaceInto": "insert", "updateTable": "update",
24
+ "deleteFrom": "delete", "mergeInto": "merge"}
25
+ TERMINAL = {"execute", "executeTakeFirst", "executeTakeFirstOrThrow", "stream", "compile", "explain"}
26
+ NO_OP = {"$castTo", "$narrowType", "$assertType", "$notNull", "$nullable", "as", "clearOrderBy", "$asScalar", "$asTuple",
27
+ "toOperationNode", "withPlugin", "withoutPlugins", "$pickTables", "$omitTables"} | TERMINAL
28
+ JOINS = {"innerJoin": "INNER JOIN", "leftJoin": "LEFT JOIN", "rightJoin": "RIGHT JOIN", "fullJoin": "FULL JOIN",
29
+ "crossJoin": "CROSS JOIN", "innerJoinLateral": "INNER JOIN LATERAL", "leftJoinLateral": "LEFT JOIN LATERAL",
30
+ "crossJoinLateral": "CROSS JOIN LATERAL"}
31
+ SETS = {"union": "UNION", "unionAll": "UNION ALL", "intersect": "INTERSECT", "intersectAll": "INTERSECT ALL",
32
+ "except": "EXCEPT", "exceptAll": "EXCEPT ALL"}
33
+ LOCKS = {"forUpdate": "FOR UPDATE", "forShare": "FOR SHARE", "forNoKeyUpdate": "FOR NO KEY UPDATE", "forKeyShare": "FOR KEY SHARE",
34
+ "skipLocked": "SKIP LOCKED", "noWait": "NOWAIT"}
35
+ STAR = "\0*"
36
+ PRE = re.compile(rb"\.\s*(?:selectFrom|insertInto|updateTable|deleteFrom|replaceInto|mergeInto)\s*\(")
37
+ _IDENT = re.compile(r"^[A-Za-z_][\w$]*(?:\.[A-Za-z_*][\w$]*){0,2}$")
38
+ _OPS = {"=", "==", "!=", "<>", ">", ">=", "<", "<=", "in", "not in", "is", "is not", "like", "not like", "ilike", "not ilike",
39
+ "@>", "<@", "&&", "?", "?&", "@@", "~", "~*", "!~", "!~*", "is distinct from", "is not distinct from", "match",
40
+ "regexp", "+", "-", "*", "/", "%", "||", "->", "->>", "between", "not between"}
41
+ _FNS = {"count": "COUNT", "sum": "SUM", "avg": "AVG", "min": "MIN", "max": "MAX", "coalesce": "COALESCE",
42
+ "jsonAgg": "JSON_AGG", "toJson": "TO_JSON", "any": "ANY"}
43
+
44
+
45
+ class Library:
46
+ name = NAME
47
+
48
+ def __init__(self, ctx, root, files, stats):
49
+ self.ctx, self.stats = ctx, stats
50
+ self.active = True
51
+ self.used = False # some file or package of the repository names Kysely
52
+ self.maybe: list[str] = [] # files with builder calls in packages that do not name it themselves
53
+ self.camel = False # CamelCasePlugin: names are written camelCase and sent snake_case
54
+ self.columns: dict[str, list[tuple[str, list[str]]]] = {} # table -> [(defining file, columns)]
55
+ from .orm_ts_schema import KyselySchema
56
+ self._schema = KyselySchema()
57
+
58
+ def wants(self, rel: str, src: bytes, deps) -> bool:
59
+ if b"CamelCasePlugin" in src and b"kysely" in src:
60
+ self.camel = True
61
+ if self._schema.wants(src):
62
+ try:
63
+ self._schema.add(rel, src)
64
+ except Exception:
65
+ pass
66
+ if not PRE.search(src):
67
+ return False
68
+ if "kysely" in deps or b"kysely" in src or b"Kysely" in src:
69
+ self.used = True
70
+ return True
71
+ self.maybe.append(rel) # the method names are Kysely's own: taken once the repository is seen to use it
72
+ return False
73
+
74
+ def prepare(self, wanted) -> None:
75
+ if self.used:
76
+ for rel in self.maybe:
77
+ wanted.setdefault(rel, set()).add(NAME)
78
+ for t in self._schema.tables():
79
+ self.columns.setdefault(t.name, []).append((t.defined_at[0].rsplit(":", 1)[0], [c["name"] for c in t.columns]))
80
+ prisma = getattr(self.ctx, "orm_prisma_schemas", None) or []
81
+ for schema in prisma: # Kysely types generated from a Prisma schema (prisma-kysely)
82
+ for m in schema.models.values():
83
+ self.columns.setdefault(m.table, []).append((schema.base + "/", [f.column for f in m.scalars()]))
84
+
85
+ def columns_of(self, rel: str, table: str) -> list[str] | None:
86
+ cands = self.columns.get(table)
87
+ if not cands:
88
+ return None
89
+ if len(cands) == 1 or len({tuple(c) for _, c in cands}) == 1:
90
+ return cands[0][1]
91
+ a = rel.split("/")
92
+ scored = sorted(((next((i for i, (x, y) in enumerate(zip(a, d.split("/"))) if x != y), min(len(a), len(d.split("/")))), cols)
93
+ for d, cols in cands), key=lambda s: -s[0])
94
+ return scored[0][1] if scored[0][0] > scored[1][0] else None
95
+
96
+ def sites(self, f) -> list:
97
+ roots = []
98
+ for call in f.calls:
99
+ fn = unwrap(call.child_by_field_name("function"))
100
+ if fn is None or fn.type != "member_expression" or txt(fn.child_by_field_name("property")) not in ROOTS:
101
+ continue
102
+ args = call.child_by_field_name("arguments")
103
+ if args is None or args.type != "arguments":
104
+ continue
105
+ roots.append((call, climb(call)))
106
+ out = []
107
+ consumed: set[int] = set()
108
+ results = {}
109
+ # outermost chains first, so that a builder used inside another is written there
110
+ for call, top in sorted(roots, key=lambda r: (r[0].start_byte, -(r[1].end_byte - r[1].start_byte))):
111
+ self.stats.see(NAME, f.test)
112
+ if call.id in consumed:
113
+ self.stats.ok(NAME, f.test, 0)
114
+ continue
115
+ line = call.start_point[0] + 1
116
+ q = Chain(self, f, call, top, consumed)
117
+ try:
118
+ sql = q.statement()
119
+ except Skip as e:
120
+ self.stats.miss(NAME, f.test, str(e), f.rel, line)
121
+ continue
122
+ except Exception as e:
123
+ if os.environ.get("CODECOP_ORM_DEBUG"):
124
+ raise
125
+ self.stats.miss(NAME, f.test, f"internal error ({type(e).__name__})", f.rel, line)
126
+ continue
127
+ results[call.id] = (q, sql, call, top)
128
+ for cid, (q, sql, call, top) in results.items():
129
+ if cid in consumed: # became the subquery of a chain read after it
130
+ self.stats.ok(NAME, f.test, 0)
131
+ continue
132
+ self.stats.ok(NAME, f.test, 1)
133
+ out.append(o.make_site(f, top, txt(call.child_by_field_name("function")), q.engine, sql, top, library=NAME,
134
+ table=q.main_table, operation=q.kind, confidence=o.CONFIDENCE[q.level], notes=q.notes))
135
+ return out
136
+
137
+
138
+ class Skip(Exception):
139
+ """The call cannot be translated; the message is the reason that is counted."""
140
+
141
+
142
+ class Chain:
143
+ def __init__(self, lib: Library, f, root: Node, top: Node, consumed: set[int], parent: "Chain | None" = None):
144
+ self.lib, self.f, self.root, self.top, self.consumed = lib, f, root, top, consumed
145
+ self.engine = parent.engine if parent is not None else o.engine_of_builder(f)
146
+ self.notes: list[str] = parent.notes if parent is not None else []
147
+ self.parent = parent
148
+ self._level = 2
149
+ self.kind = ROOTS[txt(unwrap(root.child_by_field_name("function")).child_by_field_name("property"))]
150
+ self.main_table = ""
151
+ self.alias = ""
152
+ self.extra: list = [] # steps added where a held builder is used
153
+ self.depth = parent.depth + 1 if parent is not None else 0
154
+ self.anchor: Node = parent.anchor if parent is not None else root # where names are looked up from
155
+
156
+ @property
157
+ def level(self) -> int:
158
+ return self._level
159
+
160
+ def lower(self, level: int, note: str) -> None:
161
+ top = self
162
+ while top.parent is not None:
163
+ top = top.parent
164
+ top._level = min(top._level, level)
165
+ if note not in self.notes:
166
+ self.notes.append(note)
167
+
168
+ # -- names -------------------------------------------------------------------------
169
+ def name(self, text: str) -> str:
170
+ if self.lib.camel:
171
+ text = ".".join(p if p == "*" else re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", p).lower() for p in text.split("."))
172
+ return o.qname(self.engine, text)
173
+
174
+ def ident(self, text: str, table: bool = False) -> str | None:
175
+ """`a.b as c` / `t as a` -> quoted SQL; None when the text is not a plain reference."""
176
+ text = text.strip()
177
+ m = re.match(r"^(.+?)\s+as\s+([A-Za-z_][\w$]*)$", text, re.I)
178
+ alias = ""
179
+ if m:
180
+ text, alias = m.group(1).strip(), m.group(2)
181
+ direction = ""
182
+ dm = re.match(r"^(.+?)\s+(asc|desc)$", text, re.I)
183
+ if dm and not table:
184
+ text, direction = dm.group(1), " " + dm.group(2).upper()
185
+ if not _IDENT.match(text):
186
+ return None
187
+ return self.name(text) + direction + (f" AS {o.quote(self.engine, alias)}" if alias else "")
188
+
189
+ def ref(self, node: Node | None) -> str:
190
+ """A column (or table) reference argument."""
191
+ node = unwrap(node)
192
+ s = o.string_value(node)
193
+ if s is not None:
194
+ return self.ident(s) or mark(s)
195
+ return self.val(node, ref=True)
196
+
197
+ # -- values and expressions ------------------------------------------------------------
198
+ def sub(self, node: Node | None) -> tuple[str, str] | None:
199
+ """(SQL, alias) of a builder chain used as a value (a subquery), or None when the node is not one."""
200
+ node = unwrap(node)
201
+ if node is None or node.type != "call_expression":
202
+ return None
203
+ base, steps = spine(node)
204
+ for name, _args, call in steps:
205
+ if name in ROOTS:
206
+ q = Chain(self.lib, self.f, call, node, self.consumed, parent=self)
207
+ sql = q.statement(follow=False)
208
+ self.consumed.add(call.id)
209
+ return sql, q.alias
210
+ return self.held(base, steps)
211
+
212
+ def held(self, base: Node | None, steps: list) -> tuple[str, str] | None:
213
+ """A builder held in a variable and used here (`sub`, `sub.where(...).as("x")`): the chain that built it,
214
+ with the steps added here."""
215
+ if base is None or base.type != "identifier" or self.depth > o.SETTINGS["orm_max_object_depth"]:
216
+ return None
217
+ try:
218
+ decl = self.f._decl(txt(base), self.anchor)
219
+ except Exception:
220
+ decl = None
221
+ if decl is None or decl[2] or decl[0].type != "variable_declarator":
222
+ return None
223
+ value = unwrap(decl[0].child_by_field_name("value"))
224
+ if value is None or value.type != "call_expression" or value.start_byte <= self.anchor.start_byte <= value.end_byte:
225
+ return None
226
+ _b, vsteps = spine(value)
227
+ for name, _args, call in vsteps:
228
+ if name in ROOTS:
229
+ q = Chain(self.lib, self.f, call, value, self.consumed, parent=self)
230
+ q.extra = list(steps)
231
+ sql = q.statement(follow=False)
232
+ return sql, q.alias
233
+ return None
234
+
235
+ def template(self, node: Node) -> str | None:
236
+ """A sql`...` fragment through the raw-SQL resolver."""
237
+ try:
238
+ res = self.f.resolve(node, self.root, 0)
239
+ except Exception:
240
+ res = None
241
+ return res.text.strip() if res is not None and res.text.strip() else None
242
+
243
+ def val(self, node: Node | None, ref: bool = False) -> str:
244
+ node = unwrap(node)
245
+ if node is None:
246
+ return mark("?")
247
+ lit = o.literal(node)
248
+ if lit is not None:
249
+ return lit
250
+ t = node.type
251
+ if t in ("arrow_function", "function_expression"):
252
+ body = o.callback_body(node)
253
+ return self.val(body, ref) if body is not None else mark_node(node)
254
+ if t == "array":
255
+ return "(" + o.in_list(node) + ")"
256
+ if t == "call_expression":
257
+ fnode = unwrap(node.child_by_field_name("function"))
258
+ args_node = node.child_by_field_name("arguments")
259
+ if args_node is not None and args_node.type == "template_string":
260
+ return self.template(node) or mark_node(node)
261
+ got = self.sub(node)
262
+ if got is not None:
263
+ return f"({got[0]})" + (f" AS {o.quote(self.engine, got[1])}" if got[1] else "")
264
+ args = [a for a in args_node.named_children if a.type != "comment"] if args_node is not None else []
265
+ base, steps = spine(node)
266
+ names = [s[0] for s in steps]
267
+ alias = ""
268
+ if names and names[-1] == "as" and steps[-1][1]:
269
+ a = o.string_value(steps[-1][1][0])
270
+ alias = f" AS {o.quote(self.engine, a)}" if a else ""
271
+ steps, names = steps[:-1], names[:-1]
272
+ if not steps and base is not None and base.type == "identifier":
273
+ got = self.held(base, [])
274
+ if got is not None:
275
+ return f"({got[0]})" + alias
276
+ return self.val(steps[-1][2] if steps else base) + alias
277
+ if fnode is not None and fnode.type == "identifier" and txt(fnode) in ("jsonArrayFrom", "jsonObjectFrom") and len(args) == 1:
278
+ inner = self.sub(args[0]) # kysely/helpers: a correlated subquery folded into one JSON value
279
+ if inner is not None:
280
+ if txt(fnode) == "jsonArrayFrom":
281
+ return f"(SELECT COALESCE(JSON_AGG(agg), '[]') FROM ({inner[0]}) AS agg)"
282
+ return f"(SELECT TO_JSON(obj) FROM ({inner[0]}) AS obj)"
283
+ if fnode is not None and fnode.type == "identifier" and len(args) == 3: # eb("a", "=", v)
284
+ return self.binary(args)
285
+ if fnode is not None and fnode.type == "identifier" and txt(fnode) in ("ref", "dynamicRef") and len(args) == 1 \
286
+ and o.string_value(args[0]) is not None:
287
+ return self.ident(o.string_value(args[0])) or mark_node(node)
288
+ if not names:
289
+ return mark_node(node)
290
+ last, largs = names[-1], steps[-1][1]
291
+ if last in ("ref", "table", "id") and largs and o.string_value(largs[0]) is not None:
292
+ return self.ident(o.string_value(largs[0])) or mark_node(node)
293
+ if last in ("val", "lit", "value") and largs:
294
+ return o.value(largs[0])
295
+ if last in ("and", "or") and largs:
296
+ items = o.array_items(largs[0])
297
+ if items is not None:
298
+ parts = [self.cond(i) for i in items]
299
+ return "(" + f" {last.upper()} ".join(parts) + ")" if parts else ("TRUE" if last == "and" else "FALSE")
300
+ return mark_node(node)
301
+ if last == "not" and largs:
302
+ return f"NOT ({self.cond(largs[0])})"
303
+ if last == "exists" and largs:
304
+ inner = self.val(largs[0])
305
+ return f"EXISTS {inner}" if inner.startswith("(") else f"EXISTS ({inner})"
306
+ if last in ("eb", "cmpr", "bxp") and len(largs) == 3:
307
+ return self.binary(largs)
308
+ if last == "countAll" and not largs:
309
+ return "COUNT(*)"
310
+ holder = txt(unwrap(steps[-1][2].child_by_field_name("function")).child_by_field_name("object"))
311
+ if last in _FNS and largs and re.search(r"(?:^|\.)fn$", holder):
312
+ return f"{_FNS[last]}({', '.join(self.ref(a) for a in largs)})"
313
+ if last == "distinct" and len(steps) >= 2: # fn.count("x").distinct()
314
+ inner = self.val(steps[-2][2])
315
+ return re.sub(r"^(\w+)\(", r"\1(DISTINCT ", inner, count=1)
316
+ return mark_node(node)
317
+ if t == "template_string" and node.parent is not None and node.parent.type == "call_expression":
318
+ return self.template(node.parent) or mark_node(node)
319
+ if t == "identifier":
320
+ got = self.held(node, [])
321
+ if got is not None:
322
+ return f"({got[0]})"
323
+ frag = self.fragment(node)
324
+ if frag:
325
+ return frag
326
+ if t == "binary_expression": # sql<T>`...`: the grammar reads `sql < T > template`
327
+ typed = self.typed_template(node)
328
+ if typed:
329
+ return typed
330
+ return mark_node(node)
331
+
332
+ def fragment(self, node: Node) -> str | None:
333
+ """A name bound to a sql`...` fragment."""
334
+ try:
335
+ res = self.f.resolve(node, self.root, 0)
336
+ except Exception:
337
+ res = None
338
+ return res.text.strip() if res is not None and res.frag and res.text.strip() else None
339
+
340
+ def typed_template(self, node: Node) -> str | None:
341
+ got = o.typed_template(self.f, node)
342
+ return got[0] + (f" AS {o.quote(self.engine, got[1])}" if got[1] else "") if got else None
343
+
344
+ def binary(self, args: list[Node]) -> str:
345
+ left = self.ref(args[0])
346
+ op_text = o.string_value(args[1])
347
+ if op_text is None or op_text.lower() not in _OPS:
348
+ return f"{left} {mark_node(args[1])} {mark('…')}" if op_text is None else mark(" ".join(txt(a) for a in args))
349
+ op = op_text.upper() if op_text[0].isalpha() else {"==": "=", "!=": "<>"}.get(op_text, op_text)
350
+ right_node = unwrap(args[2])
351
+ if op in ("IN", "NOT IN"):
352
+ got = self.sub(right_node)
353
+ if got is not None:
354
+ return f"{left} {op} ({got[0]})"
355
+ if right_node is not None and right_node.type in ("arrow_function", "function_expression"):
356
+ inner = self.val(right_node)
357
+ return f"{left} {op} {inner if inner.startswith('(') else '(' + inner + ')'}"
358
+ if right_node is not None and right_node.type == "call_expression" and \
359
+ right_node.child_by_field_name("arguments").type == "template_string":
360
+ inner = self.val(right_node)
361
+ return f"{left} {op} {inner if inner.startswith('(') else '(' + inner + ')'}"
362
+ return f"{left} {op} ({o.in_list(right_node)})"
363
+ return f"{left} {op} {self.val(right_node)}"
364
+
365
+ def cond(self, node: Node | None) -> str:
366
+ """A boolean expression argument (of where / having / on)."""
367
+ node = unwrap(node)
368
+ if node is None:
369
+ return mark("?")
370
+ if node.type in ("arrow_function", "function_expression"):
371
+ body = o.callback_body(node)
372
+ return self.cond(body) if body is not None else mark_node(node)
373
+ return self.val(node)
374
+
375
+ def predicate(self, args: list[Node], ref_right: bool = False) -> str:
376
+ if len(args) == 3:
377
+ if ref_right:
378
+ op = o.string_value(args[1]) or "="
379
+ return f"{self.ref(args[0])} {op.upper() if op[0].isalpha() else op} {self.ref(args[2])}"
380
+ return self.binary(args)
381
+ if len(args) == 1:
382
+ return self.cond(args[0])
383
+ return mark(", ".join(txt(a) for a in args))
384
+
385
+ # -- tables ------------------------------------------------------------------------
386
+ def table_ref(self, node: Node | None) -> list[str]:
387
+ node = unwrap(node)
388
+ items = o.array_items(node)
389
+ out = []
390
+ for it in (items if items is not None else [node]):
391
+ s = o.string_value(it)
392
+ if s is not None:
393
+ got = self.ident(s, table=True)
394
+ if got is None:
395
+ raise Skip("table name is not a plain identifier")
396
+ if not self.main_table:
397
+ self.main_table = re.split(r"\s+as\s+", s.strip(), flags=re.I)[0]
398
+ out.append(got)
399
+ continue
400
+ uit = unwrap(it)
401
+ got = self.sub(uit) if uit is not None else None
402
+ if got is None and uit is not None and uit.type in ("arrow_function", "function_expression"):
403
+ body = o.callback_body(uit)
404
+ got = self.sub(body) if body is not None else None
405
+ if got is not None:
406
+ out.append(f"({got[0]})" + (f" AS {o.quote(self.engine, got[1])}" if got[1] else ""))
407
+ if not self.main_table:
408
+ self.main_table = "(subquery)"
409
+ continue
410
+ # an alias on a builder held in a variable: `queryUnion.as("u")`
411
+ base, steps = spine(uit)
412
+ if steps and steps[-1][0] == "as" and steps[-1][1] and o.string_value(steps[-1][1][0]) and uit is not None:
413
+ alias = o.string_value(steps[-1][1][0])
414
+ inner = unwrap(unwrap(uit.child_by_field_name("function")).child_by_field_name("object"))
415
+ setop = self._set_variable(inner)
416
+ out.append(f"({setop or 'SELECT * FROM ' + mark_node(inner)}) AS {o.quote(self.engine, alias)}")
417
+ if not self.main_table:
418
+ self.main_table = "(subquery)"
419
+ self.lower(1, f"reads from a builder held in `{o.trim(txt(inner), 40)}`: its tables are in the sites that build it")
420
+ continue
421
+ raise Skip("table chosen at run time")
422
+ return out
423
+
424
+ def _set_variable(self, node: Node | None) -> str | None:
425
+ """`const u = queries.reduce((acc, q) => acc.union(q))`: a UNION of builders collected at run time."""
426
+ if node is None or node.type != "identifier":
427
+ return None
428
+ try:
429
+ decl = self.f._decl(txt(node), self.anchor)
430
+ except Exception:
431
+ decl = None
432
+ if decl is None:
433
+ return None
434
+ text = txt(decl[0])
435
+ m = re.search(r"\.(unionAll|union|intersect|except)\(", text)
436
+ if not m:
437
+ return None
438
+ src = re.search(r"=\s*([\w$.]+)\.reduce\(", text)
439
+ each = mark("each of " + (src.group(1) if src else txt(node)))
440
+ return f"SELECT * FROM {each} {SETS[m.group(1)]} SELECT * FROM {mark('…the next of ' + (src.group(1) if src else txt(node)))}"
441
+
442
+ def select_list(self, args: list[Node], out: list[str]) -> None:
443
+ for a in args:
444
+ a = unwrap(a)
445
+ if a is not None and a.type in ("arrow_function", "function_expression"):
446
+ a = o.callback_body(a)
447
+ if a is None:
448
+ out.append(mark("select callback"))
449
+ continue
450
+ items = o.array_items(a)
451
+ if items is None and a is not None and a.type == "array":
452
+ out.append(mark_node(a))
453
+ continue
454
+ for it in (items if items is not None else [a]):
455
+ s = o.string_value(it)
456
+ if s is not None:
457
+ out.append(self.ident(s) or mark(s))
458
+ else:
459
+ out.append(self.val(it))
460
+
461
+ def star(self, table: str | None, froms: list[str]) -> list[str]:
462
+ """`selectAll()`: the table's columns when its definition is known, else `*`."""
463
+ names = [table] if table else ([self.main_table] if len(froms) == 1 and self.main_table and self.main_table != "(subquery)" else [])
464
+ if len(names) == 1 and names[0]:
465
+ cols = self.lib.columns_of(self.f.rel, names[0].split(".")[-1])
466
+ if cols:
467
+ prefix = names[0] if table else ""
468
+ return [self.name(f"{prefix}.{c}" if prefix else c) for c in cols]
469
+ return [self.name(table) + ".*" if table else "*"]
470
+
471
+ # -- the statement -------------------------------------------------------------------
472
+ def steps_after_root(self, follow: bool) -> tuple[list, list[Node], list[tuple[str, list[Node], Node]]]:
473
+ base, steps = spine(self.top)
474
+ idx = next(i for i, s in enumerate(steps) if s[2].id == self.root.id)
475
+ pre, root_args, post = steps[:idx], steps[idx][1], steps[idx + 1:]
476
+ self.conditional: list[tuple[str, list[Node], Node]] = []
477
+ self.executed = any(s[0] in TERMINAL for s in post)
478
+ if follow:
479
+ post = post + self.continued()
480
+ post = post + self.extra
481
+ return pre, root_args, post
482
+
483
+ def continued(self) -> list:
484
+ """Steps added through the variable the chain is assigned to: `qb = qb.where(...)`."""
485
+ p = self.top.parent
486
+ while p is not None and p.type in o.UNWRAP:
487
+ p = p.parent
488
+ if p is None:
489
+ return []
490
+ if p.type == "variable_declarator":
491
+ name_node = p.child_by_field_name("name")
492
+ elif p.type == "assignment_expression":
493
+ name_node = p.child_by_field_name("left")
494
+ else:
495
+ return []
496
+ if name_node is None or name_node.type != "identifier":
497
+ return []
498
+ var = txt(name_node)
499
+ scope = p.parent
500
+ while scope is not None and scope.type not in o.FUNC_TYPES and scope.type != "program":
501
+ scope = scope.parent
502
+ if scope is None:
503
+ return []
504
+ home = p.parent
505
+ while home is not None and home.type not in ("statement_block", "program"):
506
+ home = home.parent
507
+ more: list = []
508
+ uses = []
509
+ budget = o.SETTINGS["orm_max_chain_statements"] * 200
510
+ stack = [scope]
511
+ while stack and budget > 0:
512
+ n = stack.pop()
513
+ budget -= 1
514
+ if n.end_byte <= self.top.end_byte:
515
+ continue
516
+ if n is not scope and n.type in o.FUNC_TYPES:
517
+ continue
518
+ if n.type == "call_expression" and n.start_byte > self.top.end_byte:
519
+ base, steps = spine(n)
520
+ if base is not None and base.type == "identifier" and txt(base) == var and steps and climb(n).id == n.id:
521
+ uses.append((n, steps))
522
+ continue
523
+ stack.extend(reversed(n.children))
524
+ ends = 0
525
+ for n, steps in sorted(uses, key=lambda u: u[0].start_byte):
526
+ par = n.parent
527
+ while par is not None and par.type in o.UNWRAP:
528
+ par = par.parent
529
+ reassigned = par is not None and par.type == "assignment_expression" and txt(par.child_by_field_name("left")) == var
530
+ terminal = any(s[0] in TERMINAL for s in steps)
531
+ if terminal:
532
+ self.executed = True
533
+ if not reassigned and not terminal:
534
+ continue
535
+ if not reassigned:
536
+ ends += 1
537
+ if ends > 1: # the builder is finished in several ways: only the shared part is one statement
538
+ self.notes.append(f"`{var}` is executed more than once with different endings")
539
+ continue
540
+ # conditional: inside an if / loop that does not hold the declaration
541
+ cond = False
542
+ c = n.parent
543
+ while c is not None and c is not home and c is not scope:
544
+ if c.type in o.CONDITIONAL_TYPES:
545
+ cond = True
546
+ break
547
+ c = c.parent
548
+ if cond:
549
+ self.conditional.extend(steps)
550
+ else:
551
+ more.extend(steps)
552
+ return more
553
+
554
+ def statement(self, follow: bool = True) -> str:
555
+ pre, root_args, post = self.steps_after_root(follow)
556
+ if not root_args:
557
+ raise Skip("no table argument")
558
+ ctes = []
559
+ for name, args, _call in pre:
560
+ if name in ("with", "withRecursive") and len(args) >= 2:
561
+ cname = o.string_value(args[0])
562
+ body = o.callback_body(args[1])
563
+ got = self.sub(body) if body is not None else None
564
+ label = o.quote(self.engine, cname.split("(")[0]) if cname else mark_node(args[0])
565
+ ctes.append(f"{label} AS ({got[0] if got is not None else 'SELECT ' + mark_node(args[1])})")
566
+ elif name == "withSchema" and args:
567
+ self.notes.append(f"schema set by withSchema({o.norm_expr(txt(args[0]))})")
568
+ froms = self.table_ref(root_args[0])
569
+ if len(root_args) > 1:
570
+ for extra in root_args[1:]:
571
+ froms += self.table_ref(extra)
572
+ cols: list[str] = []
573
+ joins: list[str] = []
574
+ wheres: list[str] = []
575
+ groups: list[str] = []
576
+ havings: list[str] = []
577
+ orders: list[str] = []
578
+ sets: list[str] = []
579
+ values: Node | None = None
580
+ columns_step: list[str] | None = None
581
+ assigns: list[str] = []
582
+ conflict = ""
583
+ returning: list[str] = []
584
+ using: list[str] = []
585
+ limit = offset = ""
586
+ distinct = ""
587
+ locks: list[str] = []
588
+ ignore = False
589
+
590
+ def apply(name: str, args: list[Node], call: Node) -> None:
591
+ nonlocal values, conflict, limit, offset, distinct, ignore, columns_step
592
+ if name in NO_OP:
593
+ if name == "as" and args and call.id == post[-1][2].id:
594
+ self.alias = o.string_value(args[0]) or ""
595
+ return
596
+ if name == "select":
597
+ self.select_list(args, cols)
598
+ elif name == "selectAll":
599
+ t = o.string_value(args[0]) if args else None
600
+ if args and t is None:
601
+ for it in (o.array_items(args[0]) or []):
602
+ s = o.string_value(it)
603
+ cols.extend(self.star(s, froms) if s else [mark_node(it)])
604
+ elif t is None:
605
+ cols.append(STAR) # expanded once the joins are known
606
+ else:
607
+ cols.extend(self.star(t, froms))
608
+ elif name == "distinct":
609
+ distinct = "DISTINCT "
610
+ elif name == "distinctOn":
611
+ tmp: list[str] = []
612
+ self.select_list(args, tmp)
613
+ distinct = f"DISTINCT ON ({', '.join(tmp)}) "
614
+ elif name in ("where", "whereRef", "orWhere", "orWhereRef"):
615
+ p = self.predicate(args, ref_right=name.endswith("Ref"))
616
+ if name.startswith("or") and wheres:
617
+ wheres[-1] = f"({wheres[-1]} OR {p})"
618
+ else:
619
+ wheres.append(p)
620
+ elif name in ("having", "havingRef"):
621
+ havings.append(self.predicate(args, ref_right=name.endswith("Ref")))
622
+ elif name in JOINS:
623
+ joins.append(self.join(JOINS[name], args))
624
+ elif name == "groupBy":
625
+ self.select_list(args, groups)
626
+ elif name == "orderBy":
627
+ self.order(args, orders)
628
+ elif name == "limit" and args:
629
+ limit = o.value(args[0])
630
+ elif name == "offset" and args:
631
+ offset = o.value(args[0])
632
+ elif name in SETS and args:
633
+ for a in (o.array_items(args[0]) or [args[0]]):
634
+ ua = unwrap(a)
635
+ if ua is not None and ua.type in ("arrow_function", "function_expression"):
636
+ ua = o.callback_body(ua)
637
+ got = self.sub(ua)
638
+ sets.append(f"{SETS[name]} {got[0] if got else 'SELECT * FROM ' + mark_node(ua)}")
639
+ elif name in LOCKS:
640
+ locks.append(LOCKS[name])
641
+ elif name == "values" and args:
642
+ values = args[0]
643
+ elif name == "columns" and args:
644
+ columns_step = [self.ident(s) or mark(s) for s in (o.string_value(i) for i in (o.array_items(args[0]) or [])) if s]
645
+ elif name == "expression" and args:
646
+ values = args[0]
647
+ elif name == "defaultValues":
648
+ values = None
649
+ elif name == "set":
650
+ self.set_step(args, assigns)
651
+ elif name in ("onConflict", "onDuplicateKeyUpdate"):
652
+ conflict = self.on_conflict(name, args)
653
+ elif name == "ignore":
654
+ ignore = True
655
+ elif name in ("returning", "returningAll"):
656
+ if name == "returningAll":
657
+ returning.extend(self.star(None, froms))
658
+ else:
659
+ self.select_list(args, returning)
660
+ elif name in ("using", "from") and args:
661
+ for a in args:
662
+ using.extend(self.table_ref(a))
663
+ elif name == "$if" and len(args) == 2:
664
+ body = o.callback_body(args[1])
665
+ _b, inner = spine(body) if body is not None else (None, [])
666
+ for iname, iargs, icall in inner:
667
+ conditional(iname, iargs, icall, o.norm_expr(txt(args[0])))
668
+ elif name == "$call" and args:
669
+ self.lower(1, f"the builder passes through {o.trim(o.norm_expr(txt(args[0])), 60)}, which may add to the statement")
670
+ elif name == "modifyEnd" and args:
671
+ locks.append(self.val(args[0]))
672
+ elif name in ("clearSelect", "clearWhere", "clearLimit", "clearOffset"):
673
+ {"clearSelect": cols, "clearWhere": wheres}.get(name, []).clear()
674
+ if name == "clearLimit":
675
+ limit = ""
676
+ if name == "clearOffset":
677
+ offset = ""
678
+ else:
679
+ self.lower(1, f"step .{name}() is not translated")
680
+
681
+ def conditional(name: str, args: list[Node], call: Node, when: str = "") -> None:
682
+ text = f".{name}({', '.join(o.norm_expr(txt(a)) for a in args)})" + (f" when {when}" if when else "")
683
+ if name in ("where", "whereRef", "orWhere"):
684
+ wheres.append(mark("optional " + text))
685
+ elif name in ("having", "havingRef"):
686
+ havings.append(mark("optional " + text))
687
+ elif name in ("select", "selectAll"):
688
+ cols.append(mark("optional " + text))
689
+ elif name not in NO_OP:
690
+ self.notes.append(f"added under a condition: {o.trim(text, 100)}")
691
+
692
+ for name, args, call in post:
693
+ apply(name, args, call)
694
+ for name, args, call in self.conditional:
695
+ conditional(name, args, call)
696
+ if not self.executed and self.parent is None:
697
+ self.lower(1, "the builder is not executed in this expression: it is passed on or used as a subquery elsewhere")
698
+
699
+ head = ("WITH " + ", ".join(ctes) + " ") if ctes else ""
700
+ where = (" WHERE " + " AND ".join(wheres)) if wheres else ""
701
+ ret = (" RETURNING " + ", ".join(returning)) if returning else ""
702
+ if STAR in cols:
703
+ at = cols.index(STAR)
704
+ cols[at: at + 1] = self.star(None, froms) if not joins and self.parent is None else ["*"]
705
+ cols = [c for c in cols if c != STAR]
706
+ if self.kind == "select":
707
+ if not cols:
708
+ cols = self.star(None, froms) if self.parent is None else ["*"]
709
+ if self.parent is None:
710
+ self.notes.append("no column is selected in this expression")
711
+ sql = (f"{head}SELECT {distinct}{', '.join(cols)} FROM {', '.join(froms)}{''.join(' ' + j for j in joins)}{where}"
712
+ + (" GROUP BY " + ", ".join(groups) if groups else "")
713
+ + (" HAVING " + " AND ".join(havings) if havings else "")
714
+ + "".join(" " + s for s in sets)
715
+ + (" ORDER BY " + ", ".join(orders) if orders else "")
716
+ + (f" LIMIT {limit}" if limit else "") + (f" OFFSET {offset}" if offset else "")
717
+ + "".join(" " + lock for lock in locks))
718
+ elif self.kind == "insert":
719
+ target = froms[0]
720
+ uv = unwrap(values)
721
+ got = self.sub(uv) if uv is not None else None
722
+ if uv is not None and got is None and uv.type in ("arrow_function", "function_expression"):
723
+ body = o.callback_body(uv)
724
+ got = self.sub(body) if body is not None else None
725
+ uv = body if got is None and body is not None else uv
726
+ if got is not None:
727
+ body_sql = (f"({', '.join(columns_step)}) " if columns_step else "") + got[0]
728
+ else:
729
+ rows = o.array_items(uv)
730
+ first = rows[0] if rows else uv
731
+ if rows is None and uv is not None and uv.type == "call_expression": # xs.map((x) => ({...}))
732
+ a = uv.child_by_field_name("arguments")
733
+ cb = o.callback_body(a.named_children[0]) if a is not None and a.named_children else None
734
+ first = cb if cb is not None and cb.type == "object" else uv
735
+ obj = o.as_object(self.f, first, self.root) if first is not None else None
736
+ if obj is not None and (obj.entries or obj.extra):
737
+ names = [self.name(k) for k, _ in obj.entries] + [mark(e) for e in obj.extra]
738
+ vals = [self.val(v) for _, v in obj.entries] + [mark(e) for e in obj.extra]
739
+ body_sql = f"({', '.join(names)}) VALUES ({', '.join(vals)})"
740
+ elif uv is None:
741
+ body_sql = "DEFAULT VALUES"
742
+ else:
743
+ body_sql = f"({mark('columns of ' + txt(uv))}) VALUES ({mark_node(uv)})"
744
+ verb = "INSERT IGNORE INTO" if ignore and self.engine == "mysql" else "INSERT INTO"
745
+ sql = f"{head}{verb} {target} {body_sql}{conflict}{ret}"
746
+ elif self.kind == "update":
747
+ if not assigns:
748
+ assigns = [f"{mark('columns')} = {mark('values')}"]
749
+ self.lower(1, "the SET list is built elsewhere")
750
+ sql = (f"{head}UPDATE {froms[0]} SET {', '.join(assigns)}{' FROM ' + ', '.join(using) if using else ''}"
751
+ f"{''.join(' ' + j for j in joins)}{where}{ret}")
752
+ elif self.kind == "delete":
753
+ sql = (f"{head}DELETE FROM {froms[0]}{' USING ' + ', '.join(using) if using else ''}{''.join(' ' + j for j in joins)}{where}"
754
+ + (" ORDER BY " + ", ".join(orders) if orders else "") + (f" LIMIT {limit}" if limit else "") + ret)
755
+ else:
756
+ raise Skip("MERGE is not translated")
757
+ return sql
758
+
759
+ def join(self, kind: str, args: list[Node]) -> str:
760
+ if not args:
761
+ return f"{kind} {mark('?')}"
762
+ saved = self.main_table
763
+ self.main_table = self.main_table or "(join)"
764
+ try:
765
+ tables = self.table_ref(args[0])
766
+ except Skip:
767
+ tables = [mark_node(args[0])]
768
+ self.main_table = saved
769
+ table = tables[0]
770
+ if len(args) == 3:
771
+ return f"{kind} {table} ON {self.ref(args[1])} = {self.ref(args[2])}"
772
+ if len(args) == 2:
773
+ body = o.callback_body(args[1])
774
+ _b, steps = spine(body) if body is not None else (None, [])
775
+ preds = []
776
+ for name, sargs, _c in steps:
777
+ if name == "onRef" and len(sargs) == 3:
778
+ preds.append(self.predicate(sargs, ref_right=True))
779
+ elif name == "on":
780
+ preds.append(self.predicate(sargs))
781
+ elif name == "onTrue":
782
+ preds.append("TRUE")
783
+ return f"{kind} {table} ON {' AND '.join(preds) if preds else mark_node(args[1])}"
784
+ return f"{kind} {table}" + (" ON TRUE" if "LATERAL" in kind else "")
785
+
786
+ def order(self, args: list[Node], out: list[str]) -> None:
787
+ if not args:
788
+ return
789
+ first = unwrap(args[0])
790
+ items = o.array_items(first)
791
+ if items is not None:
792
+ for it in items:
793
+ s = o.string_value(it)
794
+ out.append((self.ident(s) or mark(s)) if s is not None else self.val(it))
795
+ return
796
+ s = o.string_value(first)
797
+ col = (self.ident(s) or mark(s)) if s is not None else self.val(first)
798
+ if len(args) > 1:
799
+ d = o.string_value(args[1])
800
+ if d is None:
801
+ body = o.callback_body(args[1])
802
+ dtext = txt(body) if body is not None else ""
803
+ if "desc" in dtext:
804
+ col += " DESC"
805
+ if "nullsLast" in dtext:
806
+ col += " NULLS LAST"
807
+ elif "nullsFirst" in dtext:
808
+ col += " NULLS FIRST"
809
+ if body is None:
810
+ self.notes.append(f"sort direction decided at run time: {mark_node(args[1])}")
811
+ elif d.lower().startswith("desc"):
812
+ col += " DESC" + (" NULLS LAST" if "nulls last" in d.lower() else " NULLS FIRST" if "nulls first" in d.lower() else "")
813
+ out.append(col)
814
+
815
+ def set_step(self, args: list[Node], assigns: list[str]) -> None:
816
+ if len(args) == 2:
817
+ assigns.append(f"{self.ref(args[0])} = {self.val(args[1])}")
818
+ return
819
+ a = unwrap(args[0]) if args else None
820
+ if a is not None and a.type in ("arrow_function", "function_expression"):
821
+ a = o.callback_body(a)
822
+ obj = o.as_object(self.f, a, self.root) if a is not None else None
823
+ if obj is None:
824
+ assigns.append(f"{mark('columns of ' + txt(a))} = {mark_node(a)}")
825
+ return
826
+ if obj.maybe:
827
+ self.notes.append("columns set under a condition: " + ", ".join(dict.fromkeys(k for k, _v, _t in obj.maybe)))
828
+ for k, v in obj.entries + [(k, v) for k, v, _t in obj.maybe]:
829
+ assigns.append(f"{self.name(k)} = {self.val(v)}")
830
+ for e in obj.extra:
831
+ assigns.append(f"{mark(e)} = {mark(e)}")
832
+
833
+ def on_conflict(self, name: str, args: list[Node]) -> str:
834
+ if name == "onDuplicateKeyUpdate":
835
+ sets: list[str] = []
836
+ self.set_step(args, sets)
837
+ return " ON DUPLICATE KEY UPDATE " + ", ".join(sets)
838
+ body = o.callback_body(args[0]) if args else None
839
+ _b, steps = spine(body) if body is not None else (None, [])
840
+ target, action, preds = "", "", []
841
+ for sname, sargs, _c in steps:
842
+ if sname == "column" and sargs:
843
+ target = f" ({self.ref(sargs[0])})"
844
+ elif sname == "columns" and sargs:
845
+ target = " (" + ", ".join(self.ref(i) for i in (o.array_items(sargs[0]) or [])) + ")"
846
+ elif sname == "constraint" and sargs:
847
+ target = f" ON CONSTRAINT {o.quote(self.engine, o.string_value(sargs[0]) or 'constraint')}"
848
+ elif sname == "expression" and sargs:
849
+ target = f" ({self.val(sargs[0])})"
850
+ elif sname == "doNothing":
851
+ action = " DO NOTHING"
852
+ elif sname == "doUpdateSet":
853
+ sets = []
854
+ self.set_step(sargs, sets)
855
+ action = " DO UPDATE SET " + ", ".join(sets)
856
+ elif sname in ("where", "whereRef"):
857
+ preds.append(self.predicate(sargs, ref_right=sname == "whereRef"))
858
+ if not action:
859
+ return f" ON CONFLICT{target} DO NOTHING"
860
+ return f" ON CONFLICT{target}{action}" + (" WHERE " + " AND ".join(preds) if preds else "")
861
+