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,1117 @@
1
+ """Knex query-builder chains and schema-builder calls as SQL sites.
2
+
3
+ A chain starts at a Knex handle: `knex("users")`, `trx("users")`, `db("users")`, `this.knex("users")`,
4
+ `knex.select(...).from("users")`, `knex.insert({...}).into("users")`, `knex.table("users")`, `knex.from(...)`.
5
+ The handle is a name Knex is known by (`knex`, `trx`, `db`, `database`, `transaction`, a `this.knex` / `this.#knex`
6
+ field, `options.transacting`) in a file of a package that depends on knex or imports it.
7
+
8
+ The chain's steps are read in order: select / column / first / pluck / count / sum / min / max / avg / distinct,
9
+ from / into / table, every where form (`where(obj)`, `where(col, value)`, `where(col, op, value)`, `where(fn)` as a
10
+ group, whereIn / whereNotIn / whereNull / whereNotNull / whereBetween / whereLike / whereILike / whereExists /
11
+ whereRaw and their `and` / `or` / `not` forms), join / leftJoin / ... (`on` callbacks included), orderBy, groupBy,
12
+ having, limit, offset, insert, update, del / delete, increment / decrement, returning, onConflict().merge() / ignore(),
13
+ forUpdate, with, raw fragments (`?` bound values, `??` identifiers). A chain kept in a variable gets the later
14
+ `q.where(...)` calls of the same function; those under a condition become one «optional» run-time part each.
15
+
16
+ `knex.schema.createTable / alterTable / dropTable / hasTable / hasColumn / renameTable` give the DDL (or catalog read)
17
+ Knex sends, and `createTable` / `alterTable` callbacks give the tables of the schema (`KnexSchema.tables`).
18
+ Anything only known at run time (a table in a variable, a callback passed to `modify`, a spread object) is a
19
+ «run-time part»; nothing is invented.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ import re
26
+
27
+ from tree_sitter import Node, Parser
28
+
29
+ from . import orm_ts as o
30
+ from .orm_ts import mark, mark_node, txt, unwrap
31
+ from .orm_ts_schema import climb, in_down, spine
32
+
33
+ NAME = "knex"
34
+ HANDLE = re.compile(r"^(?:this\.|self\.|options\.|opts\.|ctx\.|db\.|deps\.|context\.)?(?:#|_)?(?:knex\w*|\w*Knex|trx|tx|db|database|"
35
+ r"transaction|transacting|conn|connection|dbConn|qb|knexInstance)$")
36
+ PRE = re.compile(rb"\bknex\b|\bKnex\b")
37
+ STARTS = {"select", "from", "table", "into", "insert", "update", "del", "delete", "count", "countDistinct", "sum", "min",
38
+ "max", "avg", "first", "pluck", "distinct", "with", "withRecursive", "queryBuilder", "column", "columns", "where",
39
+ "truncate", "increment", "decrement", "distinctOn", "upsert"}
40
+ NO_OP = {"transacting", "timeout", "connection", "debug", "options", "clone", "queryContext", "then", "catch", "finally",
41
+ "asCallback", "stream", "pipe", "toString", "toQuery", "toSQL", "returning_", "skipLocked", "noWait", "as", "on",
42
+ "hintComment", "comment", "clearCounters"}
43
+ JOINS = {"join": "INNER JOIN", "innerJoin": "INNER JOIN", "leftJoin": "LEFT JOIN", "leftOuterJoin": "LEFT OUTER JOIN",
44
+ "rightJoin": "RIGHT JOIN", "rightOuterJoin": "RIGHT OUTER JOIN", "fullOuterJoin": "FULL OUTER JOIN",
45
+ "outerJoin": "FULL OUTER JOIN", "crossJoin": "CROSS JOIN"}
46
+ AGG = {"count": "COUNT", "countDistinct": "COUNT", "sum": "SUM", "sumDistinct": "SUM", "min": "MIN", "max": "MAX",
47
+ "avg": "AVG", "avgDistinct": "AVG"}
48
+ SCHEMA = {"createTable", "createTableIfNotExists", "alterTable", "table", "dropTable", "dropTableIfExists", "hasTable",
49
+ "hasColumn", "renameTable", "raw", "createView", "dropView", "createSchema", "dropSchema"}
50
+ TYPES = {"increments": "serial", "bigIncrements": "bigserial", "integer": "integer", "bigInteger": "bigint",
51
+ "bigint": "bigint", "tinyint": "smallint", "smallint": "smallint", "mediumint": "integer", "text": "text",
52
+ "string": "varchar(255)", "float": "real", "double": "double precision", "decimal": "decimal", "boolean": "boolean",
53
+ "date": "date", "datetime": "timestamptz", "timestamp": "timestamptz", "time": "time", "binary": "bytea",
54
+ "enu": "text", "enum": "text", "json": "json", "jsonb": "jsonb", "uuid": "uuid", "specificType": "",
55
+ "geometry": "geometry", "geography": "geography", "point": "point"}
56
+
57
+
58
+ def _handle(text: str) -> bool:
59
+ return bool(HANDLE.match(text.replace(" ", "")))
60
+
61
+
62
+ def _str(node: Node | None) -> str | None:
63
+ return o.string_value(node)
64
+
65
+
66
+ class Skip(Exception):
67
+ pass
68
+
69
+
70
+ # ---- the schema builder ---------------------------------------------------------------------------------------
71
+
72
+ def _column_defs(f_text: str, body: Node | None, param: str) -> tuple[list[dict], list[str], list[str], list[dict], list[str]]:
73
+ """Column calls in a createTable / alterTable callback: (columns, primary key, dropped, indexes, other actions)."""
74
+ cols: list[dict] = []
75
+ pk: list[str] = []
76
+ dropped: list[str] = []
77
+ idx: list[dict] = []
78
+ other: list[str] = []
79
+ if body is None:
80
+ return cols, pk, dropped, idx, other
81
+ stack = [body]
82
+ seen: set[int] = set()
83
+ while stack:
84
+ n = stack.pop()
85
+ if n.type == "call_expression" and n.id not in seen:
86
+ base, steps = spine(n)
87
+ for _s, _a, c in steps:
88
+ seen.add(c.id)
89
+ if base is not None and txt(base) == param and steps:
90
+ name, args, _c = steps[0]
91
+ mods = [s[0] for s in steps[1:]]
92
+ first = _str(args[0]) if args else None
93
+ if name in TYPES and first:
94
+ ctype = TYPES[name]
95
+ if name == "specificType" and len(args) > 1:
96
+ ctype = _str(args[1]) or "text"
97
+ elif name == "string" and len(args) > 1 and o.literal(args[1]) and o.literal(args[1]).isdigit():
98
+ ctype = f"varchar({o.literal(args[1])})"
99
+ elif name in ("timestamp", "datetime") and len(args) > 1 and "useTz: false" in txt(args[1]):
100
+ ctype = "timestamp"
101
+ notnull = "notNullable" in mods or "primary" in mods or name in ("increments", "bigIncrements")
102
+ cols.append({"name": first, "type": ctype + (" NOT NULL" if notnull else ""),
103
+ "alter": "alter" in mods})
104
+ if "primary" in mods or name in ("increments", "bigIncrements"):
105
+ pk.append(first)
106
+ if "unique" in mods:
107
+ idx.append({"name": "", "columns": [first], "unique": True})
108
+ if "index" in mods:
109
+ idx.append({"name": "", "columns": [first], "unique": False})
110
+ elif name in ("timestamps",):
111
+ cols += [{"name": "created_at", "type": "timestamptz"}, {"name": "updated_at", "type": "timestamptz"}]
112
+ elif name in ("primary", "unique", "index") and args:
113
+ items = o.array_items(args[0])
114
+ names = [_str(i) for i in items] if items is not None else ([first] if first else [])
115
+ names = [x for x in names if x]
116
+ if names:
117
+ if name == "primary":
118
+ pk = names
119
+ else:
120
+ idx.append({"name": _str(args[1]) if len(args) > 1 else "", "columns": names, "unique": name == "unique"})
121
+ elif name in ("dropColumn", "dropColumns"):
122
+ dropped += [x for x in (_str(a) for a in args) if x]
123
+ elif name in ("renameColumn",) and len(args) == 2 and _str(args[0]) and _str(args[1]):
124
+ other.append(f'RENAME COLUMN "{_str(args[0])}" TO "{_str(args[1])}"')
125
+ elif name in ("foreign",) and first:
126
+ target = next((s for s in steps if s[0] == "references"), None)
127
+ table = next((s for s in steps if s[0] == "inTable"), None)
128
+ ref = _str(target[1][0]) if target and target[1] else None
129
+ tab = _str(table[1][0]) if table and table[1] else None
130
+ if ref and "." in ref and not tab:
131
+ tab, ref = ref.split(".", 1)
132
+ if ref and tab:
133
+ other.append(f'ADD FOREIGN KEY ("{first}") REFERENCES "{tab}" ("{ref}")')
134
+ elif name in ("dropForeign", "dropIndex", "dropUnique", "dropPrimary", "dropTimestamps", "setNullable",
135
+ "dropNullable", "comment", "engine", "charset", "collate", "inherits", "check", "dropChecks"):
136
+ other.append(name)
137
+ elif base is None or txt(base) != param:
138
+ # a helper handed the table builder and a column name: `primaryKeyAsGeneratedIdentity(table, 'project_id')`
139
+ fn = unwrap(n.child_by_field_name("function"))
140
+ a = n.child_by_field_name("arguments")
141
+ args = [x for x in (a.named_children if a is not None else []) if x.type != "comment"]
142
+ if fn is not None and fn.type == "identifier" and len(args) >= 2 and txt(unwrap(args[0])) == param and _str(args[1]):
143
+ col = _str(args[1])
144
+ if re.fullmatch(r"[A-Za-z_]\w*", col) and all(c["name"] != col for c in cols):
145
+ helper = txt(fn).lower()
146
+ ctype = "uuid" if col.endswith("uuid") else "integer" if col.endswith("_id") or "identity" in helper or "increments" in helper else "text"
147
+ cols.append({"name": col, "type": ctype + (" NOT NULL" if "primary" in helper or "identity" in helper else ""),
148
+ "alter": False})
149
+ if "primary" in helper:
150
+ pk.append(col)
151
+ stack.extend(reversed(n.children))
152
+ return cols, pk, dropped, idx, other
153
+
154
+
155
+ class KnexSchema:
156
+ """Tables created and altered through `knex.schema` (migrations)."""
157
+
158
+ def __init__(self):
159
+ self.created: list[tuple[str, int, str, list[dict], list[str], list[dict]]] = []
160
+ self.altered: list[tuple[str, str, list[dict], list[str]]] = []
161
+
162
+ @staticmethod
163
+ def wants(src: bytes) -> bool:
164
+ return (b"createTable" in src or b"alterTable" in src) and b"knex" in src.lower()
165
+
166
+ def add(self, rel: str, src: bytes) -> None:
167
+ from .typescript import language_for
168
+ tree = Parser(language_for(rel)).parse(src)
169
+ stack = [tree.root_node]
170
+ while stack:
171
+ n = stack.pop()
172
+ stack.extend(n.children)
173
+ if n.type != "call_expression":
174
+ continue
175
+ fn = unwrap(n.child_by_field_name("function"))
176
+ if fn is None or fn.type != "member_expression":
177
+ continue
178
+ head = txt(fn.child_by_field_name("property"))
179
+ if head not in ("createTable", "createTableIfNotExists", "alterTable", "table") or \
180
+ not txt(fn.child_by_field_name("object")).endswith("schema"):
181
+ continue
182
+ a = n.child_by_field_name("arguments")
183
+ args = [x for x in (a.named_children if a is not None else []) if x.type != "comment"]
184
+ name = _str(args[0]) if args else None
185
+ if not name and args and unwrap(args[0]) is not None and unwrap(args[0]).type == "identifier":
186
+ # `const TABLE = 'organization_settings'` in the migration file, then alterTable(TABLE, ...)
187
+ m = re.search(rb"(?:const|let|var)\s+" + re.escape(txt(unwrap(args[0])).encode()) + rb"\s*(?::\s*\w+\s*)?=\s*['\"`]([\w.]+)['\"`]", src)
188
+ name = m.group(1).decode() if m else None
189
+ if not name or len(args) < 2 or in_down(n):
190
+ continue
191
+ cb = unwrap(args[1])
192
+ if cb is None or cb.type not in ("arrow_function", "function_expression", "function"):
193
+ continue
194
+ params = cb.child_by_field_name("parameters") or cb.child_by_field_name("parameter")
195
+ param = txt(params.named_children[0] if params is not None and params.named_children else params).split(":")[0].strip("() ")
196
+ cols, pk, dropped, idx, _other = _column_defs(rel, cb.child_by_field_name("body"), param)
197
+ if head.startswith("create"):
198
+ if cols:
199
+ self.created.append((rel, n.start_point[0] + 1, name, cols, pk, idx))
200
+ elif cols or dropped:
201
+ self.altered.append((rel, name, [c for c in cols if not c.get("alter")], dropped))
202
+
203
+ def tables(self) -> list:
204
+ from .schema_ts import TsTable
205
+ by_name: dict[str, list] = {}
206
+ out = []
207
+ for rel, line, name, cols, pk, idx in self.created:
208
+ t = TsTable(name=name, defined_at=[f"{rel}:{line}"], columns=[{"name": c["name"], "type": c["type"]} for c in cols],
209
+ primary_key=", ".join(pk), indexes=[dict(i) for i in idx])
210
+ by_name.setdefault(name, []).append(t)
211
+ out.append(t)
212
+ for rel, name, cols, dropped in sorted(self.altered, key=lambda a: a[0]):
213
+ ts = by_name.get(name)
214
+ if not ts:
215
+ continue
216
+ # the migrations' own table, not a copy a script or test creates for itself (a seed or benchmark script)
217
+ t = next((x for x in reversed(ts) if re.search(r"(^|/)migrat", x.defined_at[0]) and
218
+ not re.search(r"(^|/)(scripts?|tests?|__tests__)/|\.(test|spec|integration)\.", x.defined_at[0])), ts[-1])
219
+ have = {c["name"] for c in t.columns}
220
+ t.columns += [{"name": c["name"], "type": c["type"]} for c in cols if c["name"] not in have]
221
+ t.columns = [c for c in t.columns if c["name"] not in dropped]
222
+ return out
223
+
224
+
225
+ # ---- the library --------------------------------------------------------------------------------------------------
226
+
227
+ class Library:
228
+ name = NAME
229
+
230
+ def __init__(self, ctx, root, files, stats):
231
+ self.ctx, self.stats = ctx, stats
232
+ self.active = True
233
+
234
+ def wants(self, rel: str, src: bytes, deps) -> bool:
235
+ if not ("knex" in deps or b"knex" in src) or b"drizzle-orm" in src or b"from 'kysely'" in src or b'from "kysely"' in src:
236
+ return False
237
+ return bool(PRE.search(src) or b"trx(" in src or b"db(" in src)
238
+
239
+ def prepare(self, wanted) -> None:
240
+ pass
241
+
242
+ def sites(self, f) -> list:
243
+ out = []
244
+ done: list[tuple[int, int]] = []
245
+ tops: list[tuple[Node, Node, bool]] = []
246
+ for call in f.calls:
247
+ fn = unwrap(call.child_by_field_name("function"))
248
+ if fn is None:
249
+ continue
250
+ if fn.type in ("identifier", "member_expression") and _handle(txt(fn)):
251
+ a = call.child_by_field_name("arguments")
252
+ args = [x for x in (a.named_children if a is not None and a.type == "arguments" else []) if x.type != "comment"]
253
+ if len(args) != 1 or not (_str(args[0]) is not None or unwrap(args[0]).type in ("identifier", "member_expression", "template_string")):
254
+ continue
255
+ if fn.type == "member_expression" and txt(fn.child_by_field_name("property")) in STARTS | SCHEMA:
256
+ continue
257
+ tops.append((call, climb(call), False))
258
+ elif fn.type == "member_expression":
259
+ prop = txt(fn.child_by_field_name("property"))
260
+ recv = unwrap(fn.child_by_field_name("object"))
261
+ if recv is None:
262
+ continue
263
+ rt = txt(recv)
264
+ if prop in STARTS and _handle(rt):
265
+ tops.append((call, climb(call), False))
266
+ elif prop in SCHEMA and rt.endswith(".schema") and _handle(rt[: -len(".schema")]):
267
+ tops.append((call, call, True))
268
+ tops.sort(key=lambda t: (t[1].start_byte, -t[1].end_byte))
269
+ for base, top, ddl in tops:
270
+ if any(s <= top.start_byte and top.end_byte <= e for s, e in done):
271
+ continue
272
+ self.stats.see(NAME, f.test)
273
+ line = top.start_point[0] + 1
274
+ try:
275
+ made = Ddl(f, base).run() if ddl else Chain(f, base, top).run()
276
+ except Skip as e:
277
+ self.stats.miss(NAME, f.test, str(e), f.rel, line)
278
+ continue
279
+ except Exception as e:
280
+ if os.environ.get("CODECOP_ORM_DEBUG"):
281
+ raise
282
+ self.stats.miss(NAME, f.test, f"internal error ({type(e).__name__})", f.rel, line)
283
+ continue
284
+ done.append((top.start_byte, top.end_byte))
285
+ self.stats.ok(NAME, f.test, len(made))
286
+ out.extend(made)
287
+ return out
288
+
289
+
290
+ def _site(f, node: Node, sink: str, engine: str, sql: str, *, table: str, operation: str, level: int, notes: list[str],
291
+ mechanism: str = "query_builder"):
292
+ site = o.make_site(f, node, sink, engine, sql, node, library=NAME, table=table, operation=operation,
293
+ confidence=o.CONFIDENCE[level], notes=notes)
294
+ site.orm["mechanism"] = mechanism
295
+ return site
296
+
297
+
298
+ class Ddl:
299
+ def __init__(self, f, call: Node):
300
+ self.f, self.call = f, call
301
+ self.engine = o.engine_of(f)
302
+
303
+ def q(self, name: str) -> str:
304
+ return o.quote(self.engine, name)
305
+
306
+ def run(self) -> list:
307
+ fn = unwrap(self.call.child_by_field_name("function"))
308
+ head = txt(fn.child_by_field_name("property"))
309
+ a = self.call.child_by_field_name("arguments")
310
+ args = [x for x in (a.named_children if a is not None else []) if x.type != "comment"]
311
+ name = _str(args[0]) if args else None
312
+ notes: list[str] = []
313
+ level = 2
314
+ table = self.q(name) if name else (mark_node(args[0]) if args else "")
315
+ if not args:
316
+ raise Skip("schema call without arguments")
317
+ if not name:
318
+ level = 1
319
+ notes.append("table name chosen at run time")
320
+ stmts: list[str] = []
321
+ op = "ddl"
322
+ if head in ("createTable", "createTableIfNotExists", "alterTable", "table"):
323
+ cb = unwrap(args[1]) if len(args) > 1 else None
324
+ if cb is None or cb.type not in ("arrow_function", "function_expression", "function"):
325
+ raise Skip("schema callback not visible")
326
+ params = cb.child_by_field_name("parameters") or cb.child_by_field_name("parameter")
327
+ param = txt(params.named_children[0] if params is not None and params.named_children else params).split(":")[0].strip("() ")
328
+ cols, pk, dropped, idx, other = _column_defs(self.f.rel, cb.child_by_field_name("body"), param)
329
+ if head.startswith("create"):
330
+ defs = [f"{self.q(c['name'])} {c['type']}" for c in cols]
331
+ if pk:
332
+ defs.append("PRIMARY KEY (" + ", ".join(self.q(p) for p in pk) + ")")
333
+ if not defs:
334
+ raise Skip("createTable with no column read")
335
+ ine = " IF NOT EXISTS" if head == "createTableIfNotExists" else ""
336
+ stmts.append(f"CREATE TABLE{ine} {table} ({', '.join(defs)})")
337
+ else:
338
+ acts = [f"ADD COLUMN {self.q(c['name'])} {c['type']}" if not c.get("alter")
339
+ else f"ALTER COLUMN {self.q(c['name'])} TYPE {c['type'].replace(' NOT NULL', '')}" for c in cols]
340
+ acts += [f"DROP COLUMN {self.q(d)}" for d in dropped]
341
+ acts += [x for x in other if " " in x]
342
+ skipped = [x for x in other if " " not in x]
343
+ if skipped:
344
+ notes.append("not translated: " + ", ".join(dict.fromkeys(skipped)))
345
+ level = min(level, 1)
346
+ if acts:
347
+ stmts.append(f"ALTER TABLE {table} " + ", ".join(acts))
348
+ for i in idx:
349
+ stmts.append(f"CREATE {'UNIQUE ' if i['unique'] else ''}INDEX ON {table} (" + ", ".join(self.q(c) for c in i["columns"]) + ")")
350
+ if not stmts:
351
+ raise Skip("schema callback changes nothing that is read")
352
+ elif head in ("dropTable", "dropTableIfExists"):
353
+ stmts.append(f"DROP TABLE{' IF EXISTS' if head.endswith('IfExists') else ''} {table}")
354
+ elif head == "renameTable" and len(args) > 1:
355
+ to = _str(args[1])
356
+ stmts.append(f"ALTER TABLE {table} RENAME TO {self.q(to) if to else mark_node(args[1])}")
357
+ elif head == "hasTable":
358
+ op = "select"
359
+ stmts.append(f"SELECT * FROM information_schema.tables WHERE table_name = {o.value(args[0])}")
360
+ elif head == "hasColumn" and len(args) > 1:
361
+ op = "select"
362
+ stmts.append(f"SELECT * FROM information_schema.columns WHERE table_name = {o.value(args[0])} AND column_name = {o.value(args[1])}")
363
+ elif head == "raw":
364
+ raise Skip("knex.schema.raw: the raw SQL is read by the string extractor")
365
+ else:
366
+ raise Skip(f"schema.{head} not translated")
367
+ return [_site(self.f, self.call, txt(fn), self.engine, s, table=name or "", operation=op, level=level, notes=notes,
368
+ mechanism="query_builder") for s in stmts]
369
+
370
+
371
+ class Chain:
372
+ """One builder chain (and the later calls on the variable that holds it)."""
373
+
374
+ def __init__(self, f, base: Node, top: Node, nested: bool = False):
375
+ self.f, self.base, self.top = f, base, top
376
+ self.engine = o.engine_of(f)
377
+ self.notes: list[str] = []
378
+ self.level = 2
379
+ self.table = ""
380
+ self.table_sql = ""
381
+ self.alias = ""
382
+ self.op = "select"
383
+ self.cols: list[str] = []
384
+ self.distinct = False
385
+ self.wheres: list[tuple[str, str]] = [] # (AND|OR, predicate)
386
+ self.joins: list[str] = []
387
+ self.order: list[str] = []
388
+ self.group: list[str] = []
389
+ self.having: list[tuple[str, str]] = []
390
+ self.limit: str | None = None
391
+ self.offset: str | None = None
392
+ self.values: list[tuple[list[str], list[str]]] = []
393
+ self.sets: list[str] = []
394
+ self.returning: list[str] = []
395
+ self.conflict: str = ""
396
+ self.lock = ""
397
+ self.ctes: list[str] = []
398
+ self.nested = nested
399
+
400
+ def q(self, name: str) -> str:
401
+ return o.quote(self.engine, name)
402
+
403
+ def lower(self, level: int, note: str) -> None:
404
+ self.level = min(self.level, level)
405
+ if note not in self.notes:
406
+ self.notes.append(note)
407
+
408
+ # -- names --------------------------------------------------------------------------------------------------
409
+ def ident(self, text: str) -> str:
410
+ """`users.id` -> "users"."id"; `name as n` -> "name" AS "n"; `*` stays."""
411
+ m = re.match(r"^\s*(.+?)\s+as\s+([\w$]+)\s*$", text, re.I)
412
+ if m:
413
+ return f"{self.ident(m.group(1))} AS {self.q(m.group(2))}"
414
+ return ".".join(p if p == "*" else self.q(p.strip()) for p in text.split("."))
415
+
416
+ def name(self, node: Node | None) -> str:
417
+ """A column or table argument: a string (or a constant) as an identifier, else a run-time part."""
418
+ node = unwrap(node)
419
+ s = _str(node)
420
+ if s is None and node is not None and node.type in ("identifier", "member_expression", "template_string", "binary_expression"):
421
+ try:
422
+ r = self.f.resolve(node, self.top)
423
+ except Exception:
424
+ r = None
425
+ if r is not None and r.text and "«" not in r.text and not r.dynamic and re.fullmatch(r"[\w$]+(?:\.[\w$]+)*(?:\.\*)?(?:\s+as\s+[\w$]+)?", r.text.strip(), re.I):
426
+ s = r.text.strip()
427
+ if s is not None:
428
+ return self.ident(s)
429
+ if node is not None and node.type == "call_expression":
430
+ raw = self.raw(node)
431
+ if raw is not None:
432
+ return raw
433
+ return mark_node(node)
434
+
435
+ def table_name(self, node: Node | None) -> str:
436
+ node = unwrap(node)
437
+ s = _str(node)
438
+ if s is None and node is not None and node.type == "object":
439
+ pairs = [c for c in node.named_children if c.type == "pair"]
440
+ if len(pairs) == 1 and _str(pairs[0].child_by_field_name("value")):
441
+ alias = txt(pairs[0].child_by_field_name("key")).strip("'\"")
442
+ t = _str(pairs[0].child_by_field_name("value"))
443
+ self.table = self.table or t
444
+ return f"{self.ident(t)} AS {self.q(alias)}"
445
+ got = self.name(node)
446
+ if "«" in got:
447
+ sub = self.subquery(node)
448
+ if sub is not None:
449
+ return sub
450
+ self.lower(1, "table chosen at run time")
451
+ elif not self.table:
452
+ self.table = got.split(" AS ")[0].replace('"', "").replace("`", "")
453
+ return got
454
+
455
+ # -- values -----------------------------------------------------------------------------------------------------
456
+ def raw(self, node: Node | None) -> str | None:
457
+ """knex.raw("... ? ...", [v]) / db.raw(...) as SQL text, or None when it is not a raw call."""
458
+ node = unwrap(node)
459
+ if node is None or node.type != "call_expression":
460
+ return None
461
+ fn = unwrap(node.child_by_field_name("function"))
462
+ if fn is None or fn.type != "member_expression" or txt(fn.child_by_field_name("property")) != "raw":
463
+ return None
464
+ a = node.child_by_field_name("arguments")
465
+ args = [x for x in (a.named_children if a is not None else []) if x.type != "comment"]
466
+ if not args:
467
+ return None
468
+ return self.raw_text(args[0], args[1] if len(args) > 1 else None)
469
+
470
+ def raw_text(self, sql_node: Node | None, bindings: Node | None) -> str:
471
+ text = _str(sql_node)
472
+ if text is None:
473
+ try:
474
+ r = self.f.resolve(sql_node, self.top)
475
+ except Exception:
476
+ r = None
477
+ if r is None or not r.text:
478
+ self.lower(1, "raw SQL fragment built at run time")
479
+ return mark_node(sql_node)
480
+ text = r.text
481
+ items = o.array_items(bindings) if bindings is not None else None
482
+ named = None
483
+ if items is None and bindings is not None:
484
+ obj = o.as_object(self.f, bindings, self.top)
485
+ named = dict(obj.entries) if obj is not None else None
486
+ out, i, k = [], 0, 0
487
+ while i < len(text):
488
+ if text.startswith("??", i):
489
+ b = items[k] if items is not None and k < len(items) else None
490
+ s = _str(b) if b is not None else None
491
+ out.append(self.ident(s) if s else mark(txt(b) if b is not None else "identifier"))
492
+ k, i = k + 1, i + 2
493
+ elif text[i] == "?" and not text.startswith("?|", i) and not text.startswith("?&", i):
494
+ b = items[k] if items is not None and k < len(items) else None
495
+ out.append(o.value(b) if b is not None else mark("binding"))
496
+ k, i = k + 1, i + 1
497
+ elif text[i] == ":" and named is not None and re.match(r":(\w+)(:?)", text[i:]):
498
+ mm = re.match(r":(\w+)(:?)", text[i:])
499
+ v = named.get(mm.group(1))
500
+ if mm.group(2):
501
+ s = _str(v)
502
+ out.append(self.ident(s) if s else mark(mm.group(1)))
503
+ else:
504
+ out.append(o.value(v) if v is not None else mark(mm.group(1)))
505
+ i += len(mm.group(0))
506
+ else:
507
+ out.append(text[i])
508
+ i += 1
509
+ return "".join(out)
510
+
511
+ def val(self, node: Node | None) -> str:
512
+ node = unwrap(node)
513
+ if node is None:
514
+ return "NULL"
515
+ r = self.raw(node)
516
+ if r is not None:
517
+ return r
518
+ sub = self.subquery(node)
519
+ if sub is not None:
520
+ return sub
521
+ if node.type == "member_expression" and re.search(r"\.fn\.now$", txt(node.child_by_field_name("object")) + "." + txt(node.child_by_field_name("property"))):
522
+ return "CURRENT_TIMESTAMP"
523
+ if node.type == "call_expression" and re.search(r"\.fn\.now\s*\(", txt(node)):
524
+ return "CURRENT_TIMESTAMP"
525
+ if node.type == "call_expression" and re.search(r"\.ref\s*\(", txt(node)):
526
+ a = node.child_by_field_name("arguments")
527
+ args = [x for x in (a.named_children if a is not None else [])]
528
+ s = _str(args[0]) if args else None
529
+ return self.ident(s) if s else mark_node(node)
530
+ return o.value(node)
531
+
532
+ def subquery(self, node: Node | None) -> str | None:
533
+ """A builder chain or a builder callback used as a value or a table: `(SELECT ...)`."""
534
+ node = unwrap(node)
535
+ if node is None:
536
+ return None
537
+ if node.type == "call_expression":
538
+ base, steps = spine(node)
539
+ fn = unwrap(node.child_by_field_name("function"))
540
+ start = None
541
+ if base is not None and _handle(txt(base)) and steps and steps[0][0] in STARTS:
542
+ start = steps[0][2]
543
+ elif fn is not None and fn.type in ("identifier", "member_expression") and _handle(txt(fn)):
544
+ start = node
545
+ elif base is not None and base.type == "call_expression" and _handle(txt(unwrap(base.child_by_field_name("function")))):
546
+ start = base
547
+ if start is None:
548
+ return None
549
+ sub = Chain(self.f, start, node, nested=True)
550
+ sql = sub.statement(sub.steps())
551
+ self.level = min(self.level, sub.level)
552
+ self.notes += [n for n in sub.notes if n not in self.notes]
553
+ alias = f" AS {self.q(sub.alias)}" if sub.alias else ""
554
+ return f"({sql}){alias}"
555
+ if node.type in ("arrow_function", "function_expression", "function"):
556
+ sub = Chain(self.f, node, node, nested=True)
557
+ steps = sub.callback_steps(node)
558
+ if steps is None:
559
+ return None
560
+ sql = sub.statement(steps)
561
+ self.level = min(self.level, sub.level)
562
+ return f"({sql})"
563
+ return None
564
+
565
+ def in_list(self, node: Node | None) -> str:
566
+ sub = self.subquery(node)
567
+ if sub is not None:
568
+ return sub[1:-1] if sub.startswith("(") and sub.endswith(")") else sub
569
+ return o.in_list(node)
570
+
571
+ # -- steps ------------------------------------------------------------------------------------------------------
572
+ def steps(self) -> list[tuple[str, list[Node], Node]]:
573
+ """The chain's steps from the base call on, then the later calls on the variable that holds it."""
574
+ base_node, steps = spine(self.top)
575
+ out: list[tuple[str, list[Node], Node]] = []
576
+ fn = unwrap(self.base.child_by_field_name("function"))
577
+ if fn is not None and (fn.type == "identifier" or (fn.type == "member_expression" and txt(fn.child_by_field_name("property")) not in STARTS)):
578
+ a = self.base.child_by_field_name("arguments")
579
+ out.append(("from", [x for x in (a.named_children if a is not None else []) if x.type != "comment"], self.base))
580
+ idx = next((i for i, s in enumerate(steps) if s[2].id == self.base.id), -1)
581
+ out += steps[idx + 1:]
582
+ else:
583
+ idx = next((i for i, s in enumerate(steps) if s[2].id == self.base.id), 0)
584
+ out += steps[idx:]
585
+ if not self.nested:
586
+ out += self.later()
587
+ return out
588
+
589
+ def later(self) -> list[tuple[str, list[Node], Node]]:
590
+ """`const q = knex("t")...; q.where(...); if (x) q.andWhere(...)`: the calls on `q` after the chain."""
591
+ node = self.top
592
+ p = node.parent
593
+ while p is not None and p.type in o.UNWRAP:
594
+ p = p.parent
595
+ if p is None or p.type != "variable_declarator":
596
+ return []
597
+ name = txt(p.child_by_field_name("name"))
598
+ func = next(iter(self.f._scopes(node)), None)
599
+ if func is None or not re.fullmatch(r"[\w$]+", name):
600
+ return []
601
+ out = []
602
+ stack = [func]
603
+ budget = o.SETTINGS["orm_max_chain_statements"] * 50
604
+ found: list[tuple[int, str, list[Node], Node, bool]] = []
605
+ while stack and budget > 0:
606
+ n = stack.pop()
607
+ budget -= 1
608
+ if n.end_byte <= p.end_byte:
609
+ continue
610
+ if n.type == "call_expression":
611
+ base, steps = spine(n)
612
+ if base is not None and base.type == "identifier" and txt(base) == name and steps:
613
+ cond = o._conditional_between(n, func)
614
+ for s in steps:
615
+ found.append((s[2].start_byte, s[0], s[1], s[2], cond))
616
+ continue
617
+ if n is not func and n.type in o.FUNC_TYPES:
618
+ continue
619
+ stack.extend(n.children)
620
+ found.sort(key=lambda x: x[0])
621
+ builder = STARTS | set(JOINS) | {"andWhere", "orWhere", "whereIn", "whereNotIn", "whereNull", "whereNotNull", "whereRaw",
622
+ "whereBetween", "whereLike", "whereILike", "whereExists", "whereNot", "orderBy",
623
+ "groupBy", "having", "limit", "offset", "returning", "onConflict", "merge", "ignore",
624
+ "forUpdate", "modify", "orderByRaw"}
625
+ for _b, sname, args, call, cond in found:
626
+ if sname in NO_OP or sname not in builder:
627
+ continue
628
+ if cond:
629
+ if sname.startswith(("where", "andWhere", "orWhere", "whereIn", "orderBy", "limit", "offset", "join", "leftJoin",
630
+ "select", "groupBy", "having", "orWhere")):
631
+ out.append(("__optional", [call], call))
632
+ continue
633
+ self.lower(1, f"`{name}.{sname}` under a condition")
634
+ continue
635
+ out.append((sname, args, call))
636
+ return out
637
+
638
+ def callback_steps(self, fnode: Node) -> list[tuple[str, list[Node], Node]] | None:
639
+ """The calls a builder callback makes on its parameter (or `this`), in order."""
640
+ params = fnode.child_by_field_name("parameters") or fnode.child_by_field_name("parameter")
641
+ names = {"this"}
642
+ if params is not None:
643
+ first = params.named_children[0] if params.named_children else (params if params.type == "identifier" else None)
644
+ if first is not None:
645
+ names.add(txt(first).split(":")[0].strip())
646
+ body = fnode.child_by_field_name("body")
647
+ if body is None:
648
+ return None
649
+ out: list[tuple[str, list[Node], Node]] = []
650
+ found: list[tuple[int, str, list[Node], Node, bool]] = []
651
+ stack = [body]
652
+ while stack:
653
+ n = stack.pop()
654
+ if n.type == "call_expression":
655
+ base, steps = spine(n)
656
+ if base is not None and txt(base) in names and steps:
657
+ cond = o._conditional_between(n, fnode)
658
+ for s in steps:
659
+ found.append((s[2].start_byte, s[0], s[1], s[2], cond))
660
+ continue
661
+ if n.type in o.FUNC_TYPES:
662
+ continue
663
+ stack.extend(n.children)
664
+ found.sort(key=lambda x: x[0])
665
+ for _b, sname, args, call, cond in found:
666
+ if cond:
667
+ out.append(("__optional", [call], call))
668
+ else:
669
+ out.append((sname, args, call))
670
+ return out
671
+
672
+ # -- where ------------------------------------------------------------------------------------------------------
673
+ def group_from(self, fnode: Node) -> str:
674
+ sub = Chain(self.f, fnode, fnode, nested=True)
675
+ steps = sub.callback_steps(fnode)
676
+ if steps is None:
677
+ self.lower(1, "where callback not read")
678
+ return mark_node(fnode)
679
+ for s in steps:
680
+ sub.apply(s)
681
+ self.level = min(self.level, sub.level)
682
+ self.notes += [n for n in sub.notes if n not in self.notes]
683
+ if sub.joins and not sub.wheres: # join(..., function () { this.on(...) })
684
+ return " ".join(sub.joins)
685
+ return "(" + sub.where_sql(sub.wheres) + ")" if sub.wheres else ""
686
+
687
+ def where_args(self, kind: str, args: list[Node]) -> str:
688
+ """One where predicate from a where / andWhere / orWhere / whereNot call."""
689
+ if not args:
690
+ return ""
691
+ first = unwrap(args[0])
692
+ if len(args) == 1:
693
+ if first.type in ("arrow_function", "function_expression", "function"):
694
+ return self.group_from(first)
695
+ r = self.raw(first)
696
+ if r is not None:
697
+ return r
698
+ obj = o.as_object(self.f, first, self.top)
699
+ if obj is not None:
700
+ preds = []
701
+ for k, v in obj.entries:
702
+ if o.is_undefined(v):
703
+ continue
704
+ lit = o.literal(v)
705
+ uv = unwrap(v)
706
+ if lit == "NULL":
707
+ preds.append(f"{self.ident(k)} IS NULL")
708
+ elif uv is not None and uv.type == "array":
709
+ preds.append(f"{self.ident(k)} IN ({o.in_list(uv)})")
710
+ else:
711
+ preds.append(f"{self.ident(k)} = {self.val(v)}")
712
+ preds += [mark(x) for x in obj.extra] + [mark("optional: " + t) for _k, _v, t in obj.maybe]
713
+ return " AND ".join(preds)
714
+ self.lower(1, "where object built at run time")
715
+ return mark_node(first)
716
+ col = self.name(first)
717
+ if len(args) == 2:
718
+ v = unwrap(args[1])
719
+ if o.literal(v) == "NULL":
720
+ return f"{col} IS NULL"
721
+ return f"{col} = {self.val(v)}"
722
+ op = _str(args[1])
723
+ if op is None:
724
+ return f"{col} {mark_node(args[1])} {self.val(args[2])}"
725
+ op_u = op.strip().upper()
726
+ if op_u in ("IN", "NOT IN"):
727
+ return f"{col} {op_u} ({self.in_list(args[2])})"
728
+ if o.literal(args[2]) == "NULL" and op_u in ("=", "IS", "!=", "<>", "IS NOT"):
729
+ return f"{col} IS {'NOT ' if op_u in ('!=', '<>', 'IS NOT') else ''}NULL"
730
+ if op_u not in ("=", "<>", "!=", "<", ">", "<=", ">=", "LIKE", "ILIKE", "NOT LIKE", "NOT ILIKE", "@>", "<@", "&&", "~",
731
+ "~*", "!~", "IS", "IS NOT", "?", "?|", "?&", "REGEXP", "SIMILAR TO"):
732
+ return mark(f"{txt(args[0])} {op} {txt(args[2])}")
733
+ return f"{col} {op_u} {self.val(args[2])}"
734
+
735
+ def where_call(self, sname: str, args: list[Node]) -> tuple[str, str] | None:
736
+ """(connector, predicate) for a where-family step, or None when the name is not one."""
737
+ conn = "AND"
738
+ name = sname
739
+ if name.startswith("orWhere") or name.startswith("orHaving") or name in ("orOn",):
740
+ conn, name = "OR", "where" + name[len("orWhere"):] if name.startswith("orWhere") else name
741
+ elif name.startswith("andWhere"):
742
+ name = "where" + name[len("andWhere"):]
743
+ negate = False
744
+ if name.startswith("whereNot") and name not in ("whereNotIn", "whereNotNull", "whereNotBetween", "whereNotExists",
745
+ "whereNotLike", "whereNotILike"):
746
+ negate, name = True, "where" + name[len("whereNot"):]
747
+ if name == "where":
748
+ p = self.where_args("where", args)
749
+ elif name in ("whereIn", "whereNotIn"):
750
+ if len(args) < 2:
751
+ return None
752
+ cols = o.array_items(args[0])
753
+ col = ("(" + ", ".join(self.name(c) for c in cols) + ")") if cols is not None else self.name(args[0])
754
+ p = f"{col} {'NOT IN' if name == 'whereNotIn' else 'IN'} ({self.in_list(args[1])})"
755
+ elif name in ("whereNull", "whereNotNull"):
756
+ if not args:
757
+ return None
758
+ p = f"{self.name(args[0])} IS {'NOT ' if name == 'whereNotNull' else ''}NULL"
759
+ elif name in ("whereBetween", "whereNotBetween"):
760
+ if len(args) < 2:
761
+ return None
762
+ items = o.array_items(args[1])
763
+ lo, hi = (self.val(items[0]), self.val(items[1])) if items and len(items) == 2 else (mark_node(args[1]), mark_node(args[1]))
764
+ p = f"{self.name(args[0])} {'NOT ' if name == 'whereNotBetween' else ''}BETWEEN {lo} AND {hi}"
765
+ elif name in ("whereLike", "whereILike", "whereNotLike", "whereNotILike"):
766
+ if len(args) < 2:
767
+ return None
768
+ op = {"whereLike": "LIKE", "whereILike": "ILIKE", "whereNotLike": "NOT LIKE", "whereNotILike": "NOT ILIKE"}[name]
769
+ p = f"{self.name(args[0])} {op} {self.val(args[1])}"
770
+ elif name in ("whereRaw",):
771
+ if not args:
772
+ return None
773
+ p = self.raw_text(args[0], args[1] if len(args) > 1 else None)
774
+ elif name in ("whereExists", "whereNotExists"):
775
+ if not args:
776
+ return None
777
+ sub = self.subquery(args[0])
778
+ p = f"{'NOT ' if name == 'whereNotExists' else ''}EXISTS {sub if sub else '(' + mark_node(args[0]) + ')'}"
779
+ elif name in ("whereColumn",):
780
+ if len(args) == 2:
781
+ p = f"{self.name(args[0])} = {self.name(args[1])}"
782
+ elif len(args) == 3 and _str(args[1]):
783
+ p = f"{self.name(args[0])} {_str(args[1])} {self.name(args[2])}"
784
+ else:
785
+ return None
786
+ elif name.startswith("whereJson"):
787
+ p = mark(f"{sname}({', '.join(txt(a) for a in args)})")
788
+ else:
789
+ return None
790
+ if not p:
791
+ return None
792
+ return conn, ("NOT " + p if negate else p)
793
+
794
+ def where_sql(self, preds: list[tuple[str, str]]) -> str:
795
+ out = ""
796
+ for i, (conn, p) in enumerate(preds):
797
+ out += p if i == 0 else f" {conn} {p}"
798
+ return out
799
+
800
+ # -- one step -------------------------------------------------------------------------------------------------
801
+ def apply(self, step: tuple[str, list[Node], Node]) -> None:
802
+ sname, args, call = step
803
+ if sname == "__optional":
804
+ self.wheres.append(("AND", mark("optional: " + o.norm_expr(txt(args[0]))[:70])))
805
+ self.lower(1, "parts of the chain added under a condition")
806
+ return
807
+ if sname in NO_OP:
808
+ if sname == "as" and args and _str(args[0]):
809
+ self.alias = _str(args[0])
810
+ return
811
+ w = self.where_call(sname, args)
812
+ if w is not None:
813
+ self.wheres.append(w)
814
+ return
815
+ if sname in ("on", "andOn", "orOn", "onIn", "onNull", "onNotNull", "andOnVal", "onVal", "orOnVal"):
816
+ if len(args) >= 2:
817
+ if sname in ("onIn",):
818
+ self.wheres.append(("AND", f"{self.name(args[0])} IN ({self.in_list(args[1])})"))
819
+ elif sname in ("onNull", "onNotNull"):
820
+ self.wheres.append(("AND", f"{self.name(args[0])} IS {'NOT ' if sname == 'onNotNull' else ''}NULL"))
821
+ else:
822
+ right = args[-1]
823
+ op = _str(args[1]) if len(args) == 3 else "="
824
+ rhs = self.val(right) if "Val" in sname else self.name(right)
825
+ self.wheres.append(("OR" if sname.startswith("or") else "AND", f"{self.name(args[0])} {op or '='} {rhs}"))
826
+ return
827
+ if sname in ("from", "table", "into", "queryBuilder"):
828
+ if args:
829
+ self.table_sql = self.table_name(args[0])
830
+ return
831
+ if sname in ("select", "column", "columns", "distinct", "distinctOn", "first", "pluck", "returning", "clearSelect"):
832
+ if sname == "clearSelect":
833
+ self.cols = []
834
+ return
835
+ items: list[Node] = []
836
+ for a in args:
837
+ arr = o.array_items(a)
838
+ items += arr if arr is not None else [a]
839
+ cols = []
840
+ for it in items:
841
+ u = unwrap(it)
842
+ if u is not None and u.type == "object":
843
+ for c in u.named_children:
844
+ if c.type == "pair" and _str(c.child_by_field_name("value")):
845
+ cols.append(f"{self.ident(_str(c.child_by_field_name('value')))} AS {self.q(txt(c.child_by_field_name('key')).strip(chr(39) + chr(34)))}")
846
+ continue
847
+ if u is not None and u.type in ("template_string", "binary_expression"):
848
+ named = self.name(it) # `${Table}.col` or `${Table}.col as alias`: a column, once resolved
849
+ cols.append(named if "«" not in named else self.val(it))
850
+ continue
851
+ cols.append(self.name(it) if _str(it) is not None or (u is not None and u.type in ("identifier", "member_expression")) else self.val(it))
852
+ if sname == "returning":
853
+ self.returning = cols
854
+ return
855
+ if sname == "first":
856
+ self.limit = "1"
857
+ if sname in ("distinct", "distinctOn"):
858
+ self.distinct = True
859
+ self.cols += cols
860
+ return
861
+ if sname in AGG:
862
+ u = unwrap(args[0]) if args else None
863
+ if u is None:
864
+ expr = "*"
865
+ alias = ""
866
+ elif u.type == "object":
867
+ pair = next((c for c in u.named_children if c.type == "pair"), None)
868
+ expr = self.name(pair.child_by_field_name("value")) if pair is not None else "*"
869
+ alias = txt(pair.child_by_field_name("key")).strip("'\"") if pair is not None else ""
870
+ else:
871
+ s = _str(u)
872
+ m = re.match(r"^\s*(.+?)\s+as\s+([\w$]+)\s*$", s or "", re.I)
873
+ expr = self.ident(m.group(1)) if m else (self.ident(s) if s else self.val(u))
874
+ alias = m.group(2) if m else ""
875
+ d = "DISTINCT " if "Distinct" in sname else ""
876
+ self.cols.append(f"{AGG[sname]}({d}{expr})" + (f" AS {self.q(alias)}" if alias else ""))
877
+ return
878
+ if sname in JOINS:
879
+ if not args:
880
+ return
881
+ target = self.table_name_join(args[0])
882
+ kw = JOINS[sname]
883
+ if sname == "crossJoin" or len(args) == 1:
884
+ self.joins.append(f"{kw} {target}")
885
+ return
886
+ u = unwrap(args[1])
887
+ if u is not None and u.type in ("arrow_function", "function_expression", "function"):
888
+ on = self.group_from(u)
889
+ on = on[1:-1] if on.startswith("(") and on.endswith(")") else on
890
+ self.joins.append(f"{kw} {target} ON {on}" if on else f"{kw} {target}")
891
+ return
892
+ if len(args) == 2:
893
+ self.joins.append(f"{kw} {target} ON {self.name(args[1])}")
894
+ elif len(args) == 3:
895
+ self.joins.append(f"{kw} {target} ON {self.name(args[1])} = {self.name(args[2])}")
896
+ else:
897
+ self.joins.append(f"{kw} {target} ON {self.name(args[1])} {_str(args[2]) or '='} {self.name(args[3])}")
898
+ return
899
+ if sname in ("joinRaw",):
900
+ if args:
901
+ self.joins.append(self.raw_text(args[0], args[1] if len(args) > 1 else None))
902
+ return
903
+ if sname in ("orderBy", "orderByRaw"):
904
+ if not args:
905
+ return
906
+ if sname == "orderByRaw":
907
+ self.order.append(self.raw_text(args[0], args[1] if len(args) > 1 else None))
908
+ return
909
+ arr = o.array_items(args[0])
910
+ if arr is not None:
911
+ for it in arr:
912
+ obj = o.as_object(self.f, it, self.top) if unwrap(it).type == "object" else None
913
+ if obj is not None:
914
+ d = _str(obj.get("order"))
915
+ self.order.append(self.name(obj.get("column")) + (f" {d.upper()}" if d else ""))
916
+ else:
917
+ self.order.append(self.name(it))
918
+ return
919
+ d = _str(args[1]) if len(args) > 1 else None
920
+ if len(args) > 1 and d is None:
921
+ self.order.append(f"{self.name(args[0])} {mark_node(args[1])}")
922
+ self.lower(1, "sort direction chosen at run time")
923
+ return
924
+ self.order.append(self.name(args[0]) + (f" {d.upper()}" if d else ""))
925
+ return
926
+ if sname in ("groupBy", "groupByRaw"):
927
+ if sname == "groupByRaw" and args:
928
+ self.group.append(self.raw_text(args[0], args[1] if len(args) > 1 else None))
929
+ return
930
+ for a in args:
931
+ arr = o.array_items(a)
932
+ self.group += [self.name(x) for x in (arr if arr is not None else [a])]
933
+ return
934
+ if sname in ("having", "orHaving", "havingRaw", "andHaving", "havingIn", "havingNull", "havingNotNull"):
935
+ if sname == "havingRaw" and args:
936
+ self.having.append(("AND", self.raw_text(args[0], args[1] if len(args) > 1 else None)))
937
+ elif sname == "havingIn" and len(args) == 2:
938
+ self.having.append(("AND", f"{self.name(args[0])} IN ({self.in_list(args[1])})"))
939
+ elif sname in ("havingNull", "havingNotNull") and args:
940
+ self.having.append(("AND", f"{self.name(args[0])} IS {'NOT ' if 'Not' in sname else ''}NULL"))
941
+ elif len(args) == 3:
942
+ col = self.name(args[0]) if _str(args[0]) is not None else self.val(args[0])
943
+ self.having.append(("OR" if sname == "orHaving" else "AND", f"{col} {_str(args[1]) or '='} {self.val(args[2])}"))
944
+ elif len(args) == 2:
945
+ self.having.append(("AND", f"{self.name(args[0])} = {self.val(args[1])}"))
946
+ return
947
+ if sname == "limit":
948
+ self.limit = self.val(args[0]) if args else None
949
+ return
950
+ if sname == "offset":
951
+ self.offset = self.val(args[0]) if args else None
952
+ return
953
+ if sname in ("insert", "upsert"):
954
+ self.op = "insert"
955
+ if args:
956
+ self.insert_values(args[0])
957
+ if len(args) > 1:
958
+ r = o.array_items(args[1])
959
+ self.returning = [self.name(x) for x in (r if r is not None else [args[1]])]
960
+ if sname == "upsert":
961
+ self.conflict = " ON CONFLICT DO UPDATE"
962
+ return
963
+ if sname == "update":
964
+ self.op = "update"
965
+ if len(args) >= 2 and _str(args[0]) is not None:
966
+ self.sets.append(f"{self.ident(_str(args[0]))} = {self.val(args[1])}")
967
+ return
968
+ if args:
969
+ obj = o.as_object(self.f, args[0], self.top)
970
+ if obj is None:
971
+ self.lower(1, "columns set at run time")
972
+ self.sets.append(f"{mark_node(args[0])} = {mark('values')}")
973
+ else:
974
+ self.sets += [f"{self.ident(k)} = {self.val(v)}" for k, v in obj.entries if not o.is_undefined(v)]
975
+ if obj.extra or obj.maybe:
976
+ self.lower(1, "columns set under a condition")
977
+ self.sets += [f"{mark(k)} = {mark(t)}" for k, _v, t in obj.maybe]
978
+ if len(args) > 1:
979
+ r = o.array_items(args[1])
980
+ self.returning = [self.name(x) for x in (r if r is not None else [args[1]])]
981
+ return
982
+ if sname in ("del", "delete"):
983
+ self.op = "delete"
984
+ if args:
985
+ r = o.array_items(args[0])
986
+ self.returning = [self.name(x) for x in (r if r is not None else [args[0]])]
987
+ return
988
+ if sname in ("increment", "decrement"):
989
+ self.op = "update"
990
+ sign = "+" if sname == "increment" else "-"
991
+ if args and unwrap(args[0]).type == "object":
992
+ obj = o.as_object(self.f, args[0], self.top)
993
+ for k, v in (obj.entries if obj else []):
994
+ self.sets.append(f"{self.ident(k)} = {self.ident(k)} {sign} {self.val(v)}")
995
+ elif args:
996
+ c = self.name(args[0])
997
+ self.sets.append(f"{c} = {c} {sign} {self.val(args[1]) if len(args) > 1 else '1'}")
998
+ return
999
+ if sname == "onConflict":
1000
+ items = o.array_items(args[0]) if args else None
1001
+ cols = [self.name(x) for x in (items if items is not None else args)]
1002
+ self.conflict = f" ON CONFLICT ({', '.join(cols)})" if cols else " ON CONFLICT"
1003
+ return
1004
+ if sname == "merge":
1005
+ cols = []
1006
+ if args:
1007
+ items = o.array_items(args[0])
1008
+ if items is not None:
1009
+ cols = [self.name(x) for x in items]
1010
+ else:
1011
+ obj = o.as_object(self.f, args[0], self.top)
1012
+ if obj is not None:
1013
+ self.conflict += " DO UPDATE SET " + ", ".join(f"{self.ident(k)} = {self.val(v)}" for k, v in obj.entries)
1014
+ return
1015
+ if not cols and self.values:
1016
+ cols = self.values[0][0]
1017
+ self.conflict += " DO UPDATE SET " + ", ".join(f"{c} = EXCLUDED.{c}" for c in cols) if cols else " DO UPDATE SET " + mark("merged columns") + " = " + mark("values")
1018
+ return
1019
+ if sname == "ignore":
1020
+ self.conflict += " DO NOTHING"
1021
+ return
1022
+ if sname in ("forUpdate", "forShare", "forNoKeyUpdate", "forKeyShare"):
1023
+ self.lock = {"forUpdate": " FOR UPDATE", "forShare": " FOR SHARE", "forNoKeyUpdate": " FOR NO KEY UPDATE",
1024
+ "forKeyShare": " FOR KEY SHARE"}[sname]
1025
+ return
1026
+ if sname in ("with", "withRecursive", "withMaterialized"):
1027
+ if len(args) >= 2 and _str(args[0]):
1028
+ sub = self.subquery(args[-1])
1029
+ if sub is None:
1030
+ r = self.raw(args[-1])
1031
+ sub = f"({r})" if r else f"({mark_node(args[-1])})"
1032
+ self.ctes.append(f"{self.q(_str(args[0]))} AS {sub}")
1033
+ return
1034
+ if sname == "truncate":
1035
+ self.op = "truncate"
1036
+ return
1037
+ if sname in ("modify", "union", "unionAll", "intersect", "except", "fromRaw"):
1038
+ if sname == "fromRaw" and args:
1039
+ self.table_sql = self.raw_text(args[0], args[1] if len(args) > 1 else None)
1040
+ return
1041
+ self.wheres.append(("AND", mark(f"{sname}: " + ", ".join(o.norm_expr(txt(a)) for a in args)[:70])))
1042
+ self.lower(1, f"`{sname}` adds parts known at run time")
1043
+ return
1044
+ if sname in ("raw",):
1045
+ raise Skip("knex.raw statement: read by the string extractor")
1046
+ self.lower(1, f"`{sname}` not translated")
1047
+
1048
+ def table_name_join(self, node: Node | None) -> str:
1049
+ keep = self.table
1050
+ got = self.table_name(node)
1051
+ self.table = keep or self.table
1052
+ return got
1053
+
1054
+ def insert_values(self, node: Node) -> None:
1055
+ node = unwrap(node)
1056
+ items = o.array_items(node)
1057
+ rows = items if items is not None else [node]
1058
+ if items is not None and not items:
1059
+ return
1060
+ if items is not None and len(items) > 1:
1061
+ self.notes.append(f"{len(items)} rows")
1062
+ obj = o.as_object(self.f, rows[0], self.top)
1063
+ if obj is None:
1064
+ self.lower(0, "row object built at run time: columns not known")
1065
+ self.values.append(([mark(txt(node) + " columns")], [mark(txt(node))]))
1066
+ return
1067
+ cols = [self.ident(k) for k, v in obj.entries if not o.is_undefined(v)]
1068
+ vals = [self.val(v) for k, v in obj.entries if not o.is_undefined(v)]
1069
+ if obj.extra or obj.maybe:
1070
+ self.lower(1, "columns added at run time: " + ", ".join(list(obj.extra) + [k for k, _v, _t in obj.maybe])[:60])
1071
+ self.values.append((cols, vals))
1072
+
1073
+ # -- the statement ------------------------------------------------------------------------------------------------
1074
+ def statement(self, steps: list[tuple[str, list[Node], Node]]) -> str:
1075
+ for s in steps:
1076
+ self.apply(s)
1077
+ table = self.table_sql or ""
1078
+ if not table:
1079
+ raise Skip("no table in the chain")
1080
+ with_ = ("WITH " + ", ".join(self.ctes) + " ") if self.ctes else ""
1081
+ where = (" WHERE " + self.where_sql(self.wheres)) if self.wheres else ""
1082
+ ret = (" RETURNING " + ", ".join(self.returning)) if self.returning and self.engine in ("postgres", "", "sqlite") else ""
1083
+ if self.op == "insert":
1084
+ if not self.values:
1085
+ raise Skip("insert without values")
1086
+ cols, vals = self.values[0]
1087
+ return f"{with_}INSERT INTO {table} ({', '.join(cols)}) VALUES ({', '.join(vals)}){self.conflict}{ret}"
1088
+ if self.op == "update":
1089
+ if not self.sets:
1090
+ raise Skip("update without values")
1091
+ return f"{with_}UPDATE {table} SET {', '.join(self.sets)}{where}{ret}"
1092
+ if self.op == "delete":
1093
+ return f"{with_}DELETE FROM {table}{where}{ret}"
1094
+ if self.op == "truncate":
1095
+ return f"TRUNCATE {table}"
1096
+ sql = f"{with_}SELECT {'DISTINCT ' if self.distinct else ''}{', '.join(self.cols) or '*'} FROM {table}"
1097
+ if self.joins:
1098
+ sql += " " + " ".join(self.joins)
1099
+ sql += where
1100
+ if self.group:
1101
+ sql += " GROUP BY " + ", ".join(self.group)
1102
+ if self.having:
1103
+ sql += " HAVING " + self.where_sql(self.having)
1104
+ if self.order:
1105
+ sql += " ORDER BY " + ", ".join(self.order)
1106
+ if self.limit is not None:
1107
+ sql += f" LIMIT {self.limit}"
1108
+ if self.offset is not None:
1109
+ sql += f" OFFSET {self.offset}"
1110
+ return sql + self.lock
1111
+
1112
+ def run(self) -> list:
1113
+ sql = self.statement(self.steps())
1114
+ fn = unwrap(self.base.child_by_field_name("function"))
1115
+ sink = txt(fn) if fn is not None else "knex"
1116
+ return [_site(self.f, self.top, sink, self.engine, sql, table=self.table, operation=self.op, level=self.level,
1117
+ notes=self.notes)]