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,1266 @@
1
+ """Peewee calls as SQL sites.
2
+
3
+ Models are the project's classes whose bases reach `peewee.Model` (or a playhouse model). Each function body is
4
+ walked once, in order, keeping what local names hold: a model class, a field of one, or a query (the model plus the
5
+ chained `select / where / join / order_by / limit / offset / ...`). A site is written where peewee sends a statement:
6
+
7
+ - a terminal call: `execute()`, `get()`, `get_or_none()`, `first()`, `scalar()`, `count()`, `exists()`;
8
+ - model shortcuts: `Model.get(...)`, `get_by_id`, `get_or_none`, `create`, `get_or_create`, `delete_by_id`,
9
+ `bulk_create`, `raw("...")`;
10
+ - a select that is iterated, measured or listed (`for`, `list()`, `len()`, `.iterator()` then consumed), and a select
11
+ handed to other code (returned, passed on, stored), once.
12
+
13
+ Peewee's operators (`==`, `<<` IN, `>>` IS, `%` LIKE, `**` ILIKE, `&`, `|`, `~`) and field methods (`in_`,
14
+ `not_in`, `is_null`, `contains`, `startswith`, `endswith`, `between`) are written as SQL; a value only known at run
15
+ time is a «run-time part»; a predicate, column list or clause that is built elsewhere (a list of clauses reduced at
16
+ run time, a clause added under an `if`) is a «run-time part» in its place, never a guess. Tables and columns come
17
+ from the model classes (`class Meta: table_name`, the legacy lower-case class name otherwise, `column_name=`,
18
+ `ForeignKeyField` as `<name>_id`), which are also returned as table definitions.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import ast
24
+ import os
25
+ import re
26
+ from pathlib import Path
27
+
28
+ from .orm_py import SETTINGS, Cls, Emitter, Mod, Project, Stats, const, dotted, kwarg, marker, sql_literal, src, str_const
29
+
30
+ LIBRARY = "peewee"
31
+ PEEWEE_MODULES = ("peewee", "playhouse")
32
+ # Database classes and the engine they speak
33
+ DATABASES = {
34
+ "SqliteDatabase": "sqlite", "SqliteExtDatabase": "sqlite", "SqliteQueueDatabase": "sqlite", "CSqliteExtDatabase": "sqlite",
35
+ "APSWDatabase": "sqlite", "SqlCipherDatabase": "sqlite", "PooledSqliteDatabase": "sqlite", "PooledSqliteExtDatabase": "sqlite",
36
+ "PostgresqlDatabase": "postgres", "PostgresqlExtDatabase": "postgres", "PooledPostgresqlDatabase": "postgres",
37
+ "PooledPostgresqlExtDatabase": "postgres", "CockroachDatabase": "postgres", "Psycopg3Database": "postgres",
38
+ "MySQLDatabase": "mysql", "PooledMySQLDatabase": "mysql", "MySQLConnectorDatabase": "mysql", "MariaDBConnectorDatabase": "mysql",
39
+ }
40
+ FIELD_TYPES = {
41
+ "AutoField": "INTEGER", "BigAutoField": "BIGINT", "IdentityField": "INTEGER", "PrimaryKeyField": "INTEGER",
42
+ "IntegerField": "INTEGER", "BigIntegerField": "BIGINT", "SmallIntegerField": "SMALLINT", "BitField": "BIGINT",
43
+ "FloatField": "REAL", "DoubleField": "DOUBLE PRECISION", "DecimalField": "NUMERIC", "BooleanField": "BOOLEAN",
44
+ "CharField": "VARCHAR", "FixedCharField": "CHAR", "TextField": "TEXT", "UUIDField": "UUID", "BinaryUUIDField": "BLOB",
45
+ "DateTimeField": "TIMESTAMP", "DateField": "DATE", "TimeField": "TIME", "TimestampField": "INTEGER",
46
+ "BlobField": "BLOB", "BareField": "TEXT", "IPField": "BIGINT", "JSONField": "JSON", "BinaryJSONField": "JSONB",
47
+ "HStoreField": "HSTORE", "ArrayField": "TEXT", "TSVectorField": "TSVECTOR", "IntervalField": "INTERVAL",
48
+ "DateTimeTZField": "TIMESTAMPTZ", "SearchField": "TEXT", "RowIDField": "INTEGER", "DocIDField": "INTEGER",
49
+ }
50
+ CONSUMERS = {"list", "tuple", "set", "frozenset", "sorted", "len", "sum", "any", "all", "dict", "next", "enumerate", "iter",
51
+ "reversed", "max", "min"}
52
+ PASS = {"dicts", "tuples", "namedtuples", "objects", "naive", "iterator", "alias", "returning", "bind", "with_cte", "clone"}
53
+ OPS = {ast.Eq: "=", ast.NotEq: "!=", ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">="}
54
+ _SIMPLE = re.compile(r"[a-z_][a-z0-9_]*")
55
+
56
+
57
+ # names peewee would quote that a bare identifier cannot be in some engine
58
+ _RESERVED = {"user", "order", "group", "select", "from", "where", "table", "column", "index", "key", "check", "default",
59
+ "limit", "offset", "end", "desc", "asc", "primary", "references", "role", "type", "values", "value", "case"}
60
+
61
+
62
+ def q(name: str) -> str:
63
+ return name if _SIMPLE.fullmatch(name) and name not in _RESERVED else '"' + name.replace('"', '""') + '"'
64
+
65
+
66
+ # ---- models -----------------------------------------------------------------------------------------------------
67
+ class PField:
68
+ __slots__ = ("name", "column", "kind", "target", "type", "pk", "line")
69
+
70
+ def __init__(self, name, column, kind="col", target=None, type_="", pk=False, line=0):
71
+ self.name, self.column, self.kind, self.target, self.type, self.pk, self.line = name, column, kind, target, type_, pk, line
72
+
73
+
74
+ class PModel:
75
+ def __init__(self, cls: Cls):
76
+ self.cls, self.name = cls, cls.name
77
+ self.table = ""
78
+ self.fields: dict[str, PField] = {}
79
+ self.pk: list[str] = []
80
+ self.temporary = False
81
+ self.abstract_like = False
82
+
83
+ @property
84
+ def label(self) -> str:
85
+ return self.name
86
+
87
+ @property
88
+ def where(self) -> str:
89
+ return f"{self.cls.mod.rel}:{self.cls.node.lineno}"
90
+
91
+ def col(self, name: str) -> str | None:
92
+ f = self.fields.get(name)
93
+ if f is not None:
94
+ return f.column
95
+ for f in self.fields.values(): # `Model.review_segment_id`: the id name of a foreign key
96
+ if f.kind == "fk" and f.column == name:
97
+ return f.column
98
+ return None
99
+
100
+ def columns(self) -> list[str]:
101
+ return [f.column for f in self.fields.values()]
102
+
103
+
104
+ def _snake(name: str) -> str:
105
+ return re.sub(r"(?<=[a-z0-9])([A-Z])|(?<=[A-Z])([A-Z][a-z])", r"_\1\2", name).lower()
106
+
107
+
108
+ class Index:
109
+ def __init__(self, project: Project):
110
+ self.project = project
111
+ self.models: dict[int, PModel] = {} # id(Cls) -> model
112
+ self.by_name: dict[str, list[PModel]] = {}
113
+ self.engines: set[str] = set()
114
+ self.files: set[str] = set() # modules that import peewee or playhouse
115
+ for mod in project.mods.values():
116
+ if any((module or "").split(".")[0] in PEEWEE_MODULES for _, module, _ in mod.imports.values()):
117
+ self.files.add(mod.rel)
118
+ for node in ast.walk(mod.tree):
119
+ if isinstance(node, ast.Call):
120
+ last = (dotted(node.func) or "").split(".")[-1]
121
+ if last in DATABASES:
122
+ self.engines.add(DATABASES[last])
123
+ if not self.files:
124
+ return
125
+ for mod in project.mods.values():
126
+ for cls in _classes(mod):
127
+ if self._is_model(cls):
128
+ self.models[id(cls)] = PModel(cls)
129
+ for m in self.models.values():
130
+ self._read(m)
131
+ for m in self.models.values():
132
+ self.by_name.setdefault(m.name, []).append(m)
133
+
134
+ @property
135
+ def engine(self) -> str:
136
+ return next(iter(self.engines)) if len(self.engines) == 1 else ""
137
+
138
+ def _is_model(self, cls: Cls) -> bool:
139
+ for ext in self.project.external_bases(cls):
140
+ if ext.split(".")[0] in PEEWEE_MODULES and ext.split(".")[-1].endswith("Model"):
141
+ return True
142
+ return False
143
+
144
+ def model_of(self, cls: Cls | None) -> PModel | None:
145
+ return self.models.get(id(cls)) if cls is not None else None
146
+
147
+ def _meta(self, m: PModel, key: str, inherit: bool = True):
148
+ for c in (self.project.mro(m.cls) if inherit else [m.cls]):
149
+ meta = c.inner.get("Meta")
150
+ if meta is not None and key in meta.assigns:
151
+ return True, meta.assigns[key]
152
+ return False, None
153
+
154
+ def _read(self, m: PModel) -> None:
155
+ ok, tn = self._meta(m, "table_name", inherit=False)
156
+ if not ok:
157
+ ok, tn = self._meta(m, "db_table", inherit=False)
158
+ name = str_const(tn) if ok else None
159
+ if name is None:
160
+ ok2, legacy = self._meta(m, "legacy_table_names")
161
+ if ok2 and const(legacy) == (True, False):
162
+ name = _snake(m.name)
163
+ else:
164
+ name = re.sub(r"[^\w]+", "_", m.name.lower())
165
+ m.table = name
166
+ ok, tmp = self._meta(m, "temporary", inherit=False)
167
+ m.temporary = ok and const(tmp) == (True, True)
168
+ # fields: nearest class wins, bases first in column order
169
+ chain = [c for c in reversed(self.project.mro(m.cls)) if id(c) in self.models or c is m.cls or self._has_fields(c)]
170
+ pk_set = False
171
+ for c in chain:
172
+ for st in c.node.body:
173
+ if not isinstance(st, ast.Assign) or len(st.targets) != 1 or not isinstance(st.targets[0], ast.Name):
174
+ continue
175
+ call = st.value
176
+ if not isinstance(call, ast.Call):
177
+ continue
178
+ ftype = (dotted(call.func) or "").split(".")[-1]
179
+ if not ftype.endswith("Field") and ftype not in ("CompositeKey",):
180
+ continue
181
+ fname = st.targets[0].id
182
+ column = str_const(kwarg(call, "column_name")) or str_const(kwarg(call, "db_column"))
183
+ kind, target = "col", None
184
+ if ftype in ("ForeignKeyField", "DeferredForeignKey"):
185
+ kind = "fk"
186
+ tnode = call.args[0] if call.args else kwarg(call, "model")
187
+ target = str_const(tnode) or dotted(tnode) or ""
188
+ if target == "self":
189
+ target = m.name
190
+ column = column or (fname if fname.endswith("_id") else fname + "_id")
191
+ ftype_sql = ""
192
+ elif ftype == "ManyToManyField":
193
+ continue # a through table peewee writes itself
194
+ else:
195
+ ftype_sql = FIELD_TYPES.get(ftype, "TEXT")
196
+ if ftype in ("CharField", "FixedCharField"):
197
+ ok_n, n = const(kwarg(call, "max_length"))
198
+ ftype_sql += f"({n if ok_n and isinstance(n, int) else 255})"
199
+ is_pk = const(kwarg(call, "primary_key")) == (True, True) or ftype in ("AutoField", "BigAutoField", "PrimaryKeyField", "IdentityField")
200
+ m.fields[fname] = PField(fname, column or fname, kind, target, ftype_sql, is_pk, st.lineno)
201
+ if is_pk:
202
+ m.pk = [column or fname]
203
+ pk_set = True
204
+ ok, pk = self._meta(m, "primary_key")
205
+ if ok:
206
+ if isinstance(pk, ast.Call) and (dotted(pk.func) or "").endswith("CompositeKey"):
207
+ names = [str_const(a) for a in pk.args]
208
+ m.pk = [m.col(n) or n for n in names if n]
209
+ pk_set = True
210
+ elif const(pk) == (True, False):
211
+ m.pk, pk_set = [], True
212
+ if not pk_set and "id" not in m.fields:
213
+ # peewee adds an auto-incrementing `id` unless a field says primary_key=True
214
+ m.fields = {"id": PField("id", "id", "col", None, "INTEGER", True), **m.fields}
215
+ m.pk = ["id"]
216
+ elif not pk_set and "id" in m.fields:
217
+ m.pk = [m.fields["id"].column]
218
+
219
+ @staticmethod
220
+ def _has_fields(c: Cls) -> bool:
221
+ return any(isinstance(v, ast.Call) and (dotted(v.func) or "").endswith("Field") for v in c.assigns.values())
222
+
223
+ def target(self, m: PModel, f: PField) -> PModel | None:
224
+ if f.target is None:
225
+ return None
226
+ name = f.target.split(".")[-1]
227
+ cands = self.by_name.get(name) or []
228
+ if len(cands) == 1:
229
+ return cands[0]
230
+ for c in cands:
231
+ if c.cls.mod is m.cls.mod:
232
+ return c
233
+ return None
234
+
235
+ def tables(self) -> list:
236
+ from .orm_django_models import OrmTable
237
+ out = []
238
+ seen: set[str] = set()
239
+ for m in self.models.values():
240
+ if m.temporary or not m.table or m.table in seen or not m.fields:
241
+ continue
242
+ # a base class with no table of its own: no model of the project subclasses it as a base of nothing else,
243
+ # but it is still a table peewee would create; keep it unless it has no field besides the implicit id
244
+ if len(m.fields) == 1 and "id" in m.fields and any(id(c) != id(m.cls) and m.cls in self.project.mro(c)
245
+ for c in (x.cls for x in self.models.values())):
246
+ continue
247
+ seen.add(m.table)
248
+ t = OrmTable(name=m.table, defined_at=[m.where], name_basis="orm")
249
+ cols = []
250
+ for f in m.fields.values():
251
+ typ = f.type
252
+ if f.kind == "fk":
253
+ tgt = self.target(m, f)
254
+ pkf = tgt.fields.get(tgt.pk[0]) if tgt is not None and len(tgt.pk) == 1 else None
255
+ if pkf is None and tgt is not None and len(tgt.pk) == 1:
256
+ pkf = next((x for x in tgt.fields.values() if x.column == tgt.pk[0]), None)
257
+ typ = (pkf.type if pkf is not None else "") or "INTEGER"
258
+ cols.append({"name": f.column, "type": typ})
259
+ t.columns = cols
260
+ t.primary_key = ", ".join(m.pk)
261
+ t.indexes = [{"name": "", "columns": list(m.pk), "unique": True, "primary": True}] if m.pk else []
262
+ t.orm = {"library": LIBRARY, "model": m.label}
263
+ out.append(t)
264
+ return out
265
+
266
+
267
+ def _classes(mod: Mod):
268
+ stack = list(mod.classes.values())
269
+ while stack:
270
+ c = stack.pop()
271
+ yield c
272
+ stack.extend(c.inner.values())
273
+
274
+
275
+ # ---- values -----------------------------------------------------------------------------------------------------
276
+ class MRef:
277
+ __slots__ = ("model",)
278
+
279
+ def __init__(self, model: PModel):
280
+ self.model = model
281
+
282
+
283
+ class FRef:
284
+ """A column expression: `Model.field`, `fn.COUNT(...)`, an arithmetic of those."""
285
+ __slots__ = ("sql", "model")
286
+
287
+ def __init__(self, sql: str, model: PModel | None = None):
288
+ self.sql, self.model = sql, model
289
+
290
+
291
+ class Query:
292
+ __slots__ = ("model", "kind", "cols", "where", "joins", "order", "limit", "offset", "group", "having", "distinct",
293
+ "sets", "ins_cols", "ins_vals", "conflict", "notes", "conf", "root", "ctx", "node")
294
+
295
+ def __init__(self, model: PModel, kind: str, node: ast.AST):
296
+ self.model, self.kind, self.node = model, kind, node
297
+ self.cols: list[str] | None = None
298
+ self.where: list[str] = []
299
+ self.joins: list[str] = []
300
+ self.order: list[str] = []
301
+ self.limit: str | None = None
302
+ self.offset: str | None = None
303
+ self.group: list[str] = []
304
+ self.having: list[str] = []
305
+ self.distinct = False
306
+ self.sets: list[tuple[str, str]] = []
307
+ self.ins_cols: list[str] = []
308
+ self.ins_vals: list[str] = []
309
+ self.conflict = ""
310
+ self.notes: list[str] = []
311
+ self.conf = 0
312
+ self.root = {"emitted": False, "node": node, "last": None}
313
+ self.ctx = model
314
+
315
+ def copy(self) -> "Query":
316
+ n = Query.__new__(Query)
317
+ for k in Query.__slots__:
318
+ v = getattr(self, k)
319
+ setattr(n, k, list(v) if isinstance(v, list) else v)
320
+ n.root["last"] = n
321
+ return n
322
+
323
+
324
+ CONF = ("high", "medium", "low")
325
+
326
+
327
+ # ---- the walker -------------------------------------------------------------------------------------------------
328
+ class Walker:
329
+ def __init__(self, pw: "Peewee", mod: Mod, cls: Cls | None, symbol: str, env: dict | None = None):
330
+ self.pw, self.mod, self.cls, self.symbol = pw, mod, cls, symbol
331
+ self.env: dict = dict(env or {})
332
+ self.loop = 0
333
+ self.cond = 0
334
+ self.roots: list[dict] = []
335
+ self.nested: list[tuple] = []
336
+
337
+ # statements
338
+ def run(self, body: list) -> None:
339
+ for st in body:
340
+ self.stmt(st)
341
+
342
+ def stmt(self, st: ast.stmt) -> None:
343
+ if isinstance(st, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
344
+ self.nested.append(st)
345
+ return
346
+ if isinstance(st, ast.Assign):
347
+ v = self.ev(st.value)
348
+ for t in st.targets:
349
+ self.bind(t, v, st.value)
350
+ elif isinstance(st, ast.AnnAssign):
351
+ if st.value is not None:
352
+ self.bind(st.target, self.ev(st.value), st.value)
353
+ elif isinstance(st, ast.AugAssign):
354
+ self.ev(st.value)
355
+ elif isinstance(st, ast.Expr):
356
+ self.ev(st.value)
357
+ elif isinstance(st, ast.Return):
358
+ if st.value is not None:
359
+ self.handed(self.ev(st.value))
360
+ elif isinstance(st, (ast.For, ast.AsyncFor)):
361
+ it = self.ev(st.iter)
362
+ self.consume(st.iter, it)
363
+ self.loop += 1
364
+ self.run(st.body)
365
+ self.loop -= 1
366
+ self.run(st.orelse)
367
+ elif isinstance(st, ast.While):
368
+ self.ev(st.test)
369
+ self.loop += 1
370
+ self.run(st.body)
371
+ self.loop -= 1
372
+ self.run(st.orelse)
373
+ elif isinstance(st, ast.If):
374
+ self.ev(st.test)
375
+ self.cond += 1
376
+ self.run(st.body)
377
+ self.run(st.orelse)
378
+ self.cond -= 1
379
+ elif isinstance(st, (ast.With, ast.AsyncWith)):
380
+ for item in st.items:
381
+ self.ev(item.context_expr)
382
+ self.run(st.body)
383
+ elif isinstance(st, ast.Try) or type(st).__name__ == "TryStar":
384
+ self.run(st.body)
385
+ for h in st.handlers:
386
+ self.run(h.body)
387
+ self.run(st.orelse)
388
+ self.run(st.finalbody)
389
+ elif isinstance(st, ast.Match):
390
+ self.ev(st.subject)
391
+ self.cond += 1
392
+ for c in st.cases:
393
+ self.run(c.body)
394
+ self.cond -= 1
395
+ else:
396
+ for node in ast.iter_child_nodes(st):
397
+ if isinstance(node, ast.expr):
398
+ self.ev(node)
399
+
400
+ def bind(self, target: ast.AST, v, value_node) -> None:
401
+ if isinstance(target, ast.Name):
402
+ old = self.env.get(target.id)
403
+ if isinstance(v, Query) and self.cond and isinstance(old, Query) and old.root is v.root and v is not old:
404
+ # `query = query.where(...)` under a condition: what it adds may or may not be there
405
+ v = self._optional(old, v, value_node)
406
+ self.env[target.id] = v
407
+ elif isinstance(target, (ast.Tuple, ast.List)):
408
+ for t in target.elts:
409
+ self.bind(t, None, None)
410
+ else:
411
+ self.handed(v) # stored on an object or in a container: runs elsewhere
412
+
413
+ def _optional(self, old: Query, new: Query, node) -> Query:
414
+ out = new.copy()
415
+ for key in ("where", "order", "joins", "group", "having"):
416
+ a, b = getattr(old, key), getattr(new, key)
417
+ if len(b) > len(a):
418
+ added = b[len(a):]
419
+ if key == "where":
420
+ setattr(out, key, a + [marker("optional: " + " AND ".join(added).replace("«", "").replace("»", ""))])
421
+ else:
422
+ setattr(out, key, list(a))
423
+ out.notes.append(f"{key} added on some run-time condition: " + ", ".join(added))
424
+ if new.limit != old.limit and new.limit is not None:
425
+ out.notes.append("limit set on some run-time condition")
426
+ out.conf = max(out.conf, 1)
427
+ out.notes.append("part of the query is added only on some run-time condition")
428
+ return out
429
+
430
+ # values
431
+ def ev(self, node: ast.AST | None):
432
+ if node is None:
433
+ return None
434
+ if isinstance(node, ast.Name):
435
+ if node.id in self.env:
436
+ return self.env[node.id]
437
+ if node.id == "cls" and self.cls is not None:
438
+ m = self.pw.index.model_of(self.cls)
439
+ if m is not None:
440
+ return MRef(m)
441
+ return self.global_name(node.id)
442
+ if isinstance(node, ast.Attribute):
443
+ base = self.ev(node.value)
444
+ if isinstance(base, MRef):
445
+ col = base.model.col(node.attr)
446
+ if col is not None:
447
+ return FRef(f"{q(base.model.table)}.{q(col)}", base.model)
448
+ return None
449
+ if base is None and isinstance(node.value, ast.Name) and node.value.id not in self.env:
450
+ got = self.global_name(dotted(node) or "")
451
+ if got is not None:
452
+ return got
453
+ return None
454
+ if isinstance(node, ast.Call):
455
+ return self.ev_call(node)
456
+ if isinstance(node, (ast.Tuple, ast.List, ast.Set)):
457
+ vals = [self.ev(e) for e in node.elts]
458
+ for e, v in zip(node.elts, vals):
459
+ if isinstance(v, Query):
460
+ self.handed(v)
461
+ return None
462
+ if isinstance(node, ast.Subscript):
463
+ base = self.ev(node.value)
464
+ self.ev(node.slice)
465
+ if isinstance(base, Query) and base.kind == "select":
466
+ ok, idx = const(node.slice)
467
+ qq = base.copy()
468
+ if ok and isinstance(idx, int):
469
+ qq.limit, qq.offset = "1", str(idx) if idx else qq.offset
470
+ self.emit_query(node, qq, "select")
471
+ if isinstance(base, MRef): # Model[pk]
472
+ self.by_pk(node, base.model, node.slice, "get")
473
+ return None
474
+ if isinstance(node, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):
475
+ for g in node.generators:
476
+ it = self.ev(g.iter)
477
+ self.consume(g.iter, it)
478
+ self.loop += 1
479
+ for child in ([node.key, node.value] if isinstance(node, ast.DictComp) else [node.elt]):
480
+ self.ev(child)
481
+ self.loop -= 1
482
+ return None
483
+ if isinstance(node, ast.Await):
484
+ return self.ev(node.value)
485
+ for child in ast.iter_child_nodes(node):
486
+ if isinstance(child, ast.expr):
487
+ v = self.ev(child)
488
+ if isinstance(v, Query) and not isinstance(node, (ast.BoolOp, ast.IfExp)):
489
+ self.handed(v)
490
+ return None
491
+
492
+ def global_name(self, name: str):
493
+ if not name:
494
+ return None
495
+ cls = self.pw.project.resolve_class(self.mod, name)
496
+ m = self.pw.index.model_of(cls)
497
+ return MRef(m) if m is not None else None
498
+
499
+ def consume(self, node: ast.AST, v) -> None:
500
+ if isinstance(v, Query) and v.kind == "select":
501
+ self.emit_query(node, v, "select")
502
+
503
+ def handed(self, v) -> None:
504
+ if isinstance(v, Query) and not v.root["emitted"]:
505
+ v.root["handed"] = v
506
+
507
+ # calls
508
+ def ev_call(self, call: ast.Call):
509
+ fn = call.func
510
+ if isinstance(fn, ast.Name) and fn.id in CONSUMERS and call.args:
511
+ v = self.ev(call.args[0])
512
+ for a in call.args[1:]:
513
+ self.ev(a)
514
+ if fn.id == "next" and isinstance(v, Query):
515
+ qq = v.copy()
516
+ qq.limit = qq.limit or None
517
+ self.emit_query(call, qq, "select")
518
+ else:
519
+ self.consume(call.args[0], v)
520
+ return None
521
+ if isinstance(fn, ast.Attribute):
522
+ method = fn.attr
523
+ recv = self.ev(fn.value)
524
+ if isinstance(recv, MRef):
525
+ return self.model_call(call, recv.model, method)
526
+ if isinstance(recv, Query):
527
+ return self.query_call(call, recv, method)
528
+ if isinstance(recv, FRef):
529
+ # a field method that makes another expression (JSONField.update, .concat, .bin_and ...): its SQL is
530
+ # not written here; the caller shows the source as a run-time part
531
+ self.args(call)
532
+ return None
533
+ if method == "execute_sql":
534
+ self.args(call)
535
+ return None
536
+ else:
537
+ self.ev(fn)
538
+ self.args(call, hand=True)
539
+ return None
540
+
541
+ def args(self, call: ast.Call, hand: bool = False) -> None:
542
+ for a in call.args:
543
+ v = self.ev(a.value if isinstance(a, ast.Starred) else a)
544
+ if hand:
545
+ self.handed(v)
546
+ for k in call.keywords:
547
+ v = self.ev(k.value)
548
+ if hand:
549
+ self.handed(v)
550
+
551
+ def seen(self, call: ast.Call, ok: bool, reason: str = "") -> None:
552
+ st = self.pw.stats
553
+ if id(call) in self.pw.counted:
554
+ return
555
+ self.pw.counted.add(id(call))
556
+ st.seen += 1
557
+ if ok:
558
+ st.translated += 1
559
+ else:
560
+ st.miss(reason, f"{self.mod.rel}:{call.lineno}")
561
+
562
+ def model_call(self, call: ast.Call, m: PModel, method: str):
563
+ if method == "select":
564
+ qq = Query(m, "select", call)
565
+ qq.cols = self.columns(call.args, m) if call.args else None
566
+ self.roots.append(qq.root)
567
+ self.pw.track(self, call, qq)
568
+ return qq
569
+ if method in ("update",):
570
+ qq = Query(m, "update", call)
571
+ qq.sets = self.sets(call, m)
572
+ self.roots.append(qq.root)
573
+ self.pw.track(self, call, qq)
574
+ return qq
575
+ if method == "delete":
576
+ qq = Query(m, "delete", call)
577
+ self.roots.append(qq.root)
578
+ self.pw.track(self, call, qq)
579
+ return qq
580
+ if method in ("insert", "replace", "insert_many", "replace_many", "insert_from"):
581
+ qq = Query(m, "insert", call)
582
+ self.insert_values(call, m, qq, many=method.endswith("_many"))
583
+ if method.startswith("replace"):
584
+ qq.conflict = "replace"
585
+ self.roots.append(qq.root)
586
+ self.pw.track(self, call, qq)
587
+ return qq
588
+ if method in ("get", "get_or_none"):
589
+ qq = Query(m, "select", call)
590
+ qq.where = [self.pred(a, m) for a in call.args] + [self.kw_pred(k, m) for k in call.keywords if k.arg]
591
+ qq.limit = "1"
592
+ self.emit_query(call, qq, "get", count=True)
593
+ return None
594
+ if method in ("get_by_id", "get_or_none_by_id"):
595
+ self.by_pk(call, m, call.args[0] if call.args else None, "get")
596
+ return None
597
+ if method == "delete_by_id":
598
+ self.by_pk(call, m, call.args[0] if call.args else None, "delete")
599
+ return None
600
+ if method == "set_by_id":
601
+ qq = Query(m, "update", call)
602
+ qq.sets = self.sets(ast.Call(func=call.func, args=call.args[1:2], keywords=[]), m)
603
+ qq.where = [self.pk_pred(m, call.args[0] if call.args else None)]
604
+ self.emit_query(call, qq, "update", count=True)
605
+ return None
606
+ if method == "create":
607
+ qq = Query(m, "insert", call)
608
+ self.insert_values(call, m, qq, many=False)
609
+ self.emit_query(call, qq, "insert", count=True)
610
+ return None
611
+ if method == "get_or_create":
612
+ look = [k for k in call.keywords if k.arg and k.arg != "defaults"]
613
+ sel = Query(m, "select", call)
614
+ sel.where = [self.kw_pred(k, m) for k in look]
615
+ sel.limit = "1"
616
+ self.emit_query(call, sel, "get", count=True)
617
+ ins = Query(m, "insert", call)
618
+ defaults = kwarg(call, "defaults")
619
+ ins.ins_cols = [m.col(k.arg) or k.arg for k in look]
620
+ ins.ins_vals = [self.value(k.value) for k in look]
621
+ if defaults is not None:
622
+ ins.notes.append("plus the columns of `defaults`: " + src(defaults))
623
+ ins.conf = 1
624
+ self.emit_query(call, ins, "insert")
625
+ return None
626
+ if method in ("bulk_create", "bulk_update"):
627
+ self.args(call)
628
+ if method == "bulk_create":
629
+ qq = Query(m, "insert", call)
630
+ cols = [f for f in m.fields.values() if not (f.pk and f.type in ("INTEGER", "BIGINT") and len(m.pk) == 1)]
631
+ qq.ins_cols = [f.column for f in cols]
632
+ qq.ins_vals = [marker(f"{src(call.args[0]) if call.args else 'objects'} .{f.name}") for f in cols]
633
+ qq.notes.append("one multi-row INSERT per batch")
634
+ else:
635
+ qq = Query(m, "update", call)
636
+ fields = kwarg(call, "fields") or (call.args[1] if len(call.args) > 1 else None)
637
+ names = [x for x in (self.field_name(e, m) for e in getattr(fields, "elts", [])) if x]
638
+ if not names:
639
+ self.seen(call, False, "bulk_update with fields not known here")
640
+ return None
641
+ qq.sets = [(c, "CASE " + marker("id -> value of each object") + " END") for c in names]
642
+ qq.where = [f"{q(m.table)}.{q(m.pk[0] if m.pk else 'id')} IN (" + marker(src(call.args[0]) if call.args else "objects") + ")"]
643
+ qq.conf = 1
644
+ self.emit_query(call, qq, qq.kind if qq.kind != "insert" else "insert", count=True)
645
+ return None
646
+ if method == "raw":
647
+ sql = str_const(call.args[0]) if call.args else None
648
+ self.args(call)
649
+ if sql is None:
650
+ self.seen(call, False, "raw() SQL text not a literal here")
651
+ return None
652
+ self.pw.emit_raw(self, call, m, sql)
653
+ self.seen(call, True)
654
+ return None
655
+ if method in ("truncate_table",):
656
+ self.pw.emit_raw(self, call, m, f"DELETE FROM {q(m.table)}", operation="delete")
657
+ self.seen(call, True)
658
+ return None
659
+ if method in ("create_table", "drop_table", "bind", "bind_ctx", "alias", "table_exists", "add_index", "index"):
660
+ self.args(call)
661
+ return None
662
+ self.args(call)
663
+ return None
664
+
665
+ def by_pk(self, node, m: PModel, key: ast.AST | None, op: str) -> None:
666
+ qq = Query(m, "select" if op == "get" else "delete", node)
667
+ qq.where = [self.pk_pred(m, key)]
668
+ if op == "get":
669
+ qq.limit = "1"
670
+ self.emit_query(node, qq, op, count=True)
671
+
672
+ def pk_pred(self, m: PModel, key: ast.AST | None) -> str:
673
+ pk = m.pk[0] if len(m.pk) == 1 else None
674
+ if pk is None:
675
+ return marker("primary key = " + (src(key) if key is not None else "?"))
676
+ return f"{q(m.table)}.{q(pk)} = {self.value(key) if key is not None else marker('id')}"
677
+
678
+ def query_call(self, call: ast.Call, qq: Query, method: str):
679
+ m = qq.model
680
+ if method in ("where", "filter", "orwhere"):
681
+ n = qq.copy()
682
+ preds = [self.pred(a, n.ctx) for a in call.args]
683
+ if method == "filter":
684
+ preds += [self.kw_pred(k, n.ctx) for k in call.keywords if k.arg]
685
+ if method == "orwhere" and n.where:
686
+ n.where = ["(" + " AND ".join(n.where) + ") OR (" + " AND ".join(preds) + ")"]
687
+ else:
688
+ n.where.extend(preds)
689
+ return n
690
+ if method in ("join", "left_outer_join", "join_from"):
691
+ n = qq.copy()
692
+ args = call.args[1:] if method == "join_from" else call.args
693
+ target = self.ev(args[0]) if args else None
694
+ on = kwarg(call, "on") or (args[2] if len(args) > 2 else None)
695
+ jt = kwarg(call, "join_type") or (args[1] if len(args) > 1 else None)
696
+ kind = "LEFT OUTER JOIN" if method == "left_outer_join" or (jt is not None and "LEFT" in src(jt).upper()) else "INNER JOIN"
697
+ if not isinstance(target, MRef):
698
+ n.joins.append(f"{kind} {marker(src(args[0]) if args else 'join')} ON {marker('join condition')}")
699
+ n.conf = max(n.conf, 1)
700
+ return n
701
+ t = target.model
702
+ cond = self.pred(on, n.ctx) if on is not None else self.join_on(n.ctx, t)
703
+ n.joins.append(f"{kind} {q(t.table)} ON {cond}")
704
+ n.ctx = t
705
+ return n
706
+ if method == "switch":
707
+ n = qq.copy()
708
+ target = self.ev(call.args[0]) if call.args else None
709
+ n.ctx = target.model if isinstance(target, MRef) else m
710
+ return n
711
+ if method in ("order_by", "order_by_extend"):
712
+ n = qq.copy()
713
+ items = [self.order_item(a, n.ctx) for a in call.args]
714
+ n.order = (n.order if method == "order_by_extend" else []) + items
715
+ return n
716
+ if method == "limit":
717
+ n = qq.copy()
718
+ n.limit = self.value(call.args[0]) if call.args else None
719
+ if n.limit == "NULL":
720
+ n.limit = None
721
+ return n
722
+ if method == "offset":
723
+ n = qq.copy()
724
+ n.offset = self.value(call.args[0]) if call.args else None
725
+ return n
726
+ if method == "paginate":
727
+ n = qq.copy()
728
+ page = call.args[0] if call.args else None
729
+ by = call.args[1] if len(call.args) > 1 else kwarg(call, "paginate_by")
730
+ okp, pv = const(page)
731
+ okb, bv = const(by) if by is not None else (True, 20)
732
+ n.limit = str(bv) if okb else self.value(by)
733
+ if okp and okb and isinstance(pv, int) and isinstance(bv, int):
734
+ n.offset = str(max(pv - 1, 0) * bv)
735
+ else:
736
+ n.offset = marker(f"({src(page) if page is not None else 'page'} - 1) * {src(by) if by is not None else 20}")
737
+ return n
738
+ if method == "distinct":
739
+ n = qq.copy()
740
+ n.distinct = True
741
+ return n
742
+ if method == "group_by":
743
+ n = qq.copy()
744
+ n.group = [self.expr(a, n.ctx) for a in call.args]
745
+ return n
746
+ if method == "having":
747
+ n = qq.copy()
748
+ n.having.extend(self.pred(a, n.ctx) for a in call.args)
749
+ return n
750
+ if method in ("select", "select_extend", "columns"):
751
+ n = qq.copy()
752
+ cols = self.columns(call.args, n.model)
753
+ n.cols = (n.cols or [] if method == "select_extend" else []) + cols
754
+ return n
755
+ if method in ("on_conflict_replace",):
756
+ n = qq.copy()
757
+ n.conflict = "replace"
758
+ return n
759
+ if method in ("on_conflict_ignore",):
760
+ n = qq.copy()
761
+ n.conflict = "ignore"
762
+ return n
763
+ if method == "on_conflict":
764
+ n = qq.copy()
765
+ action = str_const(kwarg(call, "action")) or (str_const(call.args[0]) if call.args else None)
766
+ if action and action.upper() in ("REPLACE", "IGNORE"):
767
+ n.conflict = action.lower()
768
+ return n
769
+ target = kwarg(call, "conflict_target")
770
+ cols = [self.field_name(e, m) for e in getattr(target, "elts", [])]
771
+ preserve = kwarg(call, "preserve")
772
+ update = kwarg(call, "update")
773
+ sets = []
774
+ for e in getattr(preserve, "elts", []) if preserve is not None else []:
775
+ c = self.field_name(e, m)
776
+ sets.append(f"{q(c)} = EXCLUDED.{q(c)}" if c else marker(src(e)))
777
+ if isinstance(update, ast.Dict):
778
+ for k, v in zip(update.keys, update.values):
779
+ c = self.field_name(k, m) if k is not None else None
780
+ sets.append(f"{q(c)} = {self.expr(v, m)}" if c else marker(src(k) if k is not None else "**"))
781
+ elif update is not None:
782
+ sets.append(marker(src(update)))
783
+ tgt = "(" + ", ".join(q(c) for c in cols if c) + ")" if cols and all(cols) else ""
784
+ n.conflict = f"ON CONFLICT {tgt} " + ("DO UPDATE SET " + ", ".join(sets) if sets else "DO NOTHING")
785
+ n.conflict = re.sub(r"\s+", " ", n.conflict)
786
+ return n
787
+ if method in PASS:
788
+ self.args(call)
789
+ return qq
790
+ if method in ("execute",):
791
+ self.args(call)
792
+ self.emit_query(call, qq, {"select": "select", "update": "update", "delete": "delete", "insert": "insert"}[qq.kind])
793
+ return None
794
+ if method in ("get", "first", "peek", "scalar", "get_or_none"):
795
+ n = qq.copy()
796
+ if method in ("scalar", "peek"):
797
+ pass # peewee reads the first row of the result; it adds no LIMIT
798
+ elif method == "first" and call.args:
799
+ n.limit = self.value(call.args[0])
800
+ else:
801
+ n.limit = "1"
802
+ self.emit_query(call, n, "get" if method in ("get", "get_or_none") else method)
803
+ return None
804
+ if method == "count":
805
+ self.emit_query(call, qq, "count")
806
+ return None
807
+ if method == "exists":
808
+ self.emit_query(call, qq, "exists")
809
+ return None
810
+ if method in ("__iter__", "iterator"):
811
+ return qq
812
+ self.args(call)
813
+ return qq
814
+
815
+ # SQL pieces
816
+ def columns(self, args: list, m: PModel) -> list[str]:
817
+ out = []
818
+ for a in args:
819
+ if isinstance(a, ast.Starred):
820
+ items = self.local_list(a.value)
821
+ if items is None:
822
+ out.append(marker("*" + src(a.value)))
823
+ else:
824
+ out.extend(self.columns(items, m))
825
+ continue
826
+ v = self.ev(a)
827
+ if isinstance(v, MRef):
828
+ out.extend(f"{q(v.model.table)}.{q(c)}" for c in v.model.columns())
829
+ else:
830
+ out.append(self.expr(a, m))
831
+ return out
832
+
833
+ def local_list(self, node: ast.AST):
834
+ """The elements of a list or tuple bound to a local name with a literal (no later appends followed)."""
835
+ if isinstance(node, (ast.List, ast.Tuple)):
836
+ return list(node.elts)
837
+ if isinstance(node, ast.Name):
838
+ v = self.pw.literal_lists.get((id(self), node.id))
839
+ return v
840
+ return None
841
+
842
+ def field_name(self, node: ast.AST, m: PModel) -> str | None:
843
+ s = str_const(node)
844
+ if s is not None:
845
+ return m.col(s) or s
846
+ v = self.ev(node)
847
+ if isinstance(v, FRef) and v.model is not None:
848
+ return v.sql.rsplit(".", 1)[-1].strip('"')
849
+ return None
850
+
851
+ def sets(self, call: ast.Call, m: PModel) -> list[tuple[str, str]]:
852
+ out = []
853
+ for a in call.args:
854
+ if isinstance(a, ast.Dict):
855
+ for k, v in zip(a.keys, a.values):
856
+ c = self.field_name(k, m) if k is not None else None
857
+ out.append((c, self.expr(v, m)) if c else (marker(src(k) if k is not None else "**"), marker(src(v))))
858
+ else:
859
+ out.append((marker(src(a)), marker(src(a) + " values")))
860
+ for k in call.keywords:
861
+ if k.arg is None:
862
+ out.append((marker("**" + src(k.value)), marker("**" + src(k.value) + " values")))
863
+ else:
864
+ out.append((m.col(k.arg) or k.arg, self.expr(k.value, m)))
865
+ return out
866
+
867
+ def insert_values(self, call: ast.Call, m: PModel, qq: Query, many: bool) -> None:
868
+ rows = call.args[0] if call.args else kwarg(call, "rows") or kwarg(call, "__data")
869
+ fields = kwarg(call, "fields") or (call.args[1] if many and len(call.args) > 1 else None)
870
+ if not many:
871
+ if isinstance(rows, ast.Dict):
872
+ for k, v in zip(rows.keys, rows.values):
873
+ c = self.field_name(k, m) if k is not None else None
874
+ qq.ins_cols.append(c or marker(src(k) if k is not None else "**"))
875
+ qq.ins_vals.append(self.value(v))
876
+ elif rows is not None:
877
+ qq.ins_cols.append(marker("columns of " + src(rows)))
878
+ qq.ins_vals.append(marker(src(rows)))
879
+ qq.conf = 2
880
+ for k in call.keywords:
881
+ if k.arg is None:
882
+ qq.ins_cols.append(marker("columns of **" + src(k.value)))
883
+ qq.ins_vals.append(marker("**" + src(k.value)))
884
+ qq.conf = 2
885
+ elif k.arg not in ("__data",):
886
+ qq.ins_cols.append(m.col(k.arg) or k.arg)
887
+ qq.ins_vals.append(self.value(k.value))
888
+ return
889
+ names = [self.field_name(e, m) for e in getattr(fields, "elts", [])] if fields is not None else []
890
+ if names and all(names):
891
+ qq.ins_cols = names
892
+ elif isinstance(rows, (ast.List, ast.Tuple)) and rows.elts and isinstance(rows.elts[0], ast.Dict):
893
+ qq.ins_cols = [self.field_name(k, m) or marker(src(k)) for k in rows.elts[0].keys if k is not None]
894
+ else:
895
+ qq.ins_cols = [f.column for f in m.fields.values() if not (f.pk and f.type in ("INTEGER", "BIGINT") and len(m.pk) == 1)]
896
+ qq.notes.append("columns taken from the model: the rows may set fewer")
897
+ qq.conf = max(qq.conf, 1)
898
+ qq.ins_vals = [marker(f"{src(rows) if rows is not None else 'rows'} [{c}]") for c in qq.ins_cols]
899
+ qq.notes.append("one multi-row INSERT for all the rows")
900
+ self.ev(rows)
901
+
902
+ def join_on(self, a: PModel, b: PModel) -> str:
903
+ idx = self.pw.index
904
+ for f in a.fields.values():
905
+ if f.kind == "fk" and idx.target(a, f) is b and b.pk:
906
+ return f"{q(a.table)}.{q(f.column)} = {q(b.table)}.{q(b.pk[0])}"
907
+ for f in b.fields.values():
908
+ if f.kind == "fk" and idx.target(b, f) is a and a.pk:
909
+ return f"{q(b.table)}.{q(f.column)} = {q(a.table)}.{q(a.pk[0])}"
910
+ return marker(f"join condition {a.name} -> {b.name}")
911
+
912
+ def order_item(self, node: ast.AST, m: PModel) -> str:
913
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in ("desc", "asc"):
914
+ inner = self.expr(node.func.value, m)
915
+ suffix = " DESC" if node.func.attr == "desc" else " ASC"
916
+ ok, nulls = const(kwarg(node, "nulls"))
917
+ if ok and isinstance(nulls, str):
918
+ suffix += " NULLS " + nulls.upper()
919
+ return inner + suffix
920
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
921
+ return self.expr(node.operand, m) + " DESC"
922
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.UAdd):
923
+ return self.expr(node.operand, m) + " ASC"
924
+ if isinstance(node, ast.Starred):
925
+ return marker("*" + src(node.value))
926
+ return self.expr(node, m)
927
+
928
+ def kw_pred(self, k: ast.keyword, m: PModel) -> str:
929
+ col = m.col(k.arg) if k.arg else None
930
+ if col is None:
931
+ return marker(f"{k.arg}={src(k.value)}")
932
+ v = self.value(k.value)
933
+ return f"{q(m.table)}.{q(col)} IS NULL" if v == "NULL" else f"{q(m.table)}.{q(col)} = {v}"
934
+
935
+ def value(self, node: ast.AST | None) -> str:
936
+ if node is None:
937
+ return "NULL"
938
+ ok, v = const(node)
939
+ if ok and not isinstance(v, list):
940
+ lit = sql_literal(v)
941
+ if lit is not None:
942
+ return lit
943
+ got = self.ev(node)
944
+ if isinstance(got, FRef):
945
+ return got.sql
946
+ if isinstance(got, Query):
947
+ return "(" + self.render(got, "select") + ")"
948
+ return marker(src(node))
949
+
950
+ def in_list(self, node: ast.AST) -> str:
951
+ ok, v = const(node)
952
+ if ok and isinstance(v, list):
953
+ lits = [sql_literal(x) for x in v]
954
+ if all(x is not None for x in lits):
955
+ return "(" + (", ".join(lits) or "NULL") + ")"
956
+ got = self.ev(node)
957
+ if isinstance(got, Query):
958
+ return "(" + self.render(got, "select") + ")"
959
+ return "(" + marker(src(node)) + ")"
960
+
961
+ def expr(self, node: ast.AST | None, m: PModel) -> str:
962
+ """A column-side expression (select list, SET value, order item, function argument)."""
963
+ if node is None:
964
+ return "NULL"
965
+ ok, v = const(node)
966
+ if ok and not isinstance(v, list):
967
+ lit = sql_literal(v)
968
+ if lit is not None:
969
+ return lit
970
+ if isinstance(node, ast.Call):
971
+ fname = dotted(node.func) or ""
972
+ if fname.startswith("fn.") or fname.startswith("peewee.fn."):
973
+ name = fname.split(".")[-1]
974
+ args = [self.expr(a, m) for a in node.args]
975
+ return f"{name.upper()}({', '.join(args)})"
976
+ if fname.split(".")[-1] in ("SQL",) and node.args and str_const(node.args[0]) is not None:
977
+ return str_const(node.args[0])
978
+ if fname.split(".")[-1] == "Case":
979
+ return marker(src(node))
980
+ if isinstance(node.func, ast.Attribute):
981
+ meth = node.func.attr
982
+ if meth == "alias" and node.args:
983
+ return f"{self.expr(node.func.value, m)} AS {q(str_const(node.args[0]) or 'x')}"
984
+ if meth in ("desc", "asc"):
985
+ return self.order_item(node, m)
986
+ if meth == "distinct":
987
+ return "DISTINCT " + self.expr(node.func.value, m)
988
+ if meth == "cast" and node.args and str_const(node.args[0]):
989
+ return f"CAST({self.expr(node.func.value, m)} AS {str_const(node.args[0])})"
990
+ if meth in ("in_", "not_in", "is_null", "contains", "startswith", "endswith", "between", "regexp", "iregexp",
991
+ "icontains", "istartswith", "iendswith"):
992
+ return self.pred(node, m)
993
+ if meth == "over":
994
+ return marker(src(node))
995
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)):
996
+ sym = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/"}[type(node.op)]
997
+ return f"({self.expr(node.left, m)} {sym} {self.expr(node.right, m)})"
998
+ if isinstance(node, (ast.BinOp, ast.Compare, ast.UnaryOp)):
999
+ return self.pred(node, m)
1000
+ if isinstance(node, ast.Subscript):
1001
+ base = self.ev(node.value)
1002
+ key = str_const(node.slice)
1003
+ if isinstance(base, FRef) and key is not None:
1004
+ path = "$." + key
1005
+ engine = self.pw.engine
1006
+ if engine == "sqlite":
1007
+ return f"json_extract({base.sql}, '{path}')"
1008
+ if engine == "postgres":
1009
+ return f"({base.sql} ->> '{key}')"
1010
+ if engine == "mysql":
1011
+ return f"JSON_EXTRACT({base.sql}, '{path}')"
1012
+ return marker(src(node))
1013
+ got = self.ev(node)
1014
+ if isinstance(got, FRef):
1015
+ return got.sql
1016
+ if isinstance(got, MRef):
1017
+ return f"{q(got.model.table)}.*"
1018
+ if isinstance(got, Query):
1019
+ return "(" + self.render(got, "select") + ")"
1020
+ return marker(src(node))
1021
+
1022
+ def pred(self, node: ast.AST | None, m: PModel) -> str:
1023
+ if node is None:
1024
+ return "TRUE"
1025
+ ok, v = const(node)
1026
+ if ok and isinstance(v, bool):
1027
+ return "TRUE" if v else "FALSE"
1028
+ if isinstance(node, ast.Compare) and len(node.ops) == 1:
1029
+ left = self.expr(node.left, m)
1030
+ right = node.comparators[0]
1031
+ op = node.ops[0]
1032
+ if type(op) in OPS:
1033
+ rv = self.value(right)
1034
+ if rv == "NULL" and type(op) in (ast.Eq, ast.NotEq):
1035
+ return f"{left} IS {'NOT ' if isinstance(op, ast.NotEq) else ''}NULL"
1036
+ return f"{left} {OPS[type(op)]} {rv}"
1037
+ if isinstance(node, ast.BinOp):
1038
+ if isinstance(node.op, ast.BitAnd):
1039
+ return f"({self.pred(node.left, m)} AND {self.pred(node.right, m)})"
1040
+ if isinstance(node.op, ast.BitOr):
1041
+ return f"({self.pred(node.left, m)} OR {self.pred(node.right, m)})"
1042
+ if isinstance(node.op, ast.LShift):
1043
+ return f"{self.expr(node.left, m)} IN {self.in_list(node.right)}"
1044
+ if isinstance(node.op, ast.RShift):
1045
+ rv = self.value(node.right)
1046
+ return f"{self.expr(node.left, m)} IS {rv}"
1047
+ if isinstance(node.op, ast.Mod):
1048
+ return f"{self.expr(node.left, m)} LIKE {self.value(node.right)}"
1049
+ if isinstance(node.op, ast.Pow):
1050
+ return f"{self.expr(node.left, m)} {'ILIKE' if self.pw.engine == 'postgres' else 'LIKE'} {self.value(node.right)}"
1051
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Invert):
1052
+ return f"NOT ({self.pred(node.operand, m)})"
1053
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
1054
+ meth = node.func.attr
1055
+ base = node.func.value
1056
+ arg = node.args[0] if node.args else None
1057
+ if meth in ("in_", "not_in"):
1058
+ return f"{self.expr(base, m)} {'NOT IN' if meth == 'not_in' else 'IN'} {self.in_list(arg)}"
1059
+ if meth == "is_null":
1060
+ okv, isnull = const(arg) if arg is not None else (True, True)
1061
+ if okv:
1062
+ return f"{self.expr(base, m)} IS {'' if isnull else 'NOT '}NULL"
1063
+ return f"({self.expr(base, m)} IS NULL) = {self.value(arg)}"
1064
+ if meth in ("contains", "startswith", "endswith", "icontains", "istartswith", "iendswith"):
1065
+ s = str_const(arg)
1066
+ pat = {"contains": "%{}%", "startswith": "{}%", "endswith": "%{}"}[meth.lstrip("i") if meth.startswith("i") and meth != "in_" else meth]
1067
+ like = "ILIKE" if self.pw.engine == "postgres" and meth.startswith(("contains", "i")) else "LIKE"
1068
+ val = sql_literal(pat.format(s)) if s is not None else marker(pat.format(src(arg)))
1069
+ return f"{self.expr(base, m)} {like} {val}"
1070
+ if meth == "between" and len(node.args) == 2:
1071
+ return f"{self.expr(base, m)} BETWEEN {self.value(node.args[0])} AND {self.value(node.args[1])}"
1072
+ if meth in ("regexp", "iregexp"):
1073
+ return f"{self.expr(base, m)} REGEXP {self.value(arg)}"
1074
+ got = self.ev(node)
1075
+ if isinstance(got, FRef):
1076
+ return got.sql
1077
+ # a clause built elsewhere (a list reduced at run time, a helper's result): a run-time predicate
1078
+ return marker(src(node))
1079
+
1080
+ # emission
1081
+ def render(self, qq: Query, op: str) -> str:
1082
+ m = qq.model
1083
+ t = q(m.table)
1084
+ where = (" WHERE " + " AND ".join(qq.where)) if qq.where else ""
1085
+ if qq.kind == "select":
1086
+ cols = qq.cols if qq.cols else [f"{t}.{q(c)}" for c in m.columns()]
1087
+ base = (f"SELECT {'DISTINCT ' if qq.distinct else ''}{', '.join(cols)} FROM {t}"
1088
+ + ("".join(" " + j for j in qq.joins)) + where
1089
+ + (" GROUP BY " + ", ".join(qq.group) if qq.group else "")
1090
+ + (" HAVING " + " AND ".join(qq.having) if qq.having else ""))
1091
+ if op == "count":
1092
+ inner = base
1093
+ if qq.limit:
1094
+ inner += f" LIMIT {qq.limit}" + (f" OFFSET {qq.offset}" if qq.offset else "")
1095
+ return f"SELECT COUNT(1) FROM ({inner}) AS _wrapped"
1096
+ if op == "exists":
1097
+ return (f"SELECT 1 FROM {t}" + "".join(" " + j for j in qq.joins) + where
1098
+ + (" GROUP BY " + ", ".join(qq.group) if qq.group else "") + " LIMIT 1")
1099
+ return (base + (" ORDER BY " + ", ".join(qq.order) if qq.order else "")
1100
+ + (f" LIMIT {qq.limit}" if qq.limit else "") + (f" OFFSET {qq.offset}" if qq.offset else ""))
1101
+ if qq.kind == "update":
1102
+ sets = ", ".join(f"{c if c.startswith('«') else q(c)} = {v}" for c, v in qq.sets) or marker("columns to set")
1103
+ return f"UPDATE {t} SET {sets}{where}"
1104
+ if qq.kind == "delete":
1105
+ return f"DELETE FROM {t}{where}"
1106
+ cols = ", ".join(c if c.startswith("«") else q(c) for c in qq.ins_cols)
1107
+ vals = ", ".join(qq.ins_vals)
1108
+ engine = self.pw.engine
1109
+ head = "INSERT"
1110
+ tail = ""
1111
+ if qq.conflict == "replace":
1112
+ head = "REPLACE" if engine == "mysql" else "INSERT OR REPLACE"
1113
+ elif qq.conflict == "ignore":
1114
+ if engine == "postgres":
1115
+ tail = " ON CONFLICT DO NOTHING"
1116
+ else:
1117
+ head = "INSERT IGNORE" if engine == "mysql" else "INSERT OR IGNORE"
1118
+ elif qq.conflict:
1119
+ tail = " " + qq.conflict
1120
+ if not qq.ins_cols:
1121
+ return f"{head} INTO {t} DEFAULT VALUES{tail}"
1122
+ return f"{head} INTO {t} ({cols}) VALUES ({vals}){tail}"
1123
+
1124
+ def emit_query(self, node: ast.AST, qq: Query, op: str, count: bool = False) -> None:
1125
+ if qq.root.get("emitted") and op == "select" and not count and qq.root.get("emitted_select"):
1126
+ return
1127
+ qq.root["emitted"] = True
1128
+ if op == "select":
1129
+ qq.root["emitted_select"] = True
1130
+ sql = self.render(qq, op)
1131
+ notes = list(qq.notes)
1132
+ if self.cond:
1133
+ notes.append("runs on some run-time condition")
1134
+ self.pw.emit(self, node, qq.model, sql, op, qq.conf, notes)
1135
+ if count and isinstance(node, ast.Call):
1136
+ self.seen(node, True)
1137
+ elif qq.root["node"] is not None and isinstance(qq.root["node"], ast.Call):
1138
+ self.seen(qq.root["node"], True)
1139
+
1140
+ def finish(self) -> None:
1141
+ for root in self.roots:
1142
+ if root.get("emitted"):
1143
+ continue
1144
+ last = root.get("handed") or root.get("last")
1145
+ if last is None or last.kind != "select" or root.get("handed") is None:
1146
+ if last is not None and isinstance(root["node"], ast.Call):
1147
+ self.seen(root["node"], False, "query built here; no place where it runs was found in the function"
1148
+ if last.kind == "select" else f"{last.kind} query built here; execute() not seen in the function")
1149
+ continue
1150
+ n = last.copy()
1151
+ n.notes.append("query handed to other code, which runs it")
1152
+ n.conf = max(n.conf, 1)
1153
+ self.emit_query(root["node"], n, "select")
1154
+
1155
+
1156
+ class Peewee:
1157
+ def __init__(self, root: Path, project: Project):
1158
+ self.root, self.project = root, project
1159
+ self.index = Index(project)
1160
+ self.stats = Stats(LIBRARY)
1161
+ self.out = Emitter(self.stats)
1162
+ self.counted: set[int] = set()
1163
+ self.literal_lists: dict = {}
1164
+ self.engine = self.index.engine
1165
+
1166
+ def track(self, w: Walker, call: ast.Call, qq: Query) -> None:
1167
+ qq.root["last"] = qq
1168
+
1169
+ def emit(self, w: Walker, node: ast.AST, m: PModel, sql: str, op: str, conf: int, notes: list[str]) -> None:
1170
+ if self.out.emit(w.mod, node, w.symbol, sql, sink=_sink(node), in_loop=w.loop > 0, model=m.label, operation=op,
1171
+ confidence=CONF[min(conf, 2)], notes="; ".join(dict.fromkeys(notes)), engine=self.engine):
1172
+ site = self.out.sites[-1]
1173
+ site.orm["mechanism"] = "orm_api_in_loop" if w.loop > 0 else "orm_api"
1174
+
1175
+ def emit_raw(self, w: Walker, node: ast.AST, m: PModel, sql: str, operation: str = "") -> None:
1176
+ op = operation or (sql.strip().split(None, 1)[0].lower() if sql.strip() else "raw")
1177
+ if self.out.emit(w.mod, node, w.symbol, sql, sink=_sink(node), in_loop=w.loop > 0, model=m.label, operation=op,
1178
+ confidence="high", notes="raw SQL of the model", engine=self.engine):
1179
+ self.out.sites[-1].orm["mechanism"] = "orm_raw_fragment"
1180
+
1181
+ def run(self) -> None:
1182
+ if not self.index.models:
1183
+ return
1184
+ names = re.compile(r"\b(?:" + "|".join(sorted({re.escape(m.name) for m in self.index.models.values()})) + r"|cls)\b")
1185
+ for mod in self.project.mods.values():
1186
+ if not names.search(mod.text):
1187
+ continue
1188
+ self.scope(mod, None, mod.tree.body, "", None)
1189
+
1190
+ def scope(self, mod: Mod, cls: Cls | None, body: list, symbol: str, env: dict | None) -> None:
1191
+ w = Walker(self, mod, cls, symbol, env)
1192
+ self._lists(w, body)
1193
+ try:
1194
+ w.run(body)
1195
+ except RecursionError:
1196
+ self.stats.miss("internal: expression too deep", f"{mod.rel}:{getattr(body[0], 'lineno', 1) if body else 1}")
1197
+ except Exception as e: # one function we cannot read must never stop discovery
1198
+ if os.environ.get("CODECOP_ORM_DEBUG"):
1199
+ raise
1200
+ self.stats.miss(f"internal error ({type(e).__name__})", f"{mod.rel}:{getattr(body[0], 'lineno', 1) if body else 1}")
1201
+ for st in w.nested:
1202
+ sym = (symbol + "." if symbol else "") + st.name
1203
+ if isinstance(st, ast.ClassDef):
1204
+ inner = (cls.inner.get(st.name) if cls is not None else mod.classes.get(st.name))
1205
+ self.scope(mod, inner, st.body, sym, None)
1206
+ else:
1207
+ # a function sees the names of the scope it is defined in (closures: a query built outside, run inside)
1208
+ closure = {k: v for k, v in w.env.items() if isinstance(v, (MRef, Query))} if symbol else None
1209
+ self.scope(mod, cls, st.body, sym, closure)
1210
+ try:
1211
+ w.finish()
1212
+ except Exception:
1213
+ if os.environ.get("CODECOP_ORM_DEBUG"):
1214
+ raise
1215
+
1216
+ def _lists(self, w: Walker, body: list) -> None:
1217
+ """Lists and tuples of column expressions bound once in the scope (`columns = [Event.id, Event.label]`)."""
1218
+ counts: dict[str, int] = {}
1219
+ values: dict[str, ast.AST] = {}
1220
+ for st in _flat(body):
1221
+ if isinstance(st, ast.Assign):
1222
+ for t in st.targets:
1223
+ if isinstance(t, ast.Name):
1224
+ counts[t.id] = counts.get(t.id, 0) + 1
1225
+ values[t.id] = st.value
1226
+ elif isinstance(st, ast.AugAssign) and isinstance(st.target, ast.Name):
1227
+ counts[st.target.id] = counts.get(st.target.id, 0) + 2
1228
+ elif isinstance(st, ast.Expr) and isinstance(st.value, ast.Call) and isinstance(st.value.func, ast.Attribute) \
1229
+ and isinstance(st.value.func.value, ast.Name) and st.value.func.attr in ("append", "extend", "insert"):
1230
+ counts[st.value.func.value.id] = counts.get(st.value.func.value.id, 0) + 2
1231
+ for name, n in counts.items():
1232
+ v = values.get(name)
1233
+ if n == 1 and isinstance(v, (ast.List, ast.Tuple)) and not any(isinstance(e, ast.Starred) for e in v.elts):
1234
+ self.literal_lists[(id(w), name)] = list(v.elts)
1235
+
1236
+
1237
+ def _flat(body: list):
1238
+ stack = list(reversed(body))
1239
+ while stack:
1240
+ st = stack.pop()
1241
+ if isinstance(st, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
1242
+ continue
1243
+ yield st
1244
+ for name in ("body", "orelse", "finalbody"):
1245
+ sub = getattr(st, name, None)
1246
+ if isinstance(sub, list):
1247
+ stack.extend(reversed(sub))
1248
+ for h in getattr(st, "handlers", ()):
1249
+ stack.extend(reversed(h.body))
1250
+
1251
+
1252
+ def _sink(node: ast.AST) -> str:
1253
+ if isinstance(node, ast.Call):
1254
+ return " ".join(src(node.func).split())
1255
+ return src(node)
1256
+
1257
+
1258
+ def run(root: Path, project: Project):
1259
+ pw = Peewee(root, project)
1260
+ if not pw.index.models:
1261
+ return [], pw.stats, []
1262
+ pw.run()
1263
+ pw.stats.extra["models"] = len(pw.index.models)
1264
+ if pw.engine:
1265
+ pw.stats.extra["engine"] = pw.engine
1266
+ return pw.out.sites, pw.stats, pw.index.tables()