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,1307 @@
1
+ """JPA / Hibernate mapping metadata and the translation of JPQL / HQL to SQL over the mapped tables.
2
+
3
+ Two parts, both free of I/O so they can be tested on text:
4
+
5
+ * `Model`: entities read from `@Entity`, `@Table`, `@Column`, `@Id`, `@JoinColumn`, the association annotations
6
+ with their join tables, `@Embedded`, `@MappedSuperclass` and single-table inheritance. It answers "which table
7
+ and column is `UserEntity.realmId`" and lists a table definition (columns, primary key, indexes) per entity.
8
+ * `translate()`: a JPQL or HQL statement rewritten as plain SQL: entity names become tables, paths `a.b.c` become
9
+ columns and joins, `JOIN FETCH` becomes a join whose columns are selected, constructor expressions become
10
+ their arguments, an entity in the select list becomes its columns. Named parameters stay as `:name`.
11
+
12
+ What cannot be translated raises `Untranslatable` with the reason; nothing is guessed.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from dataclasses import dataclass, field
19
+
20
+ from .schema import Table
21
+
22
+
23
+ class Untranslatable(Exception):
24
+ """The statement uses something this translator does not know. The message is the counted reason."""
25
+
26
+
27
+ # ------------------------------------------------------------------------------------------------ model
28
+ @dataclass
29
+ class Attr:
30
+ name: str
31
+ kind: str = "basic" # basic | id | embedded | embedded_id | to_one | to_many | elements | formula
32
+ column: str = "" # the column of a basic attribute, the foreign key of an owning to-one
33
+ type: str = "" # Java type; for associations and embeddables the target class
34
+ relation: str = "" # ManyToOne | OneToOne | OneToMany | ManyToMany
35
+ mapped_by: str = ""
36
+ join_table: str = ""
37
+ join_columns: list[str] = field(default_factory=list) # in the join/collection table: back to the owner
38
+ inverse_columns: list[str] = field(default_factory=list) # in the join table: to the target
39
+ fetch: str = "" # eager | lazy
40
+ batch_size: int = 0
41
+ overrides: dict[str, str] = field(default_factory=dict) # embedded attribute -> column
42
+ explicit: bool = False # the column name is written in the source, not derived by a naming strategy
43
+ unique: bool = False
44
+ line: int = 0
45
+ java_type: str = "" # declared type as written (List<Foo>)
46
+ key_column: str = "" # @MapKeyColumn of a map-valued collection
47
+ id_part: bool = False # @Id on an association: its foreign key is part of the primary key
48
+ snake: bool = False # names of this attribute go through Spring Boot's naming strategy
49
+
50
+
51
+ @dataclass
52
+ class Entity:
53
+ cls: str
54
+ name: str # entity name used in JPQL
55
+ kind: str = "entity" # entity | mapped | embeddable
56
+ table: str = ""
57
+ table_explicit: bool = False
58
+ supers: list[str] = field(default_factory=list)
59
+ attrs: dict[str, Attr] = field(default_factory=dict)
60
+ inheritance: str = "" # SINGLE_TABLE | JOINED | TABLE_PER_CLASS, on the root of a hierarchy
61
+ indexes: list[dict] = field(default_factory=list)
62
+ file: str = ""
63
+ line: int = 0
64
+ id_class: str = ""
65
+ snake: bool = False # the entity lives in (or is used by a repository of) a Spring Boot module
66
+
67
+
68
+ _SNAKE_SKIP = re.compile(r"[^A-Za-z0-9_.]")
69
+
70
+
71
+ def spring_snake(name: str) -> str:
72
+ """Spring Boot's physical naming strategy: dots to underscores, camel case to snake case, lower case."""
73
+ name = name.replace(".", "_")
74
+ out = []
75
+ for i, c in enumerate(name):
76
+ if 0 < i < len(name) - 1 and name[i - 1].islower() and c.isupper() and name[i + 1].islower():
77
+ out.append("_")
78
+ out.append(c)
79
+ return "".join(out).lower()
80
+
81
+
82
+ def _clean_name(name: str) -> str:
83
+ return name.strip().strip("`\"[]")
84
+
85
+
86
+ @dataclass
87
+ class OrmTable(Table):
88
+ """A table defined by an ORM mapping (JPA entity, Diesel `table!`). `indexes` ([{name, columns, unique}])
89
+ lists the primary key, unique constraints and declared indexes, the shape the TypeScript schemas use."""
90
+ indexes: list[dict] = field(default_factory=list)
91
+ source: str = "jpa"
92
+
93
+
94
+ JpaTable = OrmTable
95
+
96
+
97
+ class Model:
98
+ def __init__(self, snake: bool = False):
99
+ self.snake = snake # Spring Boot naming: names pass through `spring_snake`
100
+ self.entities: dict[str, Entity] = {} # class name -> entity, mapped superclass or embeddable
101
+ self.by_name: dict[str, Entity] = {} # JPQL entity name -> entity
102
+ self.supers: dict[str, list[str]] = {} # class -> superclasses, for classes that are not mapped too
103
+ # `pkg.Type.NAME` in a query: "enum" | ("value", text) | None when the type is not in the repository
104
+ self.constant = lambda path: None
105
+ self._attrs: dict[str, dict[str, Attr]] = {}
106
+
107
+ # ---- building ---------------------------------------------------------------------------------
108
+ def add(self, e: Entity) -> None:
109
+ if e.cls in self.entities and self.entities[e.cls].kind == "entity" and e.kind != "entity":
110
+ return
111
+ self.entities[e.cls] = e
112
+ if e.kind == "entity":
113
+ self.by_name[e.name] = e
114
+ self._attrs.clear()
115
+
116
+ def name(self, written: str, explicit: bool) -> str:
117
+ """A name as written in the mapping. Spring Boot's naming strategy is applied per entity (make_snake)."""
118
+ return _clean_name(written)
119
+
120
+ @staticmethod
121
+ def _nm(text: str, snake: bool) -> str:
122
+ return spring_snake(text) if snake else text
123
+
124
+ def make_snake(self, e: Entity) -> None:
125
+ """Spring Boot's physical naming strategy for one entity: every name, written or derived, becomes
126
+ snake case. Decided per entity, because one repository can hold Spring Boot and plain JPA modules."""
127
+ if e.snake:
128
+ return
129
+ e.snake = True
130
+ self.snake = True
131
+ if e.table:
132
+ e.table = ".".join(spring_snake(p) for p in e.table.split("."))
133
+ for ix in e.indexes:
134
+ ix["columns"] = [spring_snake(c) for c in ix["columns"]]
135
+ for a in e.attrs.values():
136
+ a.snake = True
137
+ a.column = spring_snake(a.column) if a.column else a.column
138
+ a.join_table = ".".join(spring_snake(p) for p in a.join_table.split(".")) if a.join_table else a.join_table
139
+ a.join_columns = [spring_snake(c) for c in a.join_columns]
140
+ a.inverse_columns = [spring_snake(c) for c in a.inverse_columns]
141
+ a.key_column = spring_snake(a.key_column) if a.key_column else a.key_column
142
+ a.overrides = {k: spring_snake(v) for k, v in a.overrides.items()}
143
+ self._attrs.clear()
144
+
145
+ # ---- lookups ----------------------------------------------------------------------------------
146
+ def entity(self, name: str) -> Entity | None:
147
+ name = name.rsplit(".", 1)[-1]
148
+ e = self.by_name.get(name) or self.entities.get(name)
149
+ if e is None:
150
+ low = name.lower()
151
+ hits = [x for n, x in self.by_name.items() if n.lower() == low]
152
+ e = hits[0] if len(hits) == 1 else None
153
+ return e if e is not None and e.kind == "entity" else None
154
+
155
+ def chain(self, e: Entity) -> list[Entity]:
156
+ """The entity and its mapped ancestors, nearest first."""
157
+ out, seen, queue = [], set(), [e.cls]
158
+ while queue:
159
+ cls = queue.pop(0)
160
+ if cls in seen:
161
+ continue
162
+ seen.add(cls)
163
+ cur = self.entities.get(cls)
164
+ if cur is not None:
165
+ out.append(cur)
166
+ queue.extend(cur.supers)
167
+ else:
168
+ queue.extend(self.supers.get(cls, ()))
169
+ return out
170
+
171
+ def root(self, e: Entity) -> Entity:
172
+ """The entity whose table holds this entity's rows: the top entity of a single-table hierarchy."""
173
+ top = e
174
+ for anc in self.chain(e)[1:]:
175
+ if anc.kind == "entity":
176
+ top = anc
177
+ if top is not e and (top.inheritance or "SINGLE_TABLE") == "SINGLE_TABLE" and not e.table_explicit:
178
+ return top
179
+ return e
180
+
181
+ def table(self, e: Entity) -> str:
182
+ r = self.root(e)
183
+ return r.table or self._nm(r.name, r.snake)
184
+
185
+ def attrs(self, e: Entity) -> dict[str, Attr]:
186
+ cached = self._attrs.get(e.cls)
187
+ if cached is None:
188
+ cached = {}
189
+ for anc in reversed(self.chain(e)):
190
+ cached.update(anc.attrs)
191
+ self._attrs[e.cls] = cached
192
+ return cached
193
+
194
+ def attr(self, e: Entity, name: str) -> Attr | None:
195
+ attrs = self.attrs(e)
196
+ a = attrs.get(name)
197
+ if a is None:
198
+ low = name.lower()
199
+ hits = [x for n, x in attrs.items() if n.lower() == low]
200
+ a = hits[0] if len(hits) == 1 else None
201
+ return a
202
+
203
+ def embeddable(self, cls: str) -> Entity | None:
204
+ e = self.entities.get(cls.rsplit(".", 1)[-1])
205
+ return e if e is not None and e.kind in ("embeddable", "mapped", "entity") else None
206
+
207
+ def column(self, a: Attr) -> str:
208
+ return a.column or self._nm(a.name, a.snake)
209
+
210
+ def embedded_columns(self, a: Attr, overrides: dict[str, str] | None = None, prefix: str = "") -> list[tuple[str, str]]:
211
+ """(attribute path, column) of every column an embedded attribute spans."""
212
+ emb = self.embeddable(a.type)
213
+ if emb is None:
214
+ return []
215
+ over = {**a.overrides, **(overrides or {})}
216
+ out = []
217
+ for sub in self.attrs(emb).values():
218
+ path = prefix + sub.name
219
+ if sub.kind in ("basic", "id"):
220
+ out.append((path, over.get(sub.name) or self.column(sub)))
221
+ elif sub.kind == "to_one" and not sub.mapped_by:
222
+ out.append((path, over.get(sub.name) or self.fk(sub)))
223
+ elif sub.kind in ("embedded", "embedded_id"):
224
+ nested = {k[len(sub.name) + 1:]: v for k, v in over.items() if k.startswith(sub.name + ".")}
225
+ out.extend(self.embedded_columns(sub, nested, path + "."))
226
+ return out
227
+
228
+ def pk(self, e: Entity) -> list[str]:
229
+ cols = []
230
+ for a in self.attrs(e).values():
231
+ if a.kind == "id":
232
+ cols.append(self.column(a))
233
+ elif a.kind == "embedded_id":
234
+ cols.extend(c for _, c in self.embedded_columns(a))
235
+ elif a.kind == "to_one" and a.id_part and not a.mapped_by:
236
+ cols.append(self.fk(a))
237
+ return cols
238
+
239
+ def pk_attr(self, e: Entity) -> Attr | None:
240
+ ids = [a for a in self.attrs(e).values() if a.kind in ("id", "embedded_id")]
241
+ return ids[0] if len(ids) == 1 else None
242
+
243
+ def fk(self, a: Attr) -> str:
244
+ """The foreign-key column of an owning to-one association."""
245
+ if a.column:
246
+ return a.column
247
+ target = self.entities.get(a.type)
248
+ pk = self.pk(target) if target is not None else []
249
+ return self._nm(f"{a.name}_{pk[0] if len(pk) == 1 else 'id'}", a.snake)
250
+
251
+ def columns(self, e: Entity) -> list[str]:
252
+ """Every column the entity's own table row has, in declaration order."""
253
+ out: list[str] = []
254
+ for a in self.attrs(e).values():
255
+ if a.kind in ("basic", "id"):
256
+ out.append(self.column(a))
257
+ elif a.kind in ("embedded", "embedded_id"):
258
+ out.extend(c for _, c in self.embedded_columns(a))
259
+ elif a.kind == "to_one" and not a.mapped_by:
260
+ out.append(self.fk(a))
261
+ seen: set[str] = set()
262
+ return [c for c in out if not (c in seen or seen.add(c))]
263
+
264
+ def inverse(self, owner: Entity, a: Attr) -> tuple[Entity, Attr] | None:
265
+ """For `mappedBy`: the attribute on the other side that owns the association."""
266
+ target = self.entities.get(a.type)
267
+ if target is None or not a.mapped_by:
268
+ return None
269
+ other = self.attr(target, a.mapped_by.split(".")[-1])
270
+ return (target, other) if other is not None else None
271
+
272
+ def collection_table(self, owner: Entity, a: Attr) -> tuple[str, str, str]:
273
+ """(table, column back to the owner, column to the target) of a join or collection table."""
274
+ if a.mapped_by:
275
+ inv = self.inverse(owner, a)
276
+ if inv is None:
277
+ raise Untranslatable("mappedBy names an attribute that was not found")
278
+ target, other = inv
279
+ table, back, to = self.collection_table(target, other)
280
+ return table, to, back
281
+ target = self.entities.get(a.type)
282
+ table = a.join_table or self._nm(f"{self.table(owner)}_{self.table(target) if target is not None else a.name}", a.snake)
283
+ opk = self.pk(owner)
284
+ back = a.join_columns[0] if a.join_columns else self._nm(f"{owner.name}_{opk[0] if len(opk) == 1 else 'id'}", a.snake)
285
+ if a.kind == "elements":
286
+ return table, back, a.column or self._nm(a.name, a.snake)
287
+ tpk = self.pk(target) if target is not None else []
288
+ to = a.inverse_columns[0] if a.inverse_columns else self._nm(f"{a.name}_{tpk[0] if len(tpk) == 1 else 'id'}", a.snake)
289
+ return table, back, to
290
+
291
+ # ---- table definitions ------------------------------------------------------------------------
292
+ def tables(self) -> list[JpaTable]:
293
+ out: dict[str, JpaTable] = {}
294
+ for e in self.entities.values():
295
+ if e.kind != "entity":
296
+ continue
297
+ name = self.table(e)
298
+ if not re.fullmatch(r"[A-Za-z_][\w.$]*", name or ""):
299
+ continue
300
+ cols = []
301
+ attrs = self.attrs(e)
302
+ for a in attrs.values():
303
+ if a.kind in ("basic", "id"):
304
+ cols.append({"name": self.column(a), "type": a.type})
305
+ elif a.kind in ("embedded", "embedded_id"):
306
+ cols.extend({"name": c, "type": ""} for _, c in self.embedded_columns(a))
307
+ elif a.kind == "to_one" and not a.mapped_by:
308
+ cols.append({"name": self.fk(a), "type": a.type})
309
+ pk = self.pk(e)
310
+ indexes = [{"name": "", "columns": pk, "unique": True, "primary": True}] if pk else []
311
+ for anc in self.chain(e):
312
+ indexes.extend(anc.indexes)
313
+ indexes.extend({"name": "", "columns": [self.column(a)], "unique": True} for a in attrs.values()
314
+ if a.unique and a.kind == "basic")
315
+ t = out.get(name)
316
+ if t is None:
317
+ out[name] = JpaTable(name=name, columns=cols, defined_at=[f"{e.file}:{e.line}"], primary_key=", ".join(pk),
318
+ indexes=indexes)
319
+ else: # a single-table hierarchy: the subclasses add their columns
320
+ have = {c["name"] for c in t.columns}
321
+ t.columns.extend(c for c in cols if c["name"] not in have)
322
+ t.defined_at.append(f"{e.file}:{e.line}")
323
+ # join and collection tables this entity owns
324
+ for a in attrs.values():
325
+ if a.kind in ("to_many", "elements") and not a.mapped_by and (a.join_table or a.kind == "elements" or a.relation == "ManyToMany"):
326
+ try:
327
+ jt, back, to = self.collection_table(e, a)
328
+ except Untranslatable:
329
+ continue
330
+ if jt and jt not in out and re.fullmatch(r"[A-Za-z_][\w.$]*", jt):
331
+ out[jt] = JpaTable(name=jt, columns=[{"name": back, "type": ""}, {"name": to, "type": ""}],
332
+ defined_at=[f"{e.file}:{a.line or e.line}"], indexes=[])
333
+ return list(out.values())
334
+
335
+
336
+ # ------------------------------------------------------------------------------------------ JPQL tokens
337
+ _TOKEN = re.compile(r"""
338
+ (?P<ws>\s+|--[^\n]*|/\*.*?\*/)
339
+ | (?P<ph>«[^»]*»)
340
+ | (?P<str>'(?:[^']|'')*')
341
+ | (?P<spel>[:?]?\#\{(?:[^{}]|\{[^{}]*\})*\})
342
+ | (?P<param>:[A-Za-z_][\w.]*|\?\d*)
343
+ | (?P<num>\d+(?:\.\d+)?(?:[eE][+-]?\d+)?[LlDdFf]?)
344
+ | (?P<id>[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*(?:\.\*)?)
345
+ | (?P<op><>|!=|\^=|<=|>=|\|\||::|[=<>+\-*/%(),;\[\].])
346
+ """, re.X | re.S)
347
+
348
+
349
+ @dataclass
350
+ class Tok:
351
+ kind: str # id | str | num | param | ph | op | grp | spel
352
+ text: str = ""
353
+ items: list["Tok"] = field(default_factory=list)
354
+
355
+ @property
356
+ def up(self) -> str:
357
+ return self.text.upper() if self.kind == "id" else ""
358
+
359
+
360
+ def tokenize(text: str) -> list[Tok]:
361
+ stack: list[list[Tok]] = [[]]
362
+ pos = 0
363
+ while pos < len(text):
364
+ m = _TOKEN.match(text, pos)
365
+ if m is None:
366
+ raise Untranslatable("character the JPQL reader does not know")
367
+ pos = m.end()
368
+ kind = m.lastgroup
369
+ if kind == "ws":
370
+ continue
371
+ t = m.group(0)
372
+ if kind == "op" and t == "(":
373
+ stack.append([])
374
+ elif kind == "op" and t == ")":
375
+ if len(stack) == 1:
376
+ raise Untranslatable("unbalanced parentheses")
377
+ items = stack.pop()
378
+ stack[-1].append(Tok("grp", "", items))
379
+ else:
380
+ stack[-1].append(Tok(kind, t))
381
+ if len(stack) != 1:
382
+ raise Untranslatable("unbalanced parentheses")
383
+ return stack[0]
384
+
385
+
386
+ KEYWORDS = {
387
+ "SELECT", "FROM", "WHERE", "GROUP", "BY", "HAVING", "ORDER", "AND", "OR", "NOT", "IN", "LIKE", "ILIKE", "IS", "NULL",
388
+ "BETWEEN", "CASE", "WHEN", "THEN", "ELSE", "END", "AS", "DISTINCT", "ASC", "DESC", "NULLS", "FIRST", "LAST", "EXISTS",
389
+ "ALL", "ANY", "SOME", "TRUE", "FALSE", "EMPTY", "MEMBER", "OF", "ESCAPE", "JOIN", "LEFT", "RIGHT", "INNER", "OUTER",
390
+ "FULL", "CROSS", "FETCH", "ON", "WITH", "SET", "UPDATE", "DELETE", "INSERT", "INTO", "VALUES", "UNION", "INTERSECT",
391
+ "EXCEPT", "LIMIT", "OFFSET", "ROWS", "ROW", "ONLY", "NEXT", "BOTH", "LEADING", "TRAILING", "CURRENT_DATE",
392
+ "CURRENT_TIME", "CURRENT_TIMESTAMP", "LOCAL", "DATE", "TIME", "DATETIME", "OVER", "PARTITION", "FILTER", "WITHIN",
393
+ "YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND", "WEEK", "QUARTER", "EPOCH", "INTERVAL", "COLLATE", "NEW",
394
+ "OBJECT", "TIES", "PERCENT", "RECURSIVE", "LATERAL", "UNBOUNDED", "PRECEDING", "FOLLOWING", "CURRENT", "RANGE",
395
+ }
396
+ CLAUSE_WORDS = ("SELECT", "FROM", "WHERE", "GROUP", "HAVING", "ORDER", "LIMIT", "OFFSET", "SET", "FETCH", "VALUES")
397
+ JOIN_WORDS = ("JOIN", "LEFT", "RIGHT", "INNER", "FULL", "CROSS")
398
+ SET_OPS = ("UNION", "INTERSECT", "EXCEPT")
399
+ CAST_TYPES = {"STRING": "VARCHAR", "INTEGER": "INTEGER", "INT": "INTEGER", "LONG": "BIGINT", "SHORT": "SMALLINT",
400
+ "DOUBLE": "DOUBLE PRECISION", "FLOAT": "REAL", "BIGDECIMAL": "DECIMAL", "BIGINTEGER": "NUMERIC",
401
+ "BOOLEAN": "BOOLEAN", "CHARACTER": "CHAR", "LOCALDATE": "DATE", "LOCALDATETIME": "TIMESTAMP",
402
+ "INSTANT": "TIMESTAMP", "UUID": "UUID", "BYTE": "SMALLINT", "TEXT": "TEXT"}
403
+ UNSUPPORTED_FUNCS = {"KEY", "VALUE", "ENTRY", "INDEX", "TREAT", "ELEMENTS", "INDICES", "MAXELEMENT", "MINELEMENT",
404
+ "MAXINDEX", "MININDEX", "TYPE"}
405
+ ENUM_PATH = re.compile(r"^(?:[\w$]+\.)*[A-Z][\w$]*\.[A-Z][A-Z0-9_]*$")
406
+
407
+
408
+ @dataclass
409
+ class Bind:
410
+ kind: str # entity | embed | elem | subq
411
+ q: str # SQL qualifier (alias, or the table name in UPDATE and DELETE)
412
+ entity: Entity | None = None
413
+ overrides: dict[str, str] = field(default_factory=dict)
414
+ value_col: str = ""
415
+ owner: Entity | None = None
416
+ key_col: str = ""
417
+
418
+
419
+ @dataclass
420
+ class Coll:
421
+ """A path that ends in a collection: usable only in IS EMPTY, SIZE() and MEMBER OF."""
422
+ bind: Bind
423
+ attr: Attr
424
+
425
+
426
+ class Env:
427
+ def __init__(self, parent: "Env | None" = None):
428
+ self.parent = parent
429
+ self.binds: dict[str, Bind] = {}
430
+ self.order: list[str] = []
431
+
432
+ def add(self, alias: str, b: Bind) -> None:
433
+ self.binds[alias.lower()] = b
434
+ self.order.append(alias.lower())
435
+
436
+ def get(self, alias: str) -> Bind | None:
437
+ env: Env | None = self
438
+ while env is not None:
439
+ b = env.binds.get(alias.lower())
440
+ if b is not None:
441
+ return b
442
+ env = env.parent
443
+ return None
444
+
445
+ def default(self) -> Bind | None:
446
+ roots = [b for b in self.binds.values() if b.kind == "entity"]
447
+ return roots[0] if len(roots) >= 1 and (len(roots) == 1 or "" in self.binds) else None
448
+
449
+ def taken(self, alias: str) -> bool:
450
+ return self.get(alias) is not None
451
+
452
+
453
+ @dataclass
454
+ class Result:
455
+ sql: str
456
+ notes: list[str] = field(default_factory=list)
457
+ selected: list[Entity] = field(default_factory=list) # entities returned whole by the outermost SELECT
458
+ fetched: list[tuple[str, str]] = field(default_factory=list) # (entity class, attribute) joined with FETCH
459
+ kind: str = "select"
460
+ root: Entity | None = None
461
+ assumed: bool = False # a table or column name came from the naming strategy, not from the source
462
+
463
+
464
+ class _Block:
465
+ """One SELECT / UPDATE / DELETE being translated: its FROM pieces and the implicit joins found on the way."""
466
+
467
+ def __init__(self, env: Env, mutating: bool = False):
468
+ self.env = env
469
+ self.pieces: list[str] = []
470
+ self.sink: list[str] = self.pieces
471
+ self.implicit: dict[tuple[str, str], Bind] = {}
472
+ self.mutating = mutating
473
+ self.n = 0
474
+
475
+
476
+ class Translator:
477
+ def __init__(self, model: Model):
478
+ self.m = model
479
+ self.notes: list[str] = []
480
+ self.selected: list[Entity] = []
481
+ self.fetched: list[tuple[str, str]] = []
482
+ self.assumed = False
483
+ self.depth = 0
484
+ self._aliases = 0
485
+ self.no_expand = False
486
+
487
+ def note(self, text: str) -> None:
488
+ if text not in self.notes:
489
+ self.notes.append(text)
490
+
491
+ # ---- names ------------------------------------------------------------------------------------
492
+ def _col(self, a: Attr) -> str:
493
+ if not a.explicit:
494
+ self.assumed = True
495
+ return self.m.column(a)
496
+
497
+ def _table(self, e: Entity) -> str:
498
+ r = self.m.root(e)
499
+ if not r.table_explicit:
500
+ self.assumed = True
501
+ if r is not e:
502
+ self.note(f"{e.name} is stored in the table of {r.name} (single-table inheritance); the discriminator predicate is not shown")
503
+ elif r.inheritance == "JOINED":
504
+ self.note(f"{e.name} uses JOINED inheritance; columns of the other tables in the hierarchy are not joined")
505
+ return self.m.table(e)
506
+
507
+ def _pk(self, e: Entity) -> list[str]:
508
+ pk = self.m.pk(e)
509
+ if not pk:
510
+ raise Untranslatable("entity without a mapped @Id")
511
+ return pk
512
+
513
+ def _fresh(self, block: _Block, base: str) -> str:
514
+ base = re.sub(r"\W", "_", base)[:20].lower() or "j"
515
+ while True:
516
+ self._aliases += 1
517
+ alias = f"{base}_{self._aliases}"
518
+ if not block.env.taken(alias):
519
+ return alias
520
+
521
+ # ---- statements -------------------------------------------------------------------------------
522
+ def statement(self, items: list[Tok], env: Env | None = None) -> str:
523
+ while items and items[-1].kind == "op" and items[-1].text == ";":
524
+ items = items[:-1]
525
+ # ( query ) at the top
526
+ while len(items) == 1 and items[0].kind == "grp":
527
+ items = items[0].items
528
+ if not items:
529
+ raise Untranslatable("empty statement")
530
+ parts, ops, cur = [], [], []
531
+ i = 0
532
+ while i < len(items):
533
+ t = items[i]
534
+ if t.up in SET_OPS:
535
+ parts.append(cur)
536
+ op = t.up
537
+ if i + 1 < len(items) and items[i + 1].up in ("ALL", "DISTINCT"):
538
+ op += " " + items[i + 1].up
539
+ i += 1
540
+ ops.append(op)
541
+ cur = []
542
+ else:
543
+ cur.append(t)
544
+ i += 1
545
+ parts.append(cur)
546
+ if len(parts) > 1:
547
+ out = [self.statement(parts[0], env)]
548
+ for op, p in zip(ops, parts[1:]):
549
+ out.append(op)
550
+ out.append(self.statement(p, env))
551
+ return " ".join(out)
552
+ head = items[0].up
553
+ if head in ("SELECT", "FROM"):
554
+ return self._select(items, env)
555
+ if head == "UPDATE":
556
+ return self._update(items, env)
557
+ if head == "DELETE":
558
+ return self._delete(items, env)
559
+ if head == "INSERT":
560
+ return self._insert(items, env)
561
+ if head == "WITH":
562
+ raise Untranslatable("WITH (common table expression) in HQL")
563
+ raise Untranslatable("not a SELECT, UPDATE, DELETE or INSERT")
564
+
565
+ @staticmethod
566
+ def _clauses(items: list[Tok], words: tuple[str, ...] = CLAUSE_WORDS) -> list[tuple[str, list[Tok]]]:
567
+ out: list[tuple[str, list[Tok]]] = []
568
+ name, cur = "", []
569
+ i = 0
570
+ while i < len(items):
571
+ t = items[i]
572
+ up = t.up
573
+ nxt = items[i + 1] if i + 1 < len(items) else None
574
+ is_clause = up in words and "." not in t.text
575
+ if is_clause and up in ("GROUP", "ORDER") and not (nxt is not None and nxt.up == "BY"):
576
+ is_clause = False
577
+ if is_clause and up == "FETCH" and not (nxt is not None and nxt.up in ("FIRST", "NEXT")):
578
+ is_clause = False
579
+ if is_clause and up in ("LIMIT", "OFFSET", "VALUES", "SET") and nxt is None:
580
+ is_clause = False
581
+ if is_clause and up == "FROM" and name == "DELETE" and not cur:
582
+ is_clause = False
583
+ if is_clause and up == "SELECT" and name == "INSERT":
584
+ is_clause = True
585
+ if is_clause:
586
+ if name or cur:
587
+ out.append((name, cur))
588
+ name, cur = up, []
589
+ if up in ("GROUP", "ORDER"):
590
+ i += 1
591
+ else:
592
+ cur.append(t)
593
+ i += 1
594
+ out.append((name, cur))
595
+ return out
596
+
597
+ def _select(self, items: list[Tok], parent: Env | None) -> str:
598
+ top = self.depth == 0 and parent is None
599
+ self.depth += 1
600
+ try:
601
+ clauses = self._clauses(items)
602
+ get = {n: c for n, c in clauses}
603
+ if "FROM" not in get:
604
+ raise Untranslatable("SELECT without FROM")
605
+ env = Env(parent)
606
+ block = _Block(env)
607
+ fetch_binds = self._from(get["FROM"], block)
608
+ sel_items = get.get("SELECT")
609
+ if sel_items is None:
610
+ first = env.binds[env.order[0]]
611
+ select = self._entity_columns(first, top)
612
+ else:
613
+ select = self._select_list(sel_items, block, top)
614
+ for b in fetch_binds:
615
+ if b.entity is not None and sel_items is not None and "COUNT" not in {t.up for t in sel_items}:
616
+ select += ", " + ", ".join(f"{b.q}.{c}" for c in self.m.columns(b.entity))
617
+ tail = []
618
+ for name, toks in clauses:
619
+ if name in ("SELECT", "FROM", ""):
620
+ continue
621
+ kw = {"GROUP": "GROUP BY", "ORDER": "ORDER BY"}.get(name, name)
622
+ tail.append(kw + " " + self._expr(toks, block))
623
+ return "SELECT " + select + " FROM " + " ".join(block.pieces) + (" " + " ".join(tail) if tail else "")
624
+ finally:
625
+ self.depth -= 1
626
+
627
+ def _update(self, items: list[Tok], parent: Env | None) -> str:
628
+ clauses = self._clauses(items[1:], ("SET", "WHERE"))
629
+ head = clauses[0][1]
630
+ if not head or head[0].kind != "id":
631
+ raise Untranslatable("UPDATE without an entity name")
632
+ if head[0].up == "VERSIONED":
633
+ head = head[1:]
634
+ e = self.m.entity(head[0].text)
635
+ if e is None:
636
+ raise Untranslatable("entity not found: mapping not in the repository")
637
+ table = self._table(e)
638
+ env = Env(parent)
639
+ block = _Block(env, mutating=True)
640
+ alias = next((t.text for t in head[1:] if t.kind == "id" and t.up != "AS"), "")
641
+ bind = Bind("entity", table, e)
642
+ env.add(alias, bind)
643
+ if alias:
644
+ env.add("", bind)
645
+ sets, where = [], ""
646
+ for name, toks in clauses[1:]:
647
+ if name == "SET":
648
+ for part in _split(toks, ","):
649
+ eq = next((k for k, t in enumerate(part) if t.kind == "op" and t.text == "="), -1)
650
+ if eq < 1:
651
+ raise Untranslatable("SET item without '='")
652
+ target = self._expr(part[:eq], block)
653
+ sets.append(target.rsplit(".", 1)[-1] + " = " + self._expr(part[eq + 1:], block))
654
+ elif name == "WHERE":
655
+ where = " WHERE " + self._expr(toks, block)
656
+ if not sets:
657
+ raise Untranslatable("UPDATE without SET")
658
+ if block.pieces:
659
+ raise Untranslatable("path through an association in UPDATE or DELETE")
660
+ self.root_entity = e
661
+ return f"UPDATE {table} SET " + ", ".join(sets) + where
662
+
663
+ def _delete(self, items: list[Tok], parent: Env | None) -> str:
664
+ rest = items[1:]
665
+ if rest and rest[0].up == "FROM":
666
+ rest = rest[1:]
667
+ clauses = self._clauses(rest, ("WHERE",))
668
+ head = clauses[0][1]
669
+ if not head or head[0].kind != "id":
670
+ raise Untranslatable("DELETE without an entity name")
671
+ e = self.m.entity(head[0].text)
672
+ if e is None:
673
+ raise Untranslatable("entity not found: mapping not in the repository")
674
+ table = self._table(e)
675
+ env = Env(parent)
676
+ block = _Block(env, mutating=True)
677
+ alias = next((t.text for t in head[1:] if t.kind == "id" and t.up != "AS"), "")
678
+ bind = Bind("entity", table, e)
679
+ env.add(alias, bind)
680
+ if alias:
681
+ env.add("", bind)
682
+ where = ""
683
+ for name, toks in clauses[1:]:
684
+ if name == "WHERE":
685
+ where = " WHERE " + self._expr(toks, block)
686
+ if block.pieces:
687
+ raise Untranslatable("path through an association in UPDATE or DELETE")
688
+ self.root_entity = e
689
+ return f"DELETE FROM {table}" + where
690
+
691
+ def _insert(self, items: list[Tok], parent: Env | None) -> str:
692
+ rest = items[1:]
693
+ if rest and rest[0].up == "INTO":
694
+ rest = rest[1:]
695
+ if len(rest) < 2 or rest[0].kind != "id":
696
+ raise Untranslatable("INSERT without an entity name")
697
+ e = self.m.entity(rest[0].text)
698
+ if e is None:
699
+ raise Untranslatable("entity not found: mapping not in the repository")
700
+ table = self._table(e)
701
+ cols = ""
702
+ k = 1
703
+ if rest[k].kind == "grp":
704
+ env = Env(parent)
705
+ block = _Block(env, mutating=True)
706
+ env.add("", Bind("entity", table, e))
707
+ cols = " (" + ", ".join(self._expr(p, block).rsplit(".", 1)[-1] for p in _split(rest[k].items, ",")) + ")"
708
+ k += 1
709
+ body = rest[k:]
710
+ if not body:
711
+ raise Untranslatable("INSERT without a source")
712
+ self.root_entity = e
713
+ if body[0].up == "VALUES":
714
+ env = Env(parent)
715
+ env.add("", Bind("entity", table, e))
716
+ tail = self._expr(body[1:], _Block(env, mutating=True))
717
+ return f"INSERT INTO {table}{cols} VALUES " + re.sub(r"(?<![\w.])" + re.escape(table) + r"\.", "", tail)
718
+ self.no_expand = True
719
+ return f"INSERT INTO {table}{cols} " + self.statement(body, parent)
720
+
721
+ # ---- FROM -------------------------------------------------------------------------------------
722
+ def _from(self, toks: list[Tok], block: _Block) -> list[Bind]:
723
+ env = block.env
724
+ fetched: list[Bind] = []
725
+ i, n = 0, len(toks)
726
+ first = True
727
+
728
+ def alias_at(k: int) -> tuple[str, int]:
729
+ if k < n and toks[k].up == "AS":
730
+ k += 1
731
+ if k < n and toks[k].kind == "id" and "." not in toks[k].text and toks[k].up not in JOIN_WORDS + ("ON", "WITH", "FETCH", "WHERE"):
732
+ return toks[k].text, k + 1
733
+ return "", k
734
+
735
+ while i < n:
736
+ t = toks[i]
737
+ if t.kind == "op" and t.text == ",":
738
+ i += 1
739
+ continue
740
+ join_kw = ""
741
+ if t.up in JOIN_WORDS and not (i + 1 < n and toks[i + 1].kind == "grp" and t.up in ("LEFT", "RIGHT")):
742
+ words = []
743
+ while i < n and toks[i].up in JOIN_WORDS + ("OUTER",):
744
+ words.append(toks[i].up)
745
+ i += 1
746
+ if "JOIN" not in words:
747
+ raise Untranslatable("join keyword without JOIN")
748
+ join_kw = " ".join(words)
749
+ fetch = False
750
+ if i < n and toks[i].up == "FETCH":
751
+ fetch = True
752
+ i += 1
753
+ if i >= n:
754
+ raise Untranslatable("JOIN without a target")
755
+ target = toks[i]
756
+ i += 1
757
+ alias, i = alias_at(i)
758
+ cond: list[Tok] = []
759
+ if i < n and toks[i].up in ("ON", "WITH"):
760
+ i += 1
761
+ while i < n and not (toks[i].kind == "op" and toks[i].text == ",") and not (
762
+ toks[i].up in JOIN_WORDS and not (i + 1 < n and toks[i + 1].kind == "grp")):
763
+ cond.append(toks[i])
764
+ i += 1
765
+ b = self._join(block, join_kw, target, alias, cond)
766
+ if fetch and b is not None:
767
+ fetched.append(b)
768
+ continue
769
+ if t.up == "IN" and i + 1 < n and toks[i + 1].kind == "grp": # FROM Order o, IN (o.items) i
770
+ inner = toks[i + 1].items
771
+ if len(inner) != 1 or inner[0].kind != "id":
772
+ raise Untranslatable("IN (collection) in FROM with something other than a path")
773
+ alias, i = alias_at(i + 2)
774
+ self._join(block, "JOIN", inner[0], alias, [])
775
+ continue
776
+ # a root: an entity or a subquery
777
+ if t.kind == "grp":
778
+ alias, i = alias_at(i + 1)
779
+ sub = self.statement(t.items, env)
780
+ alias = alias or self._fresh(block, "sub")
781
+ env.add(alias, Bind("subq", alias))
782
+ block.pieces.append(("" if first else "CROSS JOIN ") + f"({sub}) {alias}")
783
+ elif t.kind == "id":
784
+ e = self.m.entity(t.text)
785
+ if e is None:
786
+ raise Untranslatable("entity not found: mapping not in the repository")
787
+ alias, i = alias_at(i + 1)
788
+ table = self._table(e)
789
+ q = alias or self._fresh(block, e.name[:1])
790
+ b = Bind("entity", q, e)
791
+ env.add(alias, b)
792
+ if not alias:
793
+ env.add(q, b)
794
+ block.pieces.append(("" if first else "CROSS JOIN ") + f"{table} {q}")
795
+ elif t.kind == "ph":
796
+ raise Untranslatable("entity name decided at run time")
797
+ else:
798
+ raise Untranslatable("FROM item that is not an entity")
799
+ first = False
800
+ if first:
801
+ raise Untranslatable("FROM without an entity")
802
+ return fetched
803
+
804
+ def _join(self, block: _Block, kw: str, target: Tok, alias: str, cond: list[Tok]) -> Bind | None:
805
+ env = block.env
806
+ if target.kind == "grp":
807
+ sub = self.statement(target.items, env)
808
+ alias = alias or self._fresh(block, "sub")
809
+ env.add(alias, Bind("subq", alias))
810
+ on = self._on(block, cond)
811
+ block.pieces.append(f"{kw} ({sub}) {alias}" + (f" ON {on}" if on else " ON 1 = 1"))
812
+ return None
813
+ if target.kind != "id":
814
+ raise Untranslatable("JOIN target that is not a path or an entity")
815
+ comps = target.text.split(".")
816
+ head = env.get(comps[0]) if len(comps) > 1 else None
817
+ if head is None:
818
+ e = self.m.entity(target.text)
819
+ if e is None:
820
+ if len(comps) > 1:
821
+ raise Untranslatable("join path starts at an unknown alias")
822
+ raise Untranslatable("entity not found: mapping not in the repository")
823
+ q = alias or self._fresh(block, e.name[:1])
824
+ b = Bind("entity", q, e)
825
+ table = self._table(e)
826
+ env.add(alias or q, b)
827
+ on = self._on(block, cond)
828
+ block.pieces.append(f"{kw} {table} {q} ON {on}" if on else f"CROSS JOIN {table} {q}")
829
+ return b
830
+ cur = head
831
+ for comp in comps[1:-1]:
832
+ nxt = self._step(block, cur, comp, False)
833
+ if not isinstance(nxt, Bind):
834
+ raise Untranslatable("join path through a column or a collection")
835
+ cur = nxt
836
+ b = self._assoc_join(block, cur, comps[-1], kw, alias)
837
+ if cond:
838
+ on = self._on(block, cond)
839
+ block.pieces[-1] += f" AND ({on})"
840
+ return b
841
+
842
+ def _on(self, block: _Block, cond: list[Tok]) -> str:
843
+ if not cond:
844
+ return ""
845
+ saved, tmp = block.sink, []
846
+ block.sink = tmp
847
+ try:
848
+ text = self._expr(cond, block)
849
+ finally:
850
+ block.sink = saved
851
+ block.pieces.extend(tmp)
852
+ return text
853
+
854
+ def _assoc_join(self, block: _Block, cur: Bind, name: str, kw: str, alias: str, implicit: bool = False) -> Bind:
855
+ """Join the association `name` of `cur`. Appends the JOIN text and returns the new binding."""
856
+ owner = cur.entity
857
+ if owner is None:
858
+ raise Untranslatable("join from something that is not an entity")
859
+ a = self.m.attr(owner, name)
860
+ if a is None:
861
+ raise Untranslatable("attribute not found on the entity")
862
+ sink = block.sink if implicit else block.pieces
863
+ q = alias or self._fresh(block, name)
864
+ if a.kind in ("embedded", "embedded_id"):
865
+ emb = self.m.embeddable(a.type)
866
+ if emb is None:
867
+ raise Untranslatable("embeddable class not found")
868
+ b = Bind("embed", cur.q, emb, {**a.overrides, **{k[len(name) + 1:]: v for k, v in cur.overrides.items() if k.startswith(name + ".")}})
869
+ block.env.add(alias or q, b)
870
+ return b
871
+ if a.kind == "to_one":
872
+ target = self.m.entities.get(a.type)
873
+ if target is None or target.kind != "entity":
874
+ raise Untranslatable("association target is not a mapped entity in the repository")
875
+ tpk = self._pk(target)
876
+ if len(tpk) != 1:
877
+ raise Untranslatable("join over a composite key")
878
+ table = self._table(target)
879
+ if a.mapped_by:
880
+ inv = self.m.inverse(owner, a)
881
+ if inv is None:
882
+ raise Untranslatable("mappedBy names an attribute that was not found")
883
+ opk = self._pk(owner)
884
+ on = f"{q}.{self._fk(inv[1], cur)} = {cur.q}.{opk[0]}"
885
+ else:
886
+ on = f"{q}.{tpk[0]} = {cur.q}.{self._fk(a, cur)}"
887
+ sink.append(f"{kw} {table} {q} ON {on}")
888
+ b = Bind("entity", q, target)
889
+ block.env.add(alias or q, b)
890
+ return b
891
+ if a.kind == "to_many":
892
+ target = self.m.entities.get(a.type)
893
+ if target is None or target.kind != "entity":
894
+ raise Untranslatable("association target is not a mapped entity in the repository")
895
+ opk = self._pk(owner)
896
+ if len(opk) != 1:
897
+ raise Untranslatable("join over a composite key")
898
+ table = self._table(target)
899
+ inv = self.m.inverse(owner, a) if a.mapped_by else None
900
+ if inv is not None and inv[1].kind == "to_one":
901
+ sink.append(f"{kw} {table} {q} ON {q}.{self._fk(inv[1], None)} = {cur.q}.{opk[0]}")
902
+ elif a.relation == "OneToMany" and not a.mapped_by and not a.join_table and a.join_columns:
903
+ sink.append(f"{kw} {table} {q} ON {q}.{a.join_columns[0]} = {cur.q}.{opk[0]}")
904
+ else:
905
+ jt, back, to = self.m.collection_table(owner, a)
906
+ if not (a.join_table or (inv is not None and inv[1].join_table)):
907
+ self.assumed = True
908
+ tpk = self._pk(target)
909
+ if len(tpk) != 1:
910
+ raise Untranslatable("join over a composite key")
911
+ jq = self._fresh(block, name + "_jt")
912
+ sink.append(f"{kw} {jt} {jq} ON {jq}.{back} = {cur.q}.{opk[0]}")
913
+ sink.append(f"{kw} {table} {q} ON {q}.{tpk[0]} = {jq}.{to}")
914
+ b = Bind("entity", q, target)
915
+ block.env.add(alias or q, b)
916
+ return b
917
+ if a.kind == "elements":
918
+ opk = self._pk(owner)
919
+ if len(opk) != 1:
920
+ raise Untranslatable("join over a composite key")
921
+ jt, back, value = self.m.collection_table(owner, a)
922
+ if not a.join_table:
923
+ self.assumed = True
924
+ sink.append(f"{kw} {jt} {q} ON {q}.{back} = {cur.q}.{opk[0]}")
925
+ emb = self.m.embeddable(a.type)
926
+ b = Bind("embed", q, emb) if emb is not None and emb.kind == "embeddable" else Bind("elem", q, None, value_col=value, key_col=a.key_column)
927
+ block.env.add(alias or q, b)
928
+ return b
929
+ raise Untranslatable("join over a plain column")
930
+
931
+ def _fk(self, a: Attr, cur: Bind | None) -> str:
932
+ if not a.column:
933
+ self.assumed = True
934
+ if cur is not None and a.name in cur.overrides:
935
+ return cur.overrides[a.name]
936
+ return self.m.fk(a)
937
+
938
+ # ---- paths ------------------------------------------------------------------------------------
939
+ def _step(self, block: _Block, cur: Bind, name: str, last: bool, nxt: str = "", nxt_last: bool = False):
940
+ """One component of a path. Returns a column text, a Bind to continue from, or a Coll."""
941
+ if cur.kind == "subq":
942
+ return f"{cur.q}.{name}"
943
+ if cur.kind == "elem":
944
+ raise Untranslatable("path into a collection of values")
945
+ owner = cur.entity
946
+ a = self.m.attr(owner, name) if owner is not None else None
947
+ if a is None and name == "id" and owner is not None and cur.kind == "entity":
948
+ a = self.m.pk_attr(owner) # HQL: `.id` is the identifier whatever the attribute is called
949
+ if a is None:
950
+ raise Untranslatable("attribute not found on the entity")
951
+ if a.kind in ("basic", "id"):
952
+ if not last:
953
+ raise Untranslatable("path continues past a plain column")
954
+ if name in cur.overrides:
955
+ return f"{cur.q}.{cur.overrides[name]}"
956
+ return f"{cur.q}.{self._col(a)}"
957
+ if a.kind == "formula":
958
+ raise Untranslatable("@Formula attribute")
959
+ if a.kind in ("embedded", "embedded_id"):
960
+ emb = self.m.embeddable(a.type)
961
+ if emb is None:
962
+ raise Untranslatable("embeddable class not found")
963
+ over = {**a.overrides, **{k[len(name) + 1:]: v for k, v in cur.overrides.items() if k.startswith(name + ".")}}
964
+ if last:
965
+ cols = [c for _, c in self.m.embedded_columns(a, over)]
966
+ if not cols:
967
+ raise Untranslatable("embeddable without columns")
968
+ return f"{cur.q}.{cols[0]}" if len(cols) == 1 else "(" + ", ".join(f"{cur.q}.{c}" for c in cols) + ")"
969
+ return Bind("embed", cur.q, emb, over)
970
+ if a.kind == "to_one":
971
+ target = self.m.entities.get(a.type)
972
+ if not a.mapped_by:
973
+ if last:
974
+ return f"{cur.q}.{self._fk(a, cur)}"
975
+ tid = self.m.pk_attr(target) if target is not None else None
976
+ if nxt_last and tid is not None and tid.kind == "id" and (
977
+ nxt.lower() == tid.name.lower() or (nxt == "id" and self.m.attr(target, "id") is None)):
978
+ return ("fk", f"{cur.q}.{self._fk(a, cur)}") # a.user.id is the foreign key itself
979
+ key = (cur.q, name)
980
+ b = block.implicit.get(key)
981
+ if b is None:
982
+ if block.mutating:
983
+ raise Untranslatable("path through an association in UPDATE or DELETE")
984
+ b = self._assoc_join(block, cur, name, "JOIN", "", implicit=True)
985
+ block.implicit[key] = b
986
+ self.note("a path through an association is written as an inner join")
987
+ if last:
988
+ return f"{b.q}.{self._pk(b.entity)[0]}"
989
+ return b
990
+ if a.kind in ("to_many", "elements"):
991
+ if last:
992
+ return Coll(cur, a)
993
+ raise Untranslatable("path through a collection without a join")
994
+ raise Untranslatable("attribute kind not handled")
995
+
996
+ def _path(self, block: _Block, bind: Bind, comps: list[str]):
997
+ cur = bind
998
+ i = 0
999
+ while i < len(comps):
1000
+ last = i == len(comps) - 1
1001
+ r = self._step(block, cur, comps[i], last, comps[i + 1] if not last else "", i + 1 == len(comps) - 1)
1002
+ if isinstance(r, tuple):
1003
+ return r[1]
1004
+ if isinstance(r, Bind):
1005
+ cur = r
1006
+ i += 1
1007
+ continue
1008
+ return r
1009
+ return cur
1010
+
1011
+ def _entity_columns(self, b: Bind, top: bool) -> str:
1012
+ if b.kind == "elem":
1013
+ return f"{b.q}.{b.value_col}"
1014
+ if b.kind == "subq":
1015
+ return f"{b.q}.*"
1016
+ e = b.entity
1017
+ if b.kind == "entity" and (not top or self.no_expand):
1018
+ pk = self._pk(e) # an entity in a subquery or an INSERT ... SELECT stands for its key
1019
+ return ", ".join(f"{b.q}.{c}" for c in pk)
1020
+ if b.kind == "embed":
1021
+ cols = [b.overrides.get(a.name) or self._col(a) for a in self.m.attrs(e).values() if a.kind in ("basic", "id")]
1022
+ else:
1023
+ cols = self.m.columns(e)
1024
+ if any(not a.explicit for a in self.m.attrs(e).values() if a.kind in ("basic", "id", "to_one") and not a.mapped_by):
1025
+ self.assumed = True
1026
+ if top:
1027
+ self.selected.append(e)
1028
+ if not cols:
1029
+ raise Untranslatable("entity without mapped columns")
1030
+ return ", ".join(f"{b.q}.{c}" for c in cols)
1031
+
1032
+ def _select_list(self, toks: list[Tok], block: _Block, top: bool) -> str:
1033
+ out = []
1034
+ lead = ""
1035
+ if toks and toks[0].up in ("DISTINCT", "ALL"):
1036
+ lead = toks[0].up + " "
1037
+ toks = toks[1:]
1038
+ for item in _split(toks, ","):
1039
+ if not item:
1040
+ continue
1041
+ core = item
1042
+ if len(core) == 1 and core[0].kind == "grp" and len(core[0].items) == 1 and core[0].items[0].kind == "id":
1043
+ core = core[0].items
1044
+ if len(core) >= 2 and core[0].up == "OBJECT" and core[1].kind == "grp":
1045
+ core = core[1].items
1046
+ if core and core[0].up == "NEW" and len(core) >= 3 and core[2].kind == "grp":
1047
+ out.append(self._select_list(core[2].items, block, top))
1048
+ continue
1049
+ alias_only = len(core) == 1 or (len(core) == 3 and core[1].up == "AS") or (len(core) == 2 and core[1].kind == "id")
1050
+ if alias_only and core[0].kind == "id" and "." not in core[0].text:
1051
+ b = block.env.get(core[0].text)
1052
+ if b is not None:
1053
+ out.append(self._entity_columns(b, top))
1054
+ continue
1055
+ if alias_only and top and not self.no_expand and core[0].kind == "id" and "." in core[0].text:
1056
+ # a path that ends in an association selects the associated entity
1057
+ comps = core[0].text.split(".")
1058
+ b = block.env.get(comps[0])
1059
+ if b is not None and b.kind in ("entity", "embed"):
1060
+ r = self._bind_of_path(block, b, comps[1:])
1061
+ if r is not None:
1062
+ out.append(self._entity_columns(r, top))
1063
+ continue
1064
+ out.append(self._expr(item, block))
1065
+ if not out:
1066
+ raise Untranslatable("empty select list")
1067
+ return lead + ", ".join(out)
1068
+
1069
+ def _bind_of_path(self, block: _Block, b: Bind, comps: list[str]) -> Bind | None:
1070
+ cur = b
1071
+ for k, comp in enumerate(comps):
1072
+ a = self.m.attr(cur.entity, comp) if cur.entity is not None else None
1073
+ if a is None:
1074
+ return None
1075
+ last = k == len(comps) - 1
1076
+ if a.kind == "to_one" and last:
1077
+ key = (cur.q, comp)
1078
+ nb = block.implicit.get(key)
1079
+ if nb is None:
1080
+ nb = self._assoc_join(block, cur, comp, "JOIN", "", implicit=True)
1081
+ block.implicit[key] = nb
1082
+ return nb
1083
+ if a.kind in ("to_one", "embedded", "embedded_id") and not last:
1084
+ r = self._step(block, cur, comp, False)
1085
+ if not isinstance(r, Bind):
1086
+ return None
1087
+ cur = r
1088
+ continue
1089
+ return None
1090
+ return None
1091
+
1092
+ # ---- expressions ------------------------------------------------------------------------------
1093
+ def _is_query(self, items: list[Tok]) -> bool:
1094
+ while len(items) == 1 and items[0].kind == "grp":
1095
+ items = items[0].items
1096
+ return bool(items) and items[0].up in ("SELECT", "FROM") and any(t.up == "FROM" for t in items)
1097
+
1098
+ def _coll_subquery(self, block: _Block, c: Coll, select: str, extra: str = "") -> str:
1099
+ owner, a = c.bind.entity, c.attr
1100
+ opk = self._pk(owner)
1101
+ if len(opk) != 1:
1102
+ raise Untranslatable("collection of an entity with a composite key")
1103
+ inv = self.m.inverse(owner, a) if a.mapped_by else None
1104
+ target = self.m.entities.get(a.type)
1105
+ if a.kind == "to_many" and inv is not None and inv[1].kind == "to_one" and target is not None:
1106
+ t = self._table(target)
1107
+ sel = f"{t}.{self._pk(target)[0]}" if select == "id" else select
1108
+ return f"(SELECT {sel} FROM {t} WHERE {t}.{self._fk(inv[1], None)} = {c.bind.q}.{opk[0]}{extra})"
1109
+ if a.kind == "to_many" and a.relation == "OneToMany" and not a.mapped_by and not a.join_table and a.join_columns and target is not None:
1110
+ t = self._table(target)
1111
+ sel = f"{t}.{self._pk(target)[0]}" if select == "id" else select
1112
+ return f"(SELECT {sel} FROM {t} WHERE {t}.{a.join_columns[0]} = {c.bind.q}.{opk[0]}{extra})"
1113
+ jt, back, to = self.m.collection_table(owner, a)
1114
+ sel = f"{jt}.{to}" if select == "id" else select
1115
+ return f"(SELECT {sel} FROM {jt} WHERE {jt}.{back} = {c.bind.q}.{opk[0]}{extra})"
1116
+
1117
+ def _resolve_id(self, block: _Block, text: str):
1118
+ """A dotted name: a column, a Coll, or None when it is not a path of this query."""
1119
+ comps = text.split(".")
1120
+ if comps[-1] == "*":
1121
+ b = block.env.get(comps[0])
1122
+ if b is not None and len(comps) == 2:
1123
+ return self._entity_columns(b, False)
1124
+ return None
1125
+ b = block.env.get(comps[0])
1126
+ if b is not None:
1127
+ if len(comps) == 1:
1128
+ if b.kind == "entity":
1129
+ pk = self._pk(b.entity)
1130
+ return f"{b.q}.{pk[0]}" if len(pk) == 1 else "(" + ", ".join(f"{b.q}.{c}" for c in pk) + ")"
1131
+ if b.kind == "elem":
1132
+ return f"{b.q}.{b.value_col}"
1133
+ if b.kind == "subq":
1134
+ return b.q
1135
+ raise Untranslatable("embeddable used as a value")
1136
+ r = self._path(block, b, comps[1:])
1137
+ if isinstance(r, Bind):
1138
+ raise Untranslatable("embeddable used as a value")
1139
+ return r
1140
+ root = block.env.default()
1141
+ env = block.env
1142
+ while root is None and env.parent is not None:
1143
+ env = env.parent
1144
+ root = env.default()
1145
+ if root is not None and root.entity is not None and self.m.attr(root.entity, comps[0]) is not None:
1146
+ r = self._path(block, root, comps)
1147
+ if isinstance(r, Bind):
1148
+ raise Untranslatable("embeddable used as a value")
1149
+ return r
1150
+ return None
1151
+
1152
+ def _expr(self, toks: list[Tok], block: _Block) -> str:
1153
+ out: list[str] = []
1154
+ i, n = 0, len(toks)
1155
+ while i < n:
1156
+ t = toks[i]
1157
+ nxt = toks[i + 1] if i + 1 < n else None
1158
+ if t.kind == "grp":
1159
+ if self._is_query(t.items):
1160
+ out.append("(" + self.statement(t.items, block.env) + ")")
1161
+ else:
1162
+ out.append("(" + self._expr(t.items, block) + ")")
1163
+ elif t.kind == "id":
1164
+ up = t.up
1165
+ plain = "." not in t.text
1166
+ if plain and up == "NEW" and nxt is not None and nxt.kind == "id" and i + 2 < n and toks[i + 2].kind == "grp":
1167
+ out.append(self._select_list(toks[i + 2].items, block, False))
1168
+ i += 3
1169
+ continue
1170
+ if plain and up == "ILIKE" and nxt is not None and nxt.kind == "grp" and len(_split(nxt.items, ",")) > 1:
1171
+ out.append(self._call(t, nxt, block)) # Hibernate's ilike(a, b) function
1172
+ i += 2
1173
+ continue
1174
+ if nxt is not None and nxt.kind == "grp" and not (plain and up in KEYWORDS and up not in (
1175
+ "LEFT", "RIGHT", "DATE", "TIME", "YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND", "WEEK", "QUARTER",
1176
+ "FIRST", "LAST", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "LOCAL", "DATETIME", "OBJECT")):
1177
+ out.append(self._call(t, nxt, block))
1178
+ i += 2
1179
+ continue
1180
+ if plain and up == "MEMBER":
1181
+ k = i + 1
1182
+ if k < n and toks[k].up == "OF":
1183
+ k += 1
1184
+ if k < n and toks[k].kind == "id":
1185
+ c = self._resolve_id(block, toks[k].text)
1186
+ if isinstance(c, Coll):
1187
+ out.append("IN " + self._coll_subquery(block, c, "id"))
1188
+ i = k + 1
1189
+ continue
1190
+ raise Untranslatable("MEMBER OF with something other than a collection path")
1191
+ if plain and up in KEYWORDS:
1192
+ out.append(CAST_TYPES.get(up, t.text) if out and out[-1].upper() == "AS" and up in CAST_TYPES else t.text)
1193
+ elif plain and out and out[-1].upper() == "AS":
1194
+ out.append(CAST_TYPES.get(up, t.text)) # CAST(x AS String), or a select alias
1195
+ else:
1196
+ r = self._resolve_id(block, t.text)
1197
+ if isinstance(r, Coll):
1198
+ k = i + 1
1199
+ neg = False
1200
+ if k < n and toks[k].up == "IS":
1201
+ k += 1
1202
+ if k < n and toks[k].up == "NOT":
1203
+ neg, k = True, k + 1
1204
+ if k < n and toks[k].up == "EMPTY":
1205
+ out.append(("" if neg else "NOT ") + "EXISTS " + self._coll_subquery(block, r, "1"))
1206
+ i = k + 1
1207
+ continue
1208
+ raise Untranslatable("collection path used as a value")
1209
+ if r is not None:
1210
+ out.append(r)
1211
+ elif not plain and ENUM_PATH.match(t.text):
1212
+ known = self.m.constant(t.text)
1213
+ if isinstance(known, tuple):
1214
+ out.append("'" + known[1].replace("'", "''") + "'")
1215
+ elif known == "enum":
1216
+ out.append("'" + t.text.rsplit(".", 1)[-1] + "'")
1217
+ self.note("an enum constant is written as its name (assumes it is stored as a string)")
1218
+ else:
1219
+ out.append("?")
1220
+ self.note(f"the Java constant {t.text.rsplit('.', 2)[-2]}.{t.text.rsplit('.', 1)[-1]} is written as a bound value")
1221
+ elif plain:
1222
+ out.append(t.text)
1223
+ else:
1224
+ raise Untranslatable("path starts at an unknown alias")
1225
+ elif t.kind == "param":
1226
+ out.append(t.text if t.text.startswith(":") else "?")
1227
+ elif t.kind == "spel":
1228
+ inner = re.sub(r"\W+", "_", t.text).strip("_")
1229
+ out.append(":" + (inner or "spel"))
1230
+ elif t.kind == "op":
1231
+ out.append("<>" if t.text in ("!=", "^=") else t.text)
1232
+ elif t.kind == "num":
1233
+ out.append(re.sub(r"[LlDdFf]$", "", t.text))
1234
+ else:
1235
+ out.append(t.text)
1236
+ i += 1
1237
+ text = " ".join(out)
1238
+ text = re.sub(r"\s+,", ",", text)
1239
+ text = re.sub(r"\(\s+", "(", text)
1240
+ text = re.sub(r"\s+\)", ")", text)
1241
+ text = re.sub(r"\s+\.\s+", ".", text)
1242
+ return text
1243
+
1244
+ def _call(self, name: Tok, args: Tok, block: _Block) -> str:
1245
+ up = name.up
1246
+ if up == "FUNCTION" or up == "FUNC":
1247
+ parts = _split(args.items, ",")
1248
+ if not parts or len(parts[0]) != 1 or parts[0][0].kind != "str":
1249
+ raise Untranslatable("FUNCTION() without a literal name")
1250
+ fname = parts[0][0].text.strip("'")
1251
+ return fname + "(" + ", ".join(self._expr(p, block) for p in parts[1:]) + ")"
1252
+ if up == "SIZE" and len(args.items) == 1 and args.items[0].kind == "id":
1253
+ c = self._resolve_id(block, args.items[0].text)
1254
+ if isinstance(c, Coll):
1255
+ return self._coll_subquery(block, c, "COUNT(*)")
1256
+ if up in ("KEY", "VALUE") and len(args.items) == 1 and args.items[0].kind == "id":
1257
+ b = block.env.get(args.items[0].text)
1258
+ if b is not None and b.kind == "elem" and (up == "VALUE" or b.key_col):
1259
+ return f"{b.q}.{b.value_col if up == 'VALUE' else b.key_col}"
1260
+ if up in UNSUPPORTED_FUNCS and "." not in name.text:
1261
+ raise Untranslatable(f"{up}() is not translated")
1262
+ if up in ("EXISTS", "IN", "ANY", "ALL", "SOME", "NOT", "AND", "OR", "ON", "WHEN", "THEN", "ELSE", "LIKE", "AS", "OVER",
1263
+ "VALUES", "FILTER", "BY", "BETWEEN", "WHERE", "HAVING", "SELECT", "DISTINCT", "UNION", "FROM", "JOIN", "OF", "IS"):
1264
+ inner = "(" + self.statement(args.items, block.env) + ")" if self._is_query(args.items) else "(" + self._expr(args.items, block) + ")"
1265
+ return name.text + " " + inner
1266
+ if self._is_query(args.items):
1267
+ return name.text + "(" + self.statement(args.items, block.env) + ")"
1268
+ if up == "COUNT" and len(args.items) >= 1:
1269
+ core = [t for t in args.items if t.up != "DISTINCT"]
1270
+ if len(core) == 1 and core[0].kind == "id" and "." not in core[0].text:
1271
+ b = block.env.get(core[0].text)
1272
+ if b is not None and b.kind == "entity":
1273
+ pk = self._pk(b.entity)
1274
+ if len(pk) != 1:
1275
+ return "COUNT(*)"
1276
+ return name.text + "(" + self._expr(args.items, block) + ")"
1277
+
1278
+
1279
+ def _split(toks: list[Tok], sep: str) -> list[list[Tok]]:
1280
+ out, cur = [], []
1281
+ for t in toks:
1282
+ if t.kind == "op" and t.text == sep:
1283
+ out.append(cur)
1284
+ cur = []
1285
+ else:
1286
+ cur.append(t)
1287
+ out.append(cur)
1288
+ return out
1289
+
1290
+
1291
+ _ENTITY_NAME_SPEL = re.compile(r"#\{\s*#entityName\s*\}")
1292
+
1293
+
1294
+ def translate(jpql: str, model: Model, entity_name: str = "") -> Result:
1295
+ """JPQL or HQL as SQL over the mapped tables. Raises Untranslatable with the reason."""
1296
+ if entity_name:
1297
+ jpql = _ENTITY_NAME_SPEL.sub(entity_name, jpql)
1298
+ toks = tokenize(jpql)
1299
+ if not toks:
1300
+ raise Untranslatable("empty statement")
1301
+ tr = Translator(model)
1302
+ tr.root_entity = None
1303
+ sql = tr.statement(toks)
1304
+ head = sql.split(None, 1)[0].upper() if sql else ""
1305
+ kind = {"SELECT": "select", "UPDATE": "update", "DELETE": "delete", "INSERT": "insert"}.get(head, "other")
1306
+ return Result(sql=sql, notes=tr.notes, selected=tr.selected, fetched=tr.fetched, kind=kind,
1307
+ root=tr.root_entity or (tr.selected[0] if tr.selected else None), assumed=tr.assumed)