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,602 @@
1
+ """bun (github.com/uptrace/bun, and packages of a repository shaped like it, such as uptrace's ClickHouse `ch`):
2
+ the SQL a query-builder chain stands for.
3
+
4
+ `db.NewSelect().Model(&users).Where("org_id = ?", id).Order("created_at DESC").Limit(10).Scan(ctx)` is
5
+ written as the statement bun sends: `SELECT "user"."id", ... FROM users AS "user" WHERE org_id = ? ORDER BY
6
+ created_at DESC LIMIT 10`. The evaluation of chains, variables and conditional `q = q.Where(...)` is shared with
7
+ the other Go builders (orm_go.Ev); this module holds bun's operations and the final statement per terminal.
8
+
9
+ The model struct gives the table and columns (orm_go_types.Types._bun_model: `bun:"table:x,alias:y"` on the
10
+ embedded bun.BaseModel, else the underscored plural of the struct name). bun's own placeholders are filled in:
11
+ `?TableAlias`, `?TableName`, `?TableColumns`, `?PKs`; `bun.Ident(x)` passed for a `?` is the identifier it names,
12
+ `bun.Safe(s)` the text, a sub-query its SELECT. Anything else decided at run time is a «run-time part»; when no
13
+ table can be named the call is counted with the reason, never written.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+
20
+ from tree_sitter import Node
21
+
22
+ from .base import trim
23
+ from .go import STRING_TYPES, GoFile, _strip_parens, _txt, call_args, callee_name
24
+ from . import orm_go_types as T
25
+
26
+ NOOP = {"Context", "Conn", "DB", "Err", "Bulk", "OmitZero", "Comment", "Returning_", "Dialect", "Operation", "Query",
27
+ "QueryBuilder", "Apply_", "Model_", "WhereDeleted_", "Clone", "String", "AppendQuery", "NewSelect_"}
28
+ STARTS = {"NewSelect": "select", "NewInsert": "insert", "NewUpdate": "update", "NewDelete": "delete",
29
+ "NewCreateTable": "create_table", "NewDropTable": "drop_table", "NewCreateIndex": "create_index",
30
+ "NewDropIndex": "drop_index", "NewTruncateTable": "truncate", "NewAddColumn": "add_column",
31
+ "NewDropColumn": "drop_column", "NewRaw": "raw", "NewMerge": "merge", "NewValues": "values"}
32
+ WHERE_OPS = {"Where", "WhereOr", "WhereGroup", "WherePK", "WhereDeleted", "WhereAllWithDeleted", "Having"}
33
+
34
+
35
+ def O():
36
+ from . import orm_go
37
+ return orm_go
38
+
39
+
40
+ # ---- arguments ------------------------------------------------------------------------------------------------
41
+
42
+ def _bun_package(ev, gf: GoFile, alias: str) -> bool:
43
+ """`bun.` or a repository's own bun-shaped package (`ch.Name(...)`)."""
44
+ path = gf.imports.get(alias, "")
45
+ if not path:
46
+ return False
47
+ if T.import_lib(path) == "bun":
48
+ return True
49
+ target = ev.ctx.import_dir(gf.dir, path)
50
+ return target is not None and ev.types.bun_shaped(target)
51
+
52
+
53
+ def _bun_value(ev, gf: GoFile, node: Node, at: Node, env, depth: int) -> str | None:
54
+ """What `?` stands for when this argument fills it: an identifier (bun.Ident), text (bun.Safe), a sub-query,
55
+ or None for a bound value."""
56
+ n = _strip_parens(node)
57
+ if n is None or n.type != "call_expression":
58
+ return None
59
+ name, recv, _d = callee_name(n.child_by_field_name("function"))
60
+ args = call_args(n)
61
+ if recv is not None and recv.type == "identifier" and _bun_package(ev, gf, _txt(recv)):
62
+ if name in ("Ident", "Name") and args:
63
+ return ", ".join(ev.texts(gf, args, at, env, depth))
64
+ if name == "Safe" and args:
65
+ return ev.text(gf, args[0], at, env, depth)
66
+ if name in ("In", "List", "Tuple"):
67
+ return None
68
+ return None
69
+ v = ev.eval(gf, n, at, env, depth + 1)
70
+ if isinstance(v, O().Q) and v.lib == "bun":
71
+ sub = select_text(v)
72
+ return f"({sub})" if sub else None
73
+ return None
74
+
75
+
76
+ def expr(ev, gf: GoFile, args: list[Node], at: Node, env, depth: int) -> str:
77
+ """bun's query text with its arguments: `"? = ?", bun.Ident("x"), v` -> `x = ?`."""
78
+ if not args:
79
+ return ""
80
+ a0 = _strip_parens(args[0])
81
+ if a0 is not None and a0.type not in STRING_TYPES:
82
+ v = ev.eval(gf, a0, at, env, depth + 1)
83
+ if isinstance(v, O().Q) and v.lib == "bun":
84
+ sub = select_text(v)
85
+ return f"({sub})" if sub else O().marker(_txt(a0))
86
+ s = ev.text(gf, args[0], at, env, depth)
87
+ rest = args[1:]
88
+ if not rest or "?" not in s:
89
+ return s
90
+ if len(rest) == 1 and rest[0].type == "variadic_argument":
91
+ return s
92
+ out, i = [], 0
93
+ for piece in re.split(r"(\?(?![A-Za-z_\d]))", s):
94
+ if piece == "?":
95
+ got = _bun_value(ev, gf, rest[i], at, env, depth) if i < len(rest) else None
96
+ out.append(got if got is not None else "?")
97
+ i += 1
98
+ else:
99
+ out.append(piece)
100
+ return "".join(out)
101
+
102
+
103
+ def model_of(ev, gf: GoFile, arg: Node, at: Node):
104
+ """The model a `Model(...)` argument names: `&users`, `user`, `(*User)(nil)`, `new(User)`."""
105
+ a = _strip_parens(arg)
106
+ if a is not None and a.type == "call_expression":
107
+ fn = _strip_parens(a.child_by_field_name("function"))
108
+ if fn is not None and fn.type in ("pointer_type", "unary_expression", "parenthesized_type") or (
109
+ a.child_by_field_name("function") is not None and a.child_by_field_name("function").type == "parenthesized_expression"):
110
+ inner = _txt(a.child_by_field_name("function")).strip("()").strip()
111
+ return ev.types.model(T.TypeRef(inner, gf), "bun")
112
+ return ev.types.model(ev.types.type_of(gf, arg, at), "bun")
113
+
114
+
115
+ # ---- operations -----------------------------------------------------------------------------------------------
116
+
117
+ def apply(ev, q, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env, depth: int): # noqa: C901
118
+ Om = O()
119
+ tx = lambda n: ev.text(gf, n, at, env, depth) # noqa: E731
120
+ ex = lambda a: expr(ev, gf, a, at, env, depth) # noqa: E731
121
+ if name in STARTS:
122
+ q.kind = STARTS[name]
123
+ if name == "NewRaw":
124
+ q.flags.add("raw")
125
+ elif name in ("NewMerge", "NewValues"):
126
+ q.notes.append(f"{name}() is not translated")
127
+ q.flags.add("unsupported")
128
+ return q
129
+ if not q.kind:
130
+ return q # a method of the DB or Tx itself (BeginTx, RunInTx, WithNamedArg): no query yet
131
+ if name == "Model" and args:
132
+ a0 = _strip_parens(args[0])
133
+ if a0 is not None and a0.type == "identifier" and _txt(a0) == "nil":
134
+ return q
135
+ m = model_of(ev, gf, args[0], at)
136
+ if m is not None:
137
+ q.model = m
138
+ if not Om._empty_value(gf, args[0], at):
139
+ q.flags.add("model_instance")
140
+ else:
141
+ q.flags.add("model_unknown")
142
+ q.notes.append(f"Model({trim(_txt(args[0]), 40)}) is not a struct this scan can read")
143
+ elif name in ("Table", "TableExpr", "ModelTableExpr") and args:
144
+ text = ex(args) if name != "Table" else ", ".join(ev.texts(gf, args, at, env, depth))
145
+ if name == "ModelTableExpr":
146
+ q.table = text
147
+ q.flags.add("model_table_expr")
148
+ else:
149
+ # bun lists Table()/TableExpr() after the model's own table; with no model the first one is the table
150
+ q.from_extra = getattr(q, "from_extra", []) + [text]
151
+ elif name == "Column" and args:
152
+ cols = ev.texts(gf, args, at, env, depth)
153
+ q.cols.extend(cols)
154
+ q.flags.add("columns")
155
+ elif name == "ColumnExpr" and args:
156
+ q.cols.append(ex(args))
157
+ q.flags.add("columns")
158
+ elif name == "ExcludeColumn":
159
+ q.omit.extend(ev.texts(gf, args, at, env, depth))
160
+ elif name == "Where" and args:
161
+ q.and_(ex(args))
162
+ elif name == "WhereOr" and args:
163
+ q.or_(ex(args))
164
+ elif name == "WhereGroup" and len(args) >= 2:
165
+ sep = tx(args[0]).strip().upper()
166
+ inner = group(ev, gf, args[1], at, env, depth, q)
167
+ if inner is None:
168
+ inner = Om.marker(_txt(args[1]))
169
+ (q.or_ if sep == "OR" else q.and_)(f"({inner})" if not Om._is_marker(inner) else inner)
170
+ elif name == "WherePK":
171
+ q.flags.add("where_pk")
172
+ q.and_("\x06PK\x06")
173
+ elif name == "WhereDeleted":
174
+ q.flags.add("deleted_only")
175
+ elif name == "WhereAllWithDeleted":
176
+ q.flags.add("unscoped")
177
+ elif name in ("Join",) and args:
178
+ q.joins.append(ex(args))
179
+ elif name in ("JoinOn", "JoinOnOr") and args and q.joins:
180
+ cond = ex(args)
181
+ last = q.joins[-1]
182
+ kw = "OR" if name == "JoinOnOr" else "AND"
183
+ q.joins[-1] = f"{last} {kw} {cond}" if re.search(r"\bON\b", last, re.I) else f"{last} ON {cond}"
184
+ elif name == "Relation" and args:
185
+ rel = tx(args[0])
186
+ q.preloads.append(rel)
187
+ if len(args) > 1:
188
+ q.notes.append(f"Relation({rel}, …): the relation's own query is changed by a function")
189
+ elif name in ("Order", "OrderExpr") and args:
190
+ q.order.append(ex(args) if name == "OrderExpr" else ", ".join(ev.texts(gf, args, at, env, depth)))
191
+ elif name in ("Group", "GroupExpr") and args:
192
+ q.group.append(ex(args) if name == "GroupExpr" else ", ".join(ev.texts(gf, args, at, env, depth)))
193
+ elif name == "Having" and args:
194
+ q.having.append(ex(args))
195
+ elif name == "Limit" and args:
196
+ q.limit = ev.num(args[0])
197
+ elif name == "Offset" and args:
198
+ q.offset = ev.num(args[0])
199
+ elif name == "Distinct":
200
+ q.distinct = True
201
+ elif name == "DistinctOn" and args:
202
+ q.options.append(f"DISTINCT ON ({ex(args)})")
203
+ elif name == "For" and args:
204
+ q.suffix.append("FOR " + ex(args))
205
+ elif name in ("With", "WithRecursive") and len(args) >= 2:
206
+ sub = ev.eval(gf, args[1], at, env, depth + 1)
207
+ body = select_text(sub) if isinstance(sub, Om.Q) and sub.lib == "bun" else ""
208
+ q.prefix.append(f"WITH {'RECURSIVE ' if name == 'WithRecursive' else ''}{tx(args[0])} AS ({body or Om.marker(_txt(args[1]))})")
209
+ elif name in ("Set", "SetColumn") and args:
210
+ if name == "SetColumn" and len(args) >= 2:
211
+ q.sets.append(f"{tx(args[0])} = {expr(ev, gf, args[1:], at, env, depth)}")
212
+ else:
213
+ q.sets.append(ex(args))
214
+ elif name == "Value" and len(args) >= 2:
215
+ q.flags.add("values")
216
+ q.sets.append(f"{tx(args[0])} = {expr(ev, gf, args[1:], at, env, depth)}")
217
+ elif name == "On" and args:
218
+ q.suffix.append("ON " + ex(args))
219
+ q.flags.add("on_conflict")
220
+ elif name == "Ignore":
221
+ q.flags.add("ignore")
222
+ elif name == "Returning" and args:
223
+ r = ex(args)
224
+ if r.upper() != "NULL":
225
+ q.flags.add("returning")
226
+ q.suffix.append("RETURNING " + r)
227
+ elif name in ("IfNotExists", "IfExists"):
228
+ q.flags.add(name)
229
+ elif name == "Cascade":
230
+ q.flags.add("cascade")
231
+ elif name == "Unique":
232
+ q.flags.add("unique")
233
+ elif name in ("Index",) and args:
234
+ q.alias = tx(args[0])
235
+ elif name == "ForceDelete":
236
+ q.flags.add("force_delete")
237
+ elif name in ("Union", "UnionAll", "Intersect", "Except") and args:
238
+ sub = ev.eval(gf, args[0], at, env, depth + 1)
239
+ body = select_text(sub) if isinstance(sub, Om.Q) and sub.lib == "bun" else ""
240
+ q.suffix.append(f"{name.replace('All', ' ALL').upper()} ({body or Om.marker(_txt(args[0]))})")
241
+ elif name == "Apply":
242
+ if not (args and _txt(args[0]) == "nil"):
243
+ q.tail.append(Om.marker("." + name + _txt(call.child_by_field_name("arguments"))))
244
+ q.dynamic = True
245
+ elif name in ("ForeignKey", "PartitionBy", "TableSpace", "WithForeignKeys", "ColumnExprs", "Temp", "Varchar"):
246
+ q.flags.add("ddl_" + name)
247
+ if name == "ForeignKey" and args:
248
+ q.suffix.append(ex(args))
249
+ elif name not in NOOP:
250
+ q.notes.append(f".{name}() is not shown")
251
+ return q
252
+
253
+
254
+ def group(ev, gf: GoFile, fn: Node, at: Node, env, depth: int, outer) -> str | None:
255
+ """`WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery { return q.Where(...).WhereOr(...) })`: the
256
+ predicate the function adds, when its body is one return of a chain on its parameter."""
257
+ Om = O()
258
+ fn = _strip_parens(fn)
259
+ if fn is None or fn.type != "func_literal":
260
+ return None
261
+ params = fn.child_by_field_name("parameters")
262
+ pname = ""
263
+ for p in params.named_children if params is not None else []:
264
+ names = p.children_by_field_name("name")
265
+ if names:
266
+ pname = _txt(names[0])
267
+ body = fn.child_by_field_name("body")
268
+ stmts = [c for c in body.named_children if c.type != "comment"] if body is not None else []
269
+ if not pname or len(stmts) != 1 or stmts[0].type != "return_statement" or not stmts[0].named_children:
270
+ return None
271
+ ret = stmts[0].named_children[0]
272
+ if ret.type == "expression_list":
273
+ ret = ret.named_children[0] if ret.named_children else None
274
+ root, ops = Om.chain_of(ret) if ret is not None else (None, [])
275
+ if root is None or root.type != "identifier" or _txt(root) != pname or not ops:
276
+ return None
277
+ probe = Om.Q("bun", outer.kind)
278
+ probe.model = outer.model
279
+ for name, args, call in ops:
280
+ if name not in WHERE_OPS:
281
+ return None
282
+ apply(ev, probe, name, args, call, gf, call, env, depth + 1)
283
+ return probe.where or None
284
+
285
+
286
+ # ---- the statement ----------------------------------------------------------------------------------------------
287
+
288
+ def _settle(q) -> None:
289
+ """With no model and no ModelTableExpr, the first Table()/TableExpr() is the statement's table."""
290
+ extra = getattr(q, "from_extra", [])
291
+ if not q.table and q.model is None and extra:
292
+ q.table, q.from_extra = extra[0], extra[1:]
293
+
294
+
295
+ def _from(q, with_extra: bool = True) -> str:
296
+ _settle(q)
297
+ extra = getattr(q, "from_extra", []) if with_extra else []
298
+ if q.table:
299
+ main = q.table
300
+ elif q.model is not None:
301
+ main = f"{T.ident(q.model.table)} AS {T.ident(q.model.alias)}"
302
+ else:
303
+ return ""
304
+ return ", ".join([main] + extra)
305
+
306
+
307
+ def _alias(q) -> str:
308
+ if q.model is not None and not q.table:
309
+ return T.ident(q.model.alias)
310
+ if q.model is not None and "model_table_expr" in q.flags:
311
+ m = re.search(r"\bAS\s+([\w\"]+)\s*$", q.table, re.I)
312
+ return m.group(1) if m else T.ident(q.model.alias)
313
+ return ""
314
+
315
+
316
+ def _fill(q, text: str) -> str:
317
+ """bun's own placeholders in a query text."""
318
+ m = q.model
319
+ if "?" not in text and "\x06" not in text:
320
+ return text
321
+ alias = _alias(q) or (T.ident(m.alias) if m is not None else "")
322
+ if m is not None:
323
+ text = text.replace("?TableAlias", alias).replace("?TableName", T.ident(m.table))
324
+ text = text.replace("?TableColumns", ", ".join(f"{alias}.{T.ident(c.name)}" for c in m.cols))
325
+ text = text.replace("?Columns", ", ".join(T.ident(c.name) for c in m.cols))
326
+ pks = m.pk or ["id"]
327
+ text = text.replace("?PKs", ", ".join(f"{alias}.{T.ident(p)}" for p in pks))
328
+ pk_pred = " AND ".join(f"{alias + '.' if alias and q.kind == 'select' else ''}{T.ident(p)} = ?" for p in pks)
329
+ if "model_instance" in q.flags or q.kind == "select":
330
+ text = text.replace("\x06PK\x06", pk_pred)
331
+ else:
332
+ text = text.replace("\x06PK\x06", pk_pred)
333
+ return text.replace("\x06PK\x06", "id = ?")
334
+
335
+
336
+ def _soft(q) -> str:
337
+ m = q.model
338
+ if m is None or q.table and "model_table_expr" not in q.flags:
339
+ return ""
340
+ col = m.role("deleted")
341
+ if not col or "unscoped" in q.flags:
342
+ return ""
343
+ alias = _alias(q)
344
+ ref = f"{alias}.{T.ident(col)}" if alias and q.kind == "select" else T.ident(col)
345
+ return f"{ref} IS NOT NULL" if "deleted_only" in q.flags else f"{ref} IS NULL"
346
+
347
+
348
+ def _select_q(q):
349
+ """A clone ready for render(): FROM with the alias, the model's columns, soft-delete filter, placeholders."""
350
+ s = q.clone()
351
+ s.kind = "select"
352
+ s.table = _from(q)
353
+ if not s.table:
354
+ return None
355
+ s.model = None
356
+ alias = _alias(q)
357
+ if not s.cols and q.model is not None:
358
+ s.cols = [f"{alias}.{T.ident(c.name)}" if alias else T.ident(c.name) for c in q.model.cols
359
+ if c.name not in q.omit]
360
+ s.and_(_soft(q))
361
+ s.map_text(lambda t: _fill(q, t))
362
+ return s
363
+
364
+
365
+ def select_text(q) -> str:
366
+ """A bun SELECT builder as text (a sub-query, a WITH part), or ""."""
367
+ from .orm_go import render
368
+ if q.opaque or q.kind not in ("", "select"):
369
+ return ""
370
+ s = _select_q(q)
371
+ return render(s) if s is not None else ""
372
+
373
+
374
+ def _relation_stmts(ev, q, notes_out: list[str]) -> list[tuple[str, str]]:
375
+ """Relation("X"): a JOIN for has-one / belongs-to (added to the main statement), a second SELECT for
376
+ has-many / m2m. Returns the extra statements as (sql, target name)."""
377
+ from .orm_go import marker, render, Q
378
+ out: list[tuple[str, str]] = []
379
+ m = q.model
380
+ for rel_name in q.preloads:
381
+ first = rel_name.split(".")[0]
382
+ if m is None or first not in m.relations:
383
+ q.tail.append(marker(f"Relation({rel_name})"))
384
+ q.dynamic = True
385
+ continue
386
+ rel = m.relations[first]
387
+ target = ev.types.model(rel.target, "bun")
388
+ if target is None:
389
+ q.tail.append(marker(f"Relation({rel_name})"))
390
+ q.dynamic = True
391
+ continue
392
+ target.used = True
393
+ pairs = []
394
+ for part in (rel.foreign_key or "").split(","):
395
+ if "=" in part:
396
+ a, _, b = part.partition("=")
397
+ pairs.append((a.strip(), b.strip()))
398
+ owner_alias = _alias(q) or T.ident(m.alias)
399
+ ralias = T.ident(T.gonic_name(first))
400
+ if rel.kind in ("has_one", "belongs_to"):
401
+ if not pairs:
402
+ if rel.kind == "belongs_to":
403
+ pairs = [(T.gonic_name(first) + "_id", (target.pk or ["id"])[0])]
404
+ else:
405
+ pairs = [((m.pk or ["id"])[0], T.gonic_name(m.name) + "_id")]
406
+ on = " AND ".join(f"{ralias}.{T.ident(b)} = {owner_alias}.{T.ident(a)}" for a, b in pairs)
407
+ q.joins.append(f"LEFT JOIN {T.ident(target.table)} AS {ralias} ON {on}")
408
+ if "columns" not in q.flags:
409
+ q.flags.add("rel_cols")
410
+ q.cols_rel = getattr(q, "cols_rel", []) + [f'{ralias}.{T.ident(c.name)} AS "{T.gonic_name(first)}__{c.name}"'
411
+ for c in target.cols]
412
+ elif rel.kind == "has_many":
413
+ if not pairs:
414
+ pairs = [((m.pk or ["id"])[0], T.gonic_name(m.name) + "_id")]
415
+ tq = Q("bun", "select")
416
+ tq.model = target
417
+ cond = " AND ".join(f"{T.ident(target.alias)}.{T.ident(b)} IN (?)" for _a, b in pairs)
418
+ tq.and_(cond)
419
+ s = _select_q(tq)
420
+ if s is not None:
421
+ out.append((render(s), target.name))
422
+ notes_out.append(f"Relation({first}): has-many, loaded by a second query")
423
+ else:
424
+ q.tail.append(marker(f"Relation({rel_name}) {rel.kind}"))
425
+ q.dynamic = True
426
+ return out
427
+
428
+
429
+ def final(ev, q, name: str, args: list[Node], call: Node, gf: GoFile, bind) -> list: # noqa: C901
430
+ """The statements a terminal (Scan, Exec, Count, Exists, ScanAndCount, Rows) runs."""
431
+ Om = O()
432
+ Stmt, Unresolved, render, marker = Om.Stmt, Om.Unresolved, Om.render, Om.marker
433
+ if "unsupported" in q.flags:
434
+ raise Unresolved(f"{q.notes[-1] if q.notes else 'this query kind is not translated'}")
435
+ kind = q.kind or "select"
436
+ _settle(q)
437
+ # Scan(ctx, &dest): with no Model(), the destination is the model
438
+ if q.model is None and not q.table and name in ("Scan", "ScanAndCount", "Exec") and len(args) > 1:
439
+ m = model_of(ev, gf, args[1], call)
440
+ if m is not None:
441
+ q.model = m
442
+ if q.model is None and not q.table:
443
+ if "model_unknown" in q.flags:
444
+ raise Unresolved("the model is not a struct this scan can read")
445
+ raise Unresolved("no table: neither Model() nor Table() names one")
446
+ if q.model is not None:
447
+ q.model.used = True
448
+ target = q.model.name if q.model is not None and not q.table else Om._table_word(q.table)
449
+ notes = list(q.notes)
450
+ conf = lambda: "medium" if q.dynamic or notes else "high" # noqa: E731
451
+ eng = q.engine
452
+
453
+ def stmt(sql: str, op: str, more: list[str] | None = None) -> Stmt:
454
+ if not sql:
455
+ raise Unresolved(Om._why_not(q))
456
+ return Stmt(sql, op, target, conf() if not more else "medium", notes + (more or []), eng)
457
+
458
+ table_plain = q.table or (T.ident(q.model.table) if q.model is not None else "")
459
+ if kind == "select":
460
+ extra_notes: list[str] = []
461
+ extra = _relation_stmts(ev, q, extra_notes) if q.preloads else []
462
+ s = _select_q(q)
463
+ if s is None:
464
+ raise Unresolved("no table")
465
+ if "rel_cols" in q.flags and getattr(q, "cols_rel", None):
466
+ s.cols = s.cols + q.cols_rel
467
+ out = []
468
+ if name in ("Count",):
469
+ c = s.clone()
470
+ c.cols, c.order, c.limit, c.offset = ["count(*)"], [], "", ""
471
+ return [stmt(render(c), "count")]
472
+ if name == "Exists":
473
+ return [stmt(f"SELECT EXISTS ({render(s)})", "select")]
474
+ out.append(stmt(render(s), "select", extra_notes or None))
475
+ for sql, tname in extra:
476
+ out.append(Stmt(sql, "select", tname, "medium", notes + extra_notes, eng))
477
+ if name == "ScanAndCount":
478
+ c = s.clone()
479
+ c.cols, c.order, c.limit, c.offset = ["count(*)"], [], "", ""
480
+ out.append(stmt(render(c), "count", ["ScanAndCount: the count runs beside the select"]))
481
+ return out
482
+ if kind == "insert":
483
+ m = q.model
484
+ if q.sets and "values" not in q.flags and "on_conflict" not in q.flags:
485
+ pass
486
+ cols: list[str]
487
+ if q.cols:
488
+ cols = [c for c in q.cols]
489
+ elif m is not None:
490
+ cols = [T.ident(c.name) for c in m.cols if not c.autoincr and c.role != "scanonly" and c.name not in q.omit]
491
+ else:
492
+ cols = []
493
+ head = f"INSERT INTO {table_plain}"
494
+ if cols:
495
+ sql = f"{head} ({', '.join(cols)}) VALUES ({', '.join('?' for _ in cols)})"
496
+ else:
497
+ sql = f"{head} VALUES ({marker('values')})"
498
+ suffix = list(q.suffix)
499
+ if "on_conflict" in q.flags and q.sets:
500
+ i = next(i for i, x in enumerate(suffix) if x.startswith("ON "))
501
+ suffix.insert(i + 1, "SET " + ", ".join(q.sets))
502
+ if "ignore" in q.flags and not any(x.startswith("ON CONFLICT") for x in suffix):
503
+ suffix.insert(0, "ON CONFLICT DO NOTHING")
504
+ sql = " ".join([sql] + [_fill(q, x) for x in suffix] + [f"/* {t} */" for t in q.tail])
505
+ return [stmt(sql, "insert")]
506
+ if kind == "update":
507
+ s = q.clone()
508
+ s.kind = "update"
509
+ s.table = _from(q, with_extra=False)
510
+ if getattr(q, "from_extra", []):
511
+ s.joins = ["FROM " + ", ".join(q.from_extra)] + s.joins
512
+ s.model = None
513
+ m = q.model
514
+ if not s.sets:
515
+ if q.cols and m is not None:
516
+ s.sets = [f"{c} = ?" for c in q.cols]
517
+ elif m is not None:
518
+ s.sets = [f"{T.ident(c.name)} = ?" for c in m.cols if not c.pk and c.role != "scanonly" and c.name not in q.omit]
519
+ else:
520
+ raise Unresolved("an update with no Set() and no model columns")
521
+ if not s.where and "model_instance" in q.flags and m is not None:
522
+ s.where = "\x06PK\x06"
523
+ notes.append("no Where: bun updates the row with the primary key of the value given to Model()")
524
+ s.and_(_soft(q))
525
+ s.cols = []
526
+ s.map_text(lambda t: _fill(q, t))
527
+ return [stmt(render(s), "update")]
528
+ if kind == "delete":
529
+ s = q.clone()
530
+ m = q.model
531
+ s.table = _from(q, with_extra=False)
532
+ if getattr(q, "from_extra", []):
533
+ s.joins = ["USING " + ", ".join(q.from_extra)] + s.joins
534
+ s.model = None
535
+ if not s.where and "model_instance" in q.flags and m is not None:
536
+ s.where = "\x06PK\x06"
537
+ notes.append("no Where: bun deletes the row with the primary key of the value given to Model()")
538
+ deleted = m.role("deleted") if m is not None else ""
539
+ if deleted and "force_delete" not in q.flags:
540
+ s.kind, s.sets = "update", [f"{T.ident(deleted)} = ?"]
541
+ s.and_(_soft(q))
542
+ notes.append("soft delete: the model has a soft_delete column")
543
+ else:
544
+ s.kind = "delete"
545
+ s.map_text(lambda t: _fill(q, t))
546
+ return [stmt(render(s), s.kind if s.kind == "delete" else "update")]
547
+ # DDL builders
548
+ m = q.model
549
+ tname = table_plain
550
+ if kind == "create_table":
551
+ if m is None or not m.cols:
552
+ raise Unresolved("CREATE TABLE with no model columns")
553
+ cols = []
554
+ for c in m.cols:
555
+ if c.role == "scanonly":
556
+ continue
557
+ cols.append(f"{T.ident(c.name)} {sql_type(c)}" + (" PRIMARY KEY" if c.pk and len(m.pk) == 1 else ""))
558
+ if len(m.pk) > 1:
559
+ cols.append(f"PRIMARY KEY ({', '.join(T.ident(p) for p in m.pk)})")
560
+ ine = "IF NOT EXISTS " if "IfNotExists" in q.flags else ""
561
+ return [stmt(f"CREATE TABLE {ine}{tname} ({', '.join(cols + [x for x in q.suffix if x and not x.startswith('ON ')])})", "ddl")]
562
+ if kind == "drop_table":
563
+ return [stmt(f"DROP TABLE {'IF EXISTS ' if 'IfExists' in q.flags else ''}{tname}{' CASCADE' if 'cascade' in q.flags else ''}", "ddl")]
564
+ if kind == "truncate":
565
+ return [stmt(f"TRUNCATE TABLE {tname}", "ddl")]
566
+ if kind == "create_index":
567
+ if not q.alias or not q.cols:
568
+ raise Unresolved("CREATE INDEX with no name or no columns in the chain")
569
+ ine = "IF NOT EXISTS " if "IfNotExists" in q.flags else ""
570
+ return [stmt(f"CREATE {'UNIQUE ' if 'unique' in q.flags else ''}INDEX {ine}{q.alias} ON {T.ident(m.table) if m is not None and not q.table else q.table} ({', '.join(q.cols)})", "ddl")]
571
+ if kind == "drop_index":
572
+ if not q.alias:
573
+ raise Unresolved("DROP INDEX with no name in the chain")
574
+ return [stmt(f"DROP INDEX {'IF EXISTS ' if 'IfExists' in q.flags else ''}{q.alias}", "ddl")]
575
+ if kind == "add_column":
576
+ if not q.cols:
577
+ raise Unresolved("ADD COLUMN with no ColumnExpr")
578
+ return [stmt(f"ALTER TABLE {tname} ADD COLUMN {'IF NOT EXISTS ' if 'IfNotExists' in q.flags else ''}{q.cols[0]}", "ddl")]
579
+ if kind == "drop_column":
580
+ if not q.cols:
581
+ raise Unresolved("DROP COLUMN with no Column")
582
+ return [stmt(f"ALTER TABLE {tname} DROP COLUMN {q.cols[0]}", "ddl")]
583
+ raise Unresolved(f"{kind} queries are not translated")
584
+
585
+
586
+ _GO_SQL = {"string": "varchar", "bool": "boolean", "int": "bigint", "int64": "bigint", "int32": "integer", "int16": "smallint",
587
+ "int8": "smallint", "uint": "bigint", "uint64": "bigint", "uint32": "bigint", "uint16": "integer", "uint8": "smallint",
588
+ "float64": "double precision", "float32": "real", "time.Time": "timestamptz", "[]byte": "bytea",
589
+ "json.RawMessage": "jsonb", "uuid.UUID": "uuid"}
590
+
591
+
592
+ def sql_type(c) -> str:
593
+ """bun's `type:` tag, else bun's default for the Go type (pgdialect); a type it stores as JSON otherwise."""
594
+ t = (c.type or "").strip()
595
+ if t and not re.match(r"^[\*\[\]\w.]+$", t):
596
+ return t # already an SQL type from the tag (`type:text`, `varchar(64)`)
597
+ if re.fullmatch(r"[a-z][a-z0-9 ()]*", t) and t not in _GO_SQL:
598
+ return t
599
+ base = t.lstrip("*")
600
+ if c.pk and c.autoincr and base.startswith(("int", "uint")):
601
+ return "bigserial"
602
+ return _GO_SQL.get(base, "jsonb")