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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1082 @@
|
|
|
1
|
+
"""Go types and ORM models, as far as the source says them: enough to tell which library a value belongs to
|
|
2
|
+
(`*xorm.Session`, `*gorm.DB`, `sq.SelectBuilder`) and which table a struct is stored in.
|
|
3
|
+
|
|
4
|
+
Nothing here runs the Go type checker. A type is the text of its declaration plus the file it was written in
|
|
5
|
+
(so `issues.Issue` can be looked up through that file's imports); whatever cannot be followed is None, never a
|
|
6
|
+
guess.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from collections import defaultdict
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import NamedTuple
|
|
15
|
+
|
|
16
|
+
from tree_sitter import Node
|
|
17
|
+
|
|
18
|
+
from .go import FUNC_DECL, GoFile, _strip_parens, _txt, callee_name, call_args, param_type, recv_type
|
|
19
|
+
|
|
20
|
+
# How many steps one type or value is followed through (variables, fields, helpers). A setting:
|
|
21
|
+
# `[discover] orm_depth`.
|
|
22
|
+
DEFAULT_DEPTH = 14
|
|
23
|
+
DEPTH = DEFAULT_DEPTH
|
|
24
|
+
|
|
25
|
+
# import path prefix -> library
|
|
26
|
+
LIB_IMPORTS = {
|
|
27
|
+
"xorm.io/xorm": "xorm", "github.com/go-xorm/xorm": "xorm", "xorm.io/builder": "xbuilder",
|
|
28
|
+
"github.com/go-xorm/builder": "xbuilder",
|
|
29
|
+
"gorm.io/gorm": "gorm", "github.com/jinzhu/gorm": "gorm",
|
|
30
|
+
"github.com/Masterminds/squirrel": "squirrel", "github.com/lann/squirrel": "squirrel",
|
|
31
|
+
"github.com/mattermost/squirrel": "squirrel",
|
|
32
|
+
"github.com/huandu/go-sqlbuilder": "sqlbuilder",
|
|
33
|
+
"github.com/doug-martin/goqu": "goqu",
|
|
34
|
+
"github.com/uptrace/bun": "bun",
|
|
35
|
+
"entgo.io/ent": "ent",
|
|
36
|
+
}
|
|
37
|
+
# type name -> what a value of it is, per library
|
|
38
|
+
LIB_TYPES = {
|
|
39
|
+
"xorm": {"Session": "session", "Engine": "session", "Interface": "session", "EngineInterface": "session",
|
|
40
|
+
"EngineGroup": "session"},
|
|
41
|
+
"xbuilder": {"Cond": "cond", "Builder": "builder", "Eq": "cond", "Neq": "cond"},
|
|
42
|
+
"gorm": {"DB": "session", "Association": "assoc"},
|
|
43
|
+
"squirrel": {"StatementBuilderType": "stmt", "SelectBuilder": "select", "InsertBuilder": "insert",
|
|
44
|
+
"UpdateBuilder": "update", "DeleteBuilder": "delete", "Sqlizer": "cond", "And": "cond", "Or": "cond",
|
|
45
|
+
"Eq": "cond", "CaseBuilder": "cond"},
|
|
46
|
+
"sqlbuilder": {"SelectBuilder": "select", "InsertBuilder": "insert", "UpdateBuilder": "update",
|
|
47
|
+
"DeleteBuilder": "delete", "WhereClause": "cond", "Builder": "builder", "UnionBuilder": "select",
|
|
48
|
+
"CTEBuilder": "cte", "CTEQueryBuilder": "cte"},
|
|
49
|
+
"goqu": {"SelectDataset": "select", "InsertDataset": "insert", "UpdateDataset": "update", "DeleteDataset": "delete",
|
|
50
|
+
"Database": "session", "TxDatabase": "session", "DialectWrapper": "session"},
|
|
51
|
+
"bun": {"DB": "session", "IDB": "session", "Tx": "session", "Conn": "session", "SelectQuery": "select",
|
|
52
|
+
"InsertQuery": "insert", "UpdateQuery": "update", "DeleteQuery": "delete", "RawQuery": "raw"},
|
|
53
|
+
"ent": {"Client": "session", "Tx": "session"},
|
|
54
|
+
}
|
|
55
|
+
# A repository's own package shaped like bun (uptrace's `pkg/clickhouse/ch`, go-clickhouse's `ch`): a `DB` type with
|
|
56
|
+
# NewSelect() and a `SelectQuery` type. Its values are read as bun's, with these kinds.
|
|
57
|
+
BUN_SHAPED_TYPES = dict(LIB_TYPES["bun"])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# Method names that run a statement: their result is rows or an error, not the builder. Filled in by orm_go.
|
|
61
|
+
NOT_CHAINING: set[str] = set()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TypeRef(NamedTuple):
|
|
65
|
+
text: str # as written: `*issues.Issue`, `[]*T`, `map[string]X`
|
|
66
|
+
gf: GoFile # the file it was written in: its imports and its package resolve the names
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def import_lib(path: str) -> str:
|
|
70
|
+
for prefix, lib in LIB_IMPORTS.items():
|
|
71
|
+
if path == prefix or path.startswith(prefix + "/"):
|
|
72
|
+
# sub-packages are not the library's own API (gorm.io/gorm/clause, bun/dialect/...)
|
|
73
|
+
rest = path[len(prefix):]
|
|
74
|
+
if rest and not re.fullmatch(r"/v\d+", rest):
|
|
75
|
+
return ""
|
|
76
|
+
return lib
|
|
77
|
+
return ""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def base_type(text: str) -> tuple[str, bool]:
|
|
81
|
+
"""(`issues.Issue`, is a slice or array) for `[]*issues.Issue`."""
|
|
82
|
+
text = text.strip()
|
|
83
|
+
many = False
|
|
84
|
+
while True:
|
|
85
|
+
if text.startswith("*") or text.startswith("&"):
|
|
86
|
+
text = text[1:].strip()
|
|
87
|
+
elif text.startswith("..."):
|
|
88
|
+
text, many = text[3:].strip(), True
|
|
89
|
+
elif text.startswith("["):
|
|
90
|
+
close = text.find("]")
|
|
91
|
+
if close < 0:
|
|
92
|
+
break
|
|
93
|
+
text, many = text[close + 1:].strip(), True
|
|
94
|
+
else:
|
|
95
|
+
break
|
|
96
|
+
return text, many
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def elem_type(text: str) -> str:
|
|
100
|
+
"""The element type of a slice, array, or map (its values); "" when it is none of these."""
|
|
101
|
+
text = text.strip().lstrip("*")
|
|
102
|
+
if text.startswith("map["):
|
|
103
|
+
depth = 0
|
|
104
|
+
for i, c in enumerate(text[3:], 3):
|
|
105
|
+
if c == "[":
|
|
106
|
+
depth += 1
|
|
107
|
+
elif c == "]":
|
|
108
|
+
depth -= 1
|
|
109
|
+
if depth == 0:
|
|
110
|
+
return text[i + 1:].strip()
|
|
111
|
+
return ""
|
|
112
|
+
if text.startswith("..."):
|
|
113
|
+
return text[3:].strip()
|
|
114
|
+
if text.startswith("["):
|
|
115
|
+
close = text.find("]")
|
|
116
|
+
return text[close + 1:].strip() if close >= 0 else ""
|
|
117
|
+
return ""
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def type_args(text: str) -> list[str]:
|
|
121
|
+
"""`[issues.Issue, int]` -> the arguments, split at top-level commas."""
|
|
122
|
+
text = text.strip()
|
|
123
|
+
if text.startswith("[") and text.endswith("]"):
|
|
124
|
+
text = text[1:-1]
|
|
125
|
+
out, depth, cur = [], 0, []
|
|
126
|
+
for c in text:
|
|
127
|
+
if c in "[({":
|
|
128
|
+
depth += 1
|
|
129
|
+
elif c in "])}":
|
|
130
|
+
depth -= 1
|
|
131
|
+
if c == "," and depth == 0:
|
|
132
|
+
out.append("".join(cur).strip())
|
|
133
|
+
cur = []
|
|
134
|
+
else:
|
|
135
|
+
cur.append(c)
|
|
136
|
+
if "".join(cur).strip():
|
|
137
|
+
out.append("".join(cur).strip())
|
|
138
|
+
return out
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def call_type_args(call: Node) -> list[str]:
|
|
142
|
+
"""Explicit type arguments of a call: `db.Find[issues.Issue](...)`, `db.GetByID[User](...)`."""
|
|
143
|
+
targs = call.child_by_field_name("type_arguments")
|
|
144
|
+
if targs is not None:
|
|
145
|
+
return type_args(_txt(targs))
|
|
146
|
+
fn = call.child_by_field_name("function")
|
|
147
|
+
if fn is not None and fn.type == "index_expression":
|
|
148
|
+
index = fn.child_by_field_name("index")
|
|
149
|
+
return [_txt(index)] if index is not None else []
|
|
150
|
+
return []
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# ---------------------------------------------------------------------------------------- naming
|
|
154
|
+
|
|
155
|
+
def gonic_name(name: str) -> str:
|
|
156
|
+
"""xorm's GonicMapper and GORM's default naming: `RepoID` -> repo_id, `HTTPServer` -> http_server."""
|
|
157
|
+
s = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name)
|
|
158
|
+
s = re.sub(r"([a-z\d])([A-Z])", r"\1_\2", s)
|
|
159
|
+
return s.lower()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
_GORM_INITIALISMS = ["API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM",
|
|
163
|
+
"RHS", "RPC", "SLA", "SMTP", "SSH", "TLS", "TTL", "UID", "UI", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XSRF", "XSS"]
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def gorm_name(name: str) -> str:
|
|
167
|
+
"""GORM's NamingStrategy.toDBName, as written in gorm/schema/naming.go: common initialisms count as one word
|
|
168
|
+
(`UserID` -> user_id, `IPv6` -> ipv6, `DNSLabel` -> dns_label)."""
|
|
169
|
+
if not name:
|
|
170
|
+
return ""
|
|
171
|
+
out, i = [], 0
|
|
172
|
+
while i < len(name):
|
|
173
|
+
for ini in _GORM_INITIALISMS:
|
|
174
|
+
if name.startswith(ini, i):
|
|
175
|
+
out.append(ini[0] + ini[1:].lower())
|
|
176
|
+
i += len(ini)
|
|
177
|
+
break
|
|
178
|
+
else:
|
|
179
|
+
out.append(name[i])
|
|
180
|
+
i += 1
|
|
181
|
+
value = "".join(out)
|
|
182
|
+
upper = lambda c: "A" <= c <= "Z" # noqa: E731
|
|
183
|
+
buf: list[str] = []
|
|
184
|
+
last, cur = False, upper(value[0])
|
|
185
|
+
for i, v in enumerate(value[:-1]):
|
|
186
|
+
nxt, next_number = upper(value[i + 1]), value[i + 1].isdigit()
|
|
187
|
+
if cur:
|
|
188
|
+
if last and (nxt or next_number):
|
|
189
|
+
buf.append(v.lower())
|
|
190
|
+
else:
|
|
191
|
+
if i > 0 and value[i - 1] != "_" and value[i + 1] != "_":
|
|
192
|
+
buf.append("_")
|
|
193
|
+
buf.append(v.lower())
|
|
194
|
+
else:
|
|
195
|
+
buf.append(v)
|
|
196
|
+
last, cur = cur, nxt
|
|
197
|
+
if cur:
|
|
198
|
+
if not last and len(value) > 1:
|
|
199
|
+
buf.append("_")
|
|
200
|
+
buf.append(value[-1].lower())
|
|
201
|
+
else:
|
|
202
|
+
buf.append(value[-1])
|
|
203
|
+
return "".join(buf)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def snake_name(name: str) -> str:
|
|
207
|
+
"""xorm's default SnakeMapper: every capital starts a word (`RepoID` -> repo_i_d)."""
|
|
208
|
+
return re.sub(r"(?<!^)([A-Z])", r"_\1", name).lower()
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
_UNCOUNTABLE = {"equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "jeans", "police"}
|
|
212
|
+
_IRREGULAR = {"person": "people", "man": "men", "child": "children", "sex": "sexes", "move": "moves", "mombie": "mombies",
|
|
213
|
+
"criterion": "criteria"}
|
|
214
|
+
_PLURAL = [(r"(quiz)$", r"\1zes"), (r"^(oxen)$", r"\1"), (r"^(ox)$", r"\1en"), (r"(matr|vert|ind)(?:ix|ex)$", r"\1ices"),
|
|
215
|
+
(r"(x|ch|ss|sh)$", r"\1es"), (r"([^aeiouy]|qu)y$", r"\1ies"), (r"(hive)$", r"\1s"),
|
|
216
|
+
(r"(?:([^f])fe|([lr])f)$", r"\1\2ves"), (r"sis$", "ses"), (r"([ti])a$", r"\1a"), (r"([ti])um$", r"\1a"),
|
|
217
|
+
(r"(buffal|tomat)o$", r"\1oes"), (r"(bu)s$", r"\1ses"), (r"(alias|status|campus)$", r"\1es"),
|
|
218
|
+
(r"(octop|vir)i$", r"\1i"), (r"(octop|vir)us$", r"\1i"), (r"(ax|test)is$", r"\1es"), (r"s$", "s"), (r"$", "s")]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def plural(word: str) -> str:
|
|
222
|
+
"""GORM's table naming (jinzhu/inflection), for the last word of a snake-case name."""
|
|
223
|
+
head, _, last = word.rpartition("_")
|
|
224
|
+
lead = head + "_" if head else ""
|
|
225
|
+
if last in _UNCOUNTABLE:
|
|
226
|
+
return word
|
|
227
|
+
if last in _IRREGULAR:
|
|
228
|
+
return lead + _IRREGULAR[last]
|
|
229
|
+
for pat, rep in _PLURAL:
|
|
230
|
+
if re.search(pat, last):
|
|
231
|
+
return lead + re.sub(pat, rep, last)
|
|
232
|
+
return word
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# Words a statement cannot use bare as a table or column name. The ORMs quote every identifier; the SQL written
|
|
236
|
+
# here quotes only these, so it stays readable and still parses.
|
|
237
|
+
RESERVED = frozenset("""all analyse analyze and any array as asc asymmetric both case cast check collate column constraint create
|
|
238
|
+
current_date current_time current_timestamp current_user default deferrable desc distinct do else end except false fetch for foreign
|
|
239
|
+
from grant group having in index initially intersect into key lateral leading limit localtime localtimestamp not null offset on only
|
|
240
|
+
or order placing primary references returning select session_user some symmetric table then to trailing true union unique user using
|
|
241
|
+
variadic when where window with values set update delete insert join left right inner outer full cross natural is like between exists
|
|
242
|
+
""".split())
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def ident(name: str) -> str:
|
|
246
|
+
"""A model's table or column name as it can be written in a statement."""
|
|
247
|
+
return f'"{name}"' if name.lower() in RESERVED and re.fullmatch(r"\w+", name) else name
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# ---------------------------------------------------------------------------------------- models
|
|
251
|
+
|
|
252
|
+
@dataclass
|
|
253
|
+
class Col:
|
|
254
|
+
name: str
|
|
255
|
+
field: str
|
|
256
|
+
type: str = ""
|
|
257
|
+
pk: bool = False
|
|
258
|
+
autoincr: bool = False
|
|
259
|
+
role: str = "" # created | updated | deleted | version
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@dataclass
|
|
263
|
+
class Rel:
|
|
264
|
+
field: str
|
|
265
|
+
kind: str # has_many | has_one | belongs_to | many2many
|
|
266
|
+
target: TypeRef
|
|
267
|
+
foreign_key: str = "" # field name, when the tag says it
|
|
268
|
+
references: str = ""
|
|
269
|
+
join_table: str = ""
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@dataclass
|
|
273
|
+
class Model:
|
|
274
|
+
name: str
|
|
275
|
+
dir: str
|
|
276
|
+
lib: str
|
|
277
|
+
table: str
|
|
278
|
+
table_basis: str # TableName | convention
|
|
279
|
+
cols: list[Col] = field(default_factory=list)
|
|
280
|
+
indexes: list[dict] = field(default_factory=list)
|
|
281
|
+
relations: dict[str, Rel] = field(default_factory=dict)
|
|
282
|
+
defined_at: str = ""
|
|
283
|
+
alias: str = "" # bun: the table alias its statements use (`table:users,alias:u`, else the struct's name)
|
|
284
|
+
tagged: bool = False # some field carries the library's tag
|
|
285
|
+
used: bool = False # a statement was written for it
|
|
286
|
+
|
|
287
|
+
def col(self, field_name: str) -> Col | None:
|
|
288
|
+
for c in self.cols:
|
|
289
|
+
if c.field == field_name:
|
|
290
|
+
return c
|
|
291
|
+
return None
|
|
292
|
+
|
|
293
|
+
@property
|
|
294
|
+
def pk(self) -> list[str]:
|
|
295
|
+
return [c.name for c in self.cols if c.pk]
|
|
296
|
+
|
|
297
|
+
def role(self, role: str) -> str:
|
|
298
|
+
return next((c.name for c in self.cols if c.role == role), "")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
_TAG = re.compile(r'(\w+):"((?:[^"\\]|\\.)*)"')
|
|
302
|
+
_XORM_INDEX = re.compile(r"^(index|unique)(?:\(([^)]*)\))?$", re.I)
|
|
303
|
+
# xorm tag words that are not a column name: options, and SQL types (xorm's schemas.SqlTypes). Any other bare word
|
|
304
|
+
# in an `xorm:"..."` tag names the column (a field `Title` tagged `xorm:"name"` is stored in column `name`).
|
|
305
|
+
_XORM_WORDS = frozenset("""pk autoincr null notnull not unique index extends created updated deleted version default comment utc local
|
|
306
|
+
json bson noautotime collate""".split())
|
|
307
|
+
_XORM_TYPES = frozenset("""bit unsignedbit tinyint unsignedtinyint smallint unsignedsmallint mediumint unsignedmediumint int unsignedint
|
|
308
|
+
integer bigint unsignedbigint enum set char varchar nchar nvarchar tinytext text ntext clob mediumtext longtext uuid uniqueidentifier
|
|
309
|
+
sysname date datetime smalldatetime time timestamp timestampz year decimal numeric money smallmoney real float double binary varbinary
|
|
310
|
+
tinyblob blob mediumblob longblob bytea bool boolean serial bigserial json jsonb xml array unsigned""".split())
|
|
311
|
+
_GO_SCALARS = {"string", "bool", "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64",
|
|
312
|
+
"float32", "float64", "byte", "rune", "any", "interface{}", "error"}
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def struct_tags(tag_node: Node | None) -> dict[str, str]:
|
|
316
|
+
if tag_node is None:
|
|
317
|
+
return {}
|
|
318
|
+
text = _txt(tag_node)
|
|
319
|
+
if text.startswith('"'): # an interpreted string: the quotes inside are escaped
|
|
320
|
+
text = text[1:-1].replace('\\"', '"')
|
|
321
|
+
return {m.group(1): m.group(2) for m in _TAG.finditer(text.strip("`"))}
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
class Types:
|
|
325
|
+
"""Declarations of every package of one run, and what can be read off them."""
|
|
326
|
+
|
|
327
|
+
def __init__(self, ctx):
|
|
328
|
+
self.ctx = ctx
|
|
329
|
+
self.decls: dict[str, dict[str, tuple[GoFile, Node]]] = defaultdict(dict)
|
|
330
|
+
self.methods: dict[str, dict[tuple[str, str], tuple[GoFile, Node]]] = defaultdict(dict)
|
|
331
|
+
self.funcs: dict[str, dict[str, tuple[GoFile, Node]]] = defaultdict(dict)
|
|
332
|
+
self.libs: set[str] = set()
|
|
333
|
+
self.local: dict[tuple[str, str], list[Node]] = {}
|
|
334
|
+
self.xorm_gonic = False
|
|
335
|
+
self._lib_cache: dict[tuple[str, str], tuple[str, str] | None] = {}
|
|
336
|
+
self._model_cache: dict[tuple[str, str, str], Model | None] = {}
|
|
337
|
+
self._type_cache: dict[tuple[str, int, int], TypeRef | None] = {}
|
|
338
|
+
self._busy: set = set()
|
|
339
|
+
self._bun_shaped: dict[str, bool] = {}
|
|
340
|
+
files = sorted(ctx.files.values(), key=lambda f: (f.test, f.rel)) # application code declares first
|
|
341
|
+
for gf in files:
|
|
342
|
+
for path in gf.imports.values():
|
|
343
|
+
lib = import_lib(path)
|
|
344
|
+
if lib:
|
|
345
|
+
self.libs.add(lib)
|
|
346
|
+
if b"GonicMapper" in gf.src:
|
|
347
|
+
self.xorm_gonic = True
|
|
348
|
+
for n in gf.root.named_children:
|
|
349
|
+
if n.type == "type_declaration":
|
|
350
|
+
for spec in n.named_children:
|
|
351
|
+
nm = spec.child_by_field_name("name")
|
|
352
|
+
if spec.type in ("type_spec", "type_alias") and nm is not None:
|
|
353
|
+
self.decls[gf.dir].setdefault(_txt(nm), (gf, spec))
|
|
354
|
+
elif n.type == "function_declaration":
|
|
355
|
+
nm = n.child_by_field_name("name")
|
|
356
|
+
if nm is not None:
|
|
357
|
+
self.funcs[gf.dir].setdefault(_txt(nm), (gf, n))
|
|
358
|
+
self._local_types(gf, n)
|
|
359
|
+
elif n.type == "method_declaration":
|
|
360
|
+
nm = n.child_by_field_name("name")
|
|
361
|
+
if nm is not None:
|
|
362
|
+
self.methods[gf.dir].setdefault((recv_type(n), _txt(nm)), (gf, n))
|
|
363
|
+
self._local_types(gf, n) # a type declared inside a method body is a model too
|
|
364
|
+
if any(self.bun_shaped(d) for d in list(self.methods)):
|
|
365
|
+
self.libs.add("bun")
|
|
366
|
+
|
|
367
|
+
def _local_types(self, gf: GoFile, func: Node) -> None:
|
|
368
|
+
if b"type " not in gf.src[func.start_byte: func.end_byte]:
|
|
369
|
+
return
|
|
370
|
+
stack = [func]
|
|
371
|
+
while stack:
|
|
372
|
+
n = stack.pop()
|
|
373
|
+
if n.type == "type_declaration":
|
|
374
|
+
for spec in n.named_children:
|
|
375
|
+
nm = spec.child_by_field_name("name")
|
|
376
|
+
if spec.type in ("type_spec", "type_alias") and nm is not None:
|
|
377
|
+
self.local.setdefault((gf.rel, _txt(nm)), []).append(spec)
|
|
378
|
+
continue
|
|
379
|
+
stack.extend(n.children)
|
|
380
|
+
|
|
381
|
+
def _local_key(self, gf: GoFile, name: str) -> str | None:
|
|
382
|
+
"""A type one function of this file declares, when the file declares that name once."""
|
|
383
|
+
specs = self.local.get((gf.rel, name))
|
|
384
|
+
if not specs or len(specs) != 1:
|
|
385
|
+
return None
|
|
386
|
+
key = f"{name}@{gf.rel}"
|
|
387
|
+
self.decls[gf.dir].setdefault(key, (gf, specs[0]))
|
|
388
|
+
return key
|
|
389
|
+
|
|
390
|
+
# ---- names -------------------------------------------------------------------------
|
|
391
|
+
def named(self, ref: TypeRef | None) -> tuple[str, str] | None:
|
|
392
|
+
"""(package directory, type name) of a type declared in this repository."""
|
|
393
|
+
if ref is None:
|
|
394
|
+
return None
|
|
395
|
+
base = base_type(ref.text)[0].split("[")[0].strip()
|
|
396
|
+
if "@" in base and base in self.decls.get(ref.gf.dir, {}):
|
|
397
|
+
return (ref.gf.dir, base)
|
|
398
|
+
if not re.fullmatch(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?", base):
|
|
399
|
+
return None
|
|
400
|
+
if "." in base:
|
|
401
|
+
alias, name = base.split(".", 1)
|
|
402
|
+
path = ref.gf.imports.get(alias)
|
|
403
|
+
target = self.ctx.import_dir(ref.gf.dir, path) if path else None
|
|
404
|
+
return (target, name) if target is not None else None
|
|
405
|
+
if base in self.decls.get(ref.gf.dir, {}):
|
|
406
|
+
return (ref.gf.dir, base)
|
|
407
|
+
local = self._local_key(ref.gf, base) if "@" not in base else None
|
|
408
|
+
return (ref.gf.dir, local) if local else None
|
|
409
|
+
|
|
410
|
+
def external(self, ref: TypeRef | None) -> tuple[str, str] | None:
|
|
411
|
+
"""(import path, type name) of a type that another module declares."""
|
|
412
|
+
if ref is None:
|
|
413
|
+
return None
|
|
414
|
+
base = base_type(ref.text)[0].split("[")[0].strip()
|
|
415
|
+
if "." not in base:
|
|
416
|
+
return None
|
|
417
|
+
alias, name = base.split(".", 1)
|
|
418
|
+
path = ref.gf.imports.get(alias)
|
|
419
|
+
return (path, name) if path else None
|
|
420
|
+
|
|
421
|
+
def decl(self, ref: TypeRef | None) -> tuple[GoFile, Node] | None:
|
|
422
|
+
key = self.named(ref)
|
|
423
|
+
return self.decls.get(key[0], {}).get(key[1]) if key else None
|
|
424
|
+
|
|
425
|
+
def struct_node(self, ref: TypeRef | None) -> tuple[GoFile, Node] | None:
|
|
426
|
+
hit = self.decl(ref)
|
|
427
|
+
if hit is None:
|
|
428
|
+
return None
|
|
429
|
+
typ = hit[1].child_by_field_name("type")
|
|
430
|
+
return (hit[0], typ) if typ is not None and typ.type == "struct_type" else None
|
|
431
|
+
|
|
432
|
+
def fields(self, ref: TypeRef | None) -> list[tuple[str, str, dict, GoFile, Node]]:
|
|
433
|
+
"""(field name or "" when embedded, type text, tags, file, node) of a struct declared here."""
|
|
434
|
+
hit = self.struct_node(ref)
|
|
435
|
+
if hit is None:
|
|
436
|
+
return []
|
|
437
|
+
gf, typ = hit
|
|
438
|
+
out = []
|
|
439
|
+
for lst in typ.named_children:
|
|
440
|
+
for fd in lst.named_children:
|
|
441
|
+
if fd.type != "field_declaration":
|
|
442
|
+
continue
|
|
443
|
+
ftyp = fd.child_by_field_name("type")
|
|
444
|
+
if ftyp is None:
|
|
445
|
+
continue
|
|
446
|
+
tags = struct_tags(fd.child_by_field_name("tag"))
|
|
447
|
+
names = [_txt(c) for c in fd.children_by_field_name("name")]
|
|
448
|
+
for name in names or [""]:
|
|
449
|
+
out.append((name, _txt(ftyp), tags, gf, fd))
|
|
450
|
+
return out
|
|
451
|
+
|
|
452
|
+
def elem(self, ref: TypeRef | None, depth: int = 0) -> TypeRef | None:
|
|
453
|
+
"""Element type of a slice, array or map value, through a named type (`type IssueList []*Issue`)."""
|
|
454
|
+
if ref is None or depth > 4:
|
|
455
|
+
return None
|
|
456
|
+
el = elem_type(ref.text)
|
|
457
|
+
if el:
|
|
458
|
+
return TypeRef(el, ref.gf)
|
|
459
|
+
hit = self.decl(ref)
|
|
460
|
+
if hit is None:
|
|
461
|
+
return None
|
|
462
|
+
typ = hit[1].child_by_field_name("type")
|
|
463
|
+
if typ is None or typ.type in ("struct_type", "interface_type"):
|
|
464
|
+
return None
|
|
465
|
+
return self.elem(TypeRef(_txt(typ), hit[0]), depth + 1)
|
|
466
|
+
|
|
467
|
+
def field_type(self, ref: TypeRef | None, name: str, depth: int = 0) -> TypeRef | None:
|
|
468
|
+
"""Type of `x.name`, through embedded structs."""
|
|
469
|
+
if ref is None or depth > 4:
|
|
470
|
+
return None
|
|
471
|
+
if ref.text.lstrip("*").lstrip().startswith("struct"): # `var in struct { Article *Article }`
|
|
472
|
+
m = re.search(rf"(?:[{{;\n]|^)\s*{re.escape(name)}\s+([^\s`;}}]+)", ref.text.lstrip("*").lstrip()[6:])
|
|
473
|
+
return TypeRef(m.group(1), ref.gf) if m else None
|
|
474
|
+
embedded = []
|
|
475
|
+
for fname, ftype, _tags, gf, _fd in self.fields(ref):
|
|
476
|
+
if fname == name:
|
|
477
|
+
return TypeRef(ftype, gf)
|
|
478
|
+
if not fname:
|
|
479
|
+
if base_type(ftype)[0].split(".")[-1] == name:
|
|
480
|
+
return TypeRef(ftype, gf)
|
|
481
|
+
embedded.append(TypeRef(ftype, gf))
|
|
482
|
+
for e in embedded:
|
|
483
|
+
hit = self.field_type(e, name, depth + 1)
|
|
484
|
+
if hit is not None:
|
|
485
|
+
return hit
|
|
486
|
+
return None
|
|
487
|
+
|
|
488
|
+
def method(self, ref: TypeRef | None, name: str, depth: int = 0) -> tuple[GoFile, Node] | None:
|
|
489
|
+
"""The method `name` of a type declared here: its own, an embedded struct's, or an interface's."""
|
|
490
|
+
key = self.named(ref)
|
|
491
|
+
if key is None or depth > 4:
|
|
492
|
+
return None
|
|
493
|
+
hit = self.methods.get(key[0], {}).get((key[1], name))
|
|
494
|
+
if hit is not None:
|
|
495
|
+
return hit
|
|
496
|
+
declared = self.decls.get(key[0], {}).get(key[1])
|
|
497
|
+
if declared is None:
|
|
498
|
+
return None
|
|
499
|
+
gf, spec = declared
|
|
500
|
+
typ = spec.child_by_field_name("type")
|
|
501
|
+
if typ is None:
|
|
502
|
+
return None
|
|
503
|
+
if typ.type == "struct_type":
|
|
504
|
+
for fname, ftype, _tags, fgf, _fd in self.fields(ref):
|
|
505
|
+
if not fname:
|
|
506
|
+
hit = self.method(TypeRef(ftype, fgf), name, depth + 1)
|
|
507
|
+
if hit is not None:
|
|
508
|
+
return hit
|
|
509
|
+
elif typ.type == "interface_type":
|
|
510
|
+
for el in typ.named_children:
|
|
511
|
+
if el.type in ("method_elem", "method_spec"):
|
|
512
|
+
nm = el.child_by_field_name("name")
|
|
513
|
+
if nm is not None and _txt(nm) == name:
|
|
514
|
+
return gf, el
|
|
515
|
+
elif el.type in ("type_elem", "constraint_elem", "type_identifier", "qualified_type"):
|
|
516
|
+
hit = self.method(TypeRef(_txt(el), gf), name, depth + 1)
|
|
517
|
+
if hit is not None:
|
|
518
|
+
return hit
|
|
519
|
+
elif typ.type in ("type_identifier", "qualified_type", "pointer_type", "generic_type"):
|
|
520
|
+
return self.method(TypeRef(_txt(typ), gf), name, depth + 1)
|
|
521
|
+
return None
|
|
522
|
+
|
|
523
|
+
@staticmethod
|
|
524
|
+
def result_type(gf: GoFile, func: Node, index: int = 0) -> TypeRef | None:
|
|
525
|
+
result = func.child_by_field_name("result")
|
|
526
|
+
if result is None:
|
|
527
|
+
return None
|
|
528
|
+
if result.type != "parameter_list":
|
|
529
|
+
return TypeRef(_txt(result), gf) if index <= 0 else None
|
|
530
|
+
types: list[str] = []
|
|
531
|
+
for p in result.named_children:
|
|
532
|
+
typ = p.child_by_field_name("type")
|
|
533
|
+
if typ is None:
|
|
534
|
+
continue
|
|
535
|
+
types.extend([_txt(typ)] * max(1, len(p.children_by_field_name("name"))))
|
|
536
|
+
index = max(index, 0)
|
|
537
|
+
return TypeRef(types[index], gf) if index < len(types) else None
|
|
538
|
+
|
|
539
|
+
@staticmethod
|
|
540
|
+
def type_params(func: Node) -> list[str]:
|
|
541
|
+
tp = func.child_by_field_name("type_parameters")
|
|
542
|
+
out: list[str] = []
|
|
543
|
+
for p in (tp.named_children if tp is not None else ()):
|
|
544
|
+
out.extend(_txt(c) for c in p.children_by_field_name("name"))
|
|
545
|
+
return out
|
|
546
|
+
|
|
547
|
+
# ---- libraries ---------------------------------------------------------------------
|
|
548
|
+
def lib_of(self, ref: TypeRef | None, depth: int = 0) -> tuple[str, str] | None:
|
|
549
|
+
"""(library, kind of value) when the type is a library's builder or session, or a local type that
|
|
550
|
+
wraps one (an interface whose methods return `*xorm.Session`, a struct that embeds `*gorm.DB`)."""
|
|
551
|
+
if ref is None or depth > 4:
|
|
552
|
+
return None
|
|
553
|
+
ext = self.external(ref)
|
|
554
|
+
if ext is not None:
|
|
555
|
+
lib = import_lib(ext[0])
|
|
556
|
+
if lib:
|
|
557
|
+
kind = LIB_TYPES.get(lib, {}).get(ext[1].split("[")[0])
|
|
558
|
+
return (lib, kind) if kind else None
|
|
559
|
+
key = self.named(ref)
|
|
560
|
+
if key is None:
|
|
561
|
+
return None
|
|
562
|
+
if key[1] in BUN_SHAPED_TYPES and self.bun_shaped(key[0]):
|
|
563
|
+
return ("bun", BUN_SHAPED_TYPES[key[1]])
|
|
564
|
+
if key in self._lib_cache:
|
|
565
|
+
return self._lib_cache[key]
|
|
566
|
+
self._lib_cache[key] = None
|
|
567
|
+
declared = self.decls.get(key[0], {}).get(key[1])
|
|
568
|
+
found = None
|
|
569
|
+
if declared is not None:
|
|
570
|
+
gf, spec = declared
|
|
571
|
+
typ = spec.child_by_field_name("type")
|
|
572
|
+
if typ is not None and typ.type == "interface_type":
|
|
573
|
+
votes: dict[tuple[str, str], int] = defaultdict(int)
|
|
574
|
+
for el in typ.named_children:
|
|
575
|
+
if el.type in ("method_elem", "method_spec"):
|
|
576
|
+
got = self.result_type(gf, el)
|
|
577
|
+
hit = self.lib_of(got, depth + 1) if got is not None else None
|
|
578
|
+
else:
|
|
579
|
+
hit = self.lib_of(TypeRef(_txt(el), gf), depth + 1)
|
|
580
|
+
if hit is not None and hit[1] in ("session", "stmt"):
|
|
581
|
+
votes[hit] += 1
|
|
582
|
+
if votes:
|
|
583
|
+
found = max(votes, key=votes.get)
|
|
584
|
+
elif typ is not None and typ.type == "struct_type":
|
|
585
|
+
for fname, ftype, _tags, fgf, _fd in self.fields(ref):
|
|
586
|
+
if not fname:
|
|
587
|
+
hit = self.lib_of(TypeRef(ftype, fgf), depth + 1)
|
|
588
|
+
if hit is not None and hit[1] in ("session", "stmt"):
|
|
589
|
+
found = hit
|
|
590
|
+
break
|
|
591
|
+
elif typ is not None:
|
|
592
|
+
found = self.lib_of(TypeRef(_txt(typ), gf), depth + 1)
|
|
593
|
+
self._lib_cache[key] = found
|
|
594
|
+
return found
|
|
595
|
+
|
|
596
|
+
def bun_shaped(self, dir_: str) -> bool:
|
|
597
|
+
"""A package of this repository that declares bun's API itself: `DB.NewSelect()` and a `SelectQuery`."""
|
|
598
|
+
hit = self._bun_shaped.get(dir_)
|
|
599
|
+
if hit is None:
|
|
600
|
+
ms = self.methods.get(dir_, {})
|
|
601
|
+
hit = self._bun_shaped[dir_] = ("DB", "NewSelect") in ms and "SelectQuery" in self.decls.get(dir_, {})
|
|
602
|
+
return hit
|
|
603
|
+
|
|
604
|
+
# ---- expression types --------------------------------------------------------------
|
|
605
|
+
def type_of(self, gf: GoFile, node: Node | None, at: Node | None = None, depth: int = 0) -> TypeRef | None:
|
|
606
|
+
node = _strip_parens(node)
|
|
607
|
+
if node is None or depth > DEPTH:
|
|
608
|
+
return None
|
|
609
|
+
key = (gf.rel, node.id, at.id if at is not None else 0)
|
|
610
|
+
if key in self._type_cache:
|
|
611
|
+
return self._type_cache[key]
|
|
612
|
+
if key in self._busy:
|
|
613
|
+
return None
|
|
614
|
+
self._busy.add(key)
|
|
615
|
+
try:
|
|
616
|
+
out = self._type_of(gf, node, at if at is not None else node, depth)
|
|
617
|
+
finally:
|
|
618
|
+
self._busy.discard(key)
|
|
619
|
+
self._type_cache[key] = out
|
|
620
|
+
return out
|
|
621
|
+
|
|
622
|
+
def _type_of(self, gf: GoFile, node: Node, at: Node, depth: int) -> TypeRef | None: # noqa: C901
|
|
623
|
+
t = node.type
|
|
624
|
+
if t == "unary_expression":
|
|
625
|
+
inner = self.type_of(gf, node.child_by_field_name("operand"), at, depth + 1)
|
|
626
|
+
if inner is None:
|
|
627
|
+
return None
|
|
628
|
+
op = _txt(node.children[0]) if node.children else ""
|
|
629
|
+
if op == "&":
|
|
630
|
+
return TypeRef("*" + inner.text, inner.gf)
|
|
631
|
+
if op == "*":
|
|
632
|
+
return TypeRef(inner.text.lstrip("*"), inner.gf)
|
|
633
|
+
return inner
|
|
634
|
+
if t == "composite_literal":
|
|
635
|
+
typ = node.child_by_field_name("type")
|
|
636
|
+
return TypeRef(_txt(typ), gf) if typ is not None else None
|
|
637
|
+
if t == "type_assertion_expression" or t == "type_conversion_expression":
|
|
638
|
+
typ = node.child_by_field_name("type")
|
|
639
|
+
return TypeRef(_txt(typ), gf) if typ is not None else None
|
|
640
|
+
if t == "index_expression":
|
|
641
|
+
return self.elem(self.type_of(gf, node.child_by_field_name("operand"), at, depth + 1))
|
|
642
|
+
if t == "slice_expression":
|
|
643
|
+
return self.type_of(gf, node.child_by_field_name("operand"), at, depth + 1)
|
|
644
|
+
if t == "identifier":
|
|
645
|
+
return self._ident_type(gf, node, at, depth)
|
|
646
|
+
if t == "selector_expression":
|
|
647
|
+
operand, fld = node.child_by_field_name("operand"), node.child_by_field_name("field")
|
|
648
|
+
if operand is None or fld is None:
|
|
649
|
+
return None
|
|
650
|
+
if operand.type == "identifier" and _txt(operand) in gf.imports and gf._local(_txt(operand), at) is None:
|
|
651
|
+
target = self.ctx.import_dir(gf.dir, gf.imports[_txt(operand)])
|
|
652
|
+
return self._package_var(target, _txt(fld), depth) if target is not None else None
|
|
653
|
+
return self.field_type(self.type_of(gf, operand, at, depth + 1), _txt(fld))
|
|
654
|
+
if t == "call_expression":
|
|
655
|
+
return self._call_type(gf, node, at, depth)
|
|
656
|
+
return None
|
|
657
|
+
|
|
658
|
+
def _package_var(self, dir: str, name: str, depth: int) -> TypeRef | None:
|
|
659
|
+
hit = self.ctx.pkg_decls.get(dir, {}).get(name)
|
|
660
|
+
if hit is None:
|
|
661
|
+
return None
|
|
662
|
+
owner = hit[0]
|
|
663
|
+
for n in owner.root.named_children:
|
|
664
|
+
if n.type not in ("var_declaration", "const_declaration"):
|
|
665
|
+
continue
|
|
666
|
+
for spec in n.named_children:
|
|
667
|
+
specs = spec.named_children if spec.type == "var_spec_list" else [spec]
|
|
668
|
+
for s in specs:
|
|
669
|
+
if s.type in ("var_spec", "const_spec") and any(_txt(c) == name for c in s.children_by_field_name("name")):
|
|
670
|
+
typ = s.child_by_field_name("type")
|
|
671
|
+
if typ is not None:
|
|
672
|
+
return TypeRef(_txt(typ), owner)
|
|
673
|
+
value = s.child_by_field_name("value")
|
|
674
|
+
vals = value.named_children if value is not None else []
|
|
675
|
+
return self.type_of(owner, vals[0], vals[0], depth + 1) if len(vals) == 1 else None
|
|
676
|
+
return None
|
|
677
|
+
|
|
678
|
+
def _ident_type(self, gf: GoFile, node: Node, at: Node, depth: int) -> TypeRef | None:
|
|
679
|
+
name = _txt(node)
|
|
680
|
+
local = gf._local(name, at)
|
|
681
|
+
if local is None:
|
|
682
|
+
if name in ("nil", "true", "false"):
|
|
683
|
+
return None
|
|
684
|
+
named_result = self._named_result(gf, node, name)
|
|
685
|
+
if named_result is not None:
|
|
686
|
+
return named_result
|
|
687
|
+
return self._package_var(gf.dir, name, depth)
|
|
688
|
+
_top, decl, _later = local
|
|
689
|
+
if decl.kind == "param":
|
|
690
|
+
func = decl.node
|
|
691
|
+
typ = param_type(func, name)
|
|
692
|
+
if typ:
|
|
693
|
+
return TypeRef(typ, gf)
|
|
694
|
+
recv = func.child_by_field_name("receiver")
|
|
695
|
+
if recv is not None:
|
|
696
|
+
for p in recv.named_children:
|
|
697
|
+
if any(_txt(c) == name for c in p.children_by_field_name("name")):
|
|
698
|
+
ptyp = p.child_by_field_name("type")
|
|
699
|
+
return TypeRef(_txt(ptyp), gf) if ptyp is not None else None
|
|
700
|
+
return None
|
|
701
|
+
if decl.kind == "range":
|
|
702
|
+
clause = decl.node
|
|
703
|
+
right = clause.child_by_field_name("right")
|
|
704
|
+
left = clause.child_by_field_name("left")
|
|
705
|
+
n_left = len(left.named_children) if left is not None else 0
|
|
706
|
+
inner = self.type_of(gf, right, clause, depth + 1)
|
|
707
|
+
if inner is None:
|
|
708
|
+
return None
|
|
709
|
+
if decl.index == 1 and n_left == 2: # `for _, v := range xs`: the element
|
|
710
|
+
return self.elem(inner)
|
|
711
|
+
return None
|
|
712
|
+
spec = decl.node
|
|
713
|
+
if spec.type in ("var_spec", "const_spec"):
|
|
714
|
+
typ = spec.child_by_field_name("type")
|
|
715
|
+
if typ is not None:
|
|
716
|
+
return TypeRef(_txt(typ), gf)
|
|
717
|
+
if decl.value is None:
|
|
718
|
+
return None
|
|
719
|
+
if decl.index >= 0:
|
|
720
|
+
return self._call_type(gf, decl.value, decl.node, depth + 1, decl.index) if decl.value.type == "call_expression" else None
|
|
721
|
+
return self.type_of(gf, decl.value, decl.node, depth + 1)
|
|
722
|
+
|
|
723
|
+
@staticmethod
|
|
724
|
+
def _named_result(gf: GoFile, node: Node, name: str) -> TypeRef | None:
|
|
725
|
+
n = node.parent
|
|
726
|
+
while n is not None:
|
|
727
|
+
if n.type in ("function_declaration", "method_declaration", "func_literal"):
|
|
728
|
+
result = n.child_by_field_name("result")
|
|
729
|
+
if result is not None and result.type == "parameter_list":
|
|
730
|
+
for p in result.named_children:
|
|
731
|
+
if any(_txt(c) == name for c in p.children_by_field_name("name")):
|
|
732
|
+
typ = p.child_by_field_name("type")
|
|
733
|
+
return TypeRef(_txt(typ), gf) if typ is not None else None
|
|
734
|
+
n = n.parent
|
|
735
|
+
return None
|
|
736
|
+
|
|
737
|
+
def callee(self, gf: GoFile, call: Node, at: Node | None = None, depth: int = 0) -> tuple[GoFile, Node] | None:
|
|
738
|
+
"""The declaration a call means, when the source decides it: a function of this or an imported package,
|
|
739
|
+
or a method of a receiver whose type is known. An interface method resolves to its declaration in the
|
|
740
|
+
interface, which has no body."""
|
|
741
|
+
fn = call.child_by_field_name("function")
|
|
742
|
+
name, recv, _dotted = callee_name(fn)
|
|
743
|
+
if not name:
|
|
744
|
+
return None
|
|
745
|
+
at = at if at is not None else call
|
|
746
|
+
if recv is None:
|
|
747
|
+
return self.funcs.get(gf.dir, {}).get(name)
|
|
748
|
+
if recv.type == "identifier" and _txt(recv) in gf.imports and gf._local(_txt(recv), at) is None:
|
|
749
|
+
target = self.ctx.import_dir(gf.dir, gf.imports[_txt(recv)])
|
|
750
|
+
return self.funcs.get(target, {}).get(name) if target is not None else None
|
|
751
|
+
return self.method(self.type_of(gf, recv, at, depth + 1), name)
|
|
752
|
+
|
|
753
|
+
def _call_type(self, gf: GoFile, node: Node, at: Node, depth: int, index: int = 0) -> TypeRef | None:
|
|
754
|
+
fn = node.child_by_field_name("function")
|
|
755
|
+
name, recv, _dotted = callee_name(fn)
|
|
756
|
+
args = call_args(node)
|
|
757
|
+
if recv is None and name == "new" and args:
|
|
758
|
+
return TypeRef("*" + _txt(args[0]), gf)
|
|
759
|
+
if recv is None and name == "make" and args:
|
|
760
|
+
return TypeRef(_txt(args[0]), gf)
|
|
761
|
+
if recv is None and name == "append" and args:
|
|
762
|
+
return self.type_of(gf, args[0], at, depth + 1)
|
|
763
|
+
if not name:
|
|
764
|
+
return None
|
|
765
|
+
hit = self.callee(gf, node, at, depth)
|
|
766
|
+
if hit is None:
|
|
767
|
+
if recv is not None and name not in NOT_CHAINING:
|
|
768
|
+
# a builder's own methods return the builder; the ones that run the statement do not
|
|
769
|
+
inner = self.type_of(gf, recv, at, depth + 1)
|
|
770
|
+
if inner is not None and self.lib_of(inner) is not None:
|
|
771
|
+
return inner
|
|
772
|
+
return None
|
|
773
|
+
out = self.result_type(hit[0], hit[1], index)
|
|
774
|
+
if out is None:
|
|
775
|
+
return None
|
|
776
|
+
params = self.type_params(hit[1]) if hit[1].type in FUNC_DECL else []
|
|
777
|
+
given = call_type_args(node) if params else []
|
|
778
|
+
if params and given:
|
|
779
|
+
text = out.text
|
|
780
|
+
for p, g in zip(params, given):
|
|
781
|
+
text = re.sub(rf"\b{re.escape(p)}\b", g, text)
|
|
782
|
+
if text != out.text:
|
|
783
|
+
return TypeRef(text, gf) # the arguments are written in the caller's file
|
|
784
|
+
return out
|
|
785
|
+
|
|
786
|
+
# ---- models ------------------------------------------------------------------------
|
|
787
|
+
def model(self, ref: TypeRef | None, lib: str, depth: int = 0) -> Model | None:
|
|
788
|
+
if ref is not None and ref.text.strip().lstrip("*").startswith("map[") and depth < 4:
|
|
789
|
+
return self.model(self.elem(ref), lib, depth + 1)
|
|
790
|
+
key = self.named(ref)
|
|
791
|
+
if key is None:
|
|
792
|
+
return None
|
|
793
|
+
if self.struct_node(ref) is None and depth < 4:
|
|
794
|
+
declared = self.decls.get(key[0], {}).get(key[1])
|
|
795
|
+
if declared is None:
|
|
796
|
+
return None
|
|
797
|
+
dgf, spec = declared
|
|
798
|
+
el = self.elem(TypeRef(key[1], dgf))
|
|
799
|
+
if el is not None:
|
|
800
|
+
return self.model(el, lib, depth + 1)
|
|
801
|
+
typ = spec.child_by_field_name("type")
|
|
802
|
+
if typ is not None and typ.type in ("type_identifier", "qualified_type"):
|
|
803
|
+
return self._derived_model(key, TypeRef(_txt(typ), dgf), lib, depth)
|
|
804
|
+
return None
|
|
805
|
+
ck = (key[0], key[1], lib)
|
|
806
|
+
if ck not in self._model_cache:
|
|
807
|
+
self._model_cache[ck] = None
|
|
808
|
+
hit = self.struct_node(ref)
|
|
809
|
+
if hit is not None:
|
|
810
|
+
base = TypeRef(key[1], hit[0])
|
|
811
|
+
self._model_cache[ck] = (self._gorm_model(base, key) if lib == "gorm" else
|
|
812
|
+
self._bun_model(base, key) if lib == "bun" else self._xorm_model(base, key))
|
|
813
|
+
return self._model_cache[ck]
|
|
814
|
+
|
|
815
|
+
def _derived_model(self, key: tuple[str, str], base: TypeRef, lib: str, depth: int) -> Model | None:
|
|
816
|
+
"""`type Organization User`: the fields of the base struct, the table of the new type."""
|
|
817
|
+
ck = (key[0], key[1], lib)
|
|
818
|
+
if ck in self._model_cache:
|
|
819
|
+
return self._model_cache[ck]
|
|
820
|
+
self._model_cache[ck] = None
|
|
821
|
+
inner = self.model(base, lib, depth + 1)
|
|
822
|
+
if inner is None:
|
|
823
|
+
return None
|
|
824
|
+
dgf, spec = self.decls[key[0]][key[1]]
|
|
825
|
+
named = self._table_name(TypeRef(key[1], dgf), key)
|
|
826
|
+
if named is None:
|
|
827
|
+
named = (plural(gorm_name(key[1])) if lib == "gorm" else plural(gonic_name(key[1])) if lib == "bun"
|
|
828
|
+
else (gonic_name if self.xorm_gonic else snake_name)(key[1]))
|
|
829
|
+
m = Model(name=key[1], dir=key[0], lib=lib, table=named, table_basis="TableName", cols=list(inner.cols),
|
|
830
|
+
indexes=[], relations=dict(inner.relations), defined_at=f"{dgf.rel}:{spec.start_point[0] + 1}")
|
|
831
|
+
self._model_cache[ck] = m
|
|
832
|
+
return m
|
|
833
|
+
|
|
834
|
+
def _table_name(self, ref: TypeRef, key: tuple[str, str]) -> str | None:
|
|
835
|
+
"""The string a `TableName()` method returns, when it returns one literal."""
|
|
836
|
+
hit = self.methods.get(key[0], {}).get((key[1], "TableName"))
|
|
837
|
+
if hit is None:
|
|
838
|
+
return None
|
|
839
|
+
gf, func = hit
|
|
840
|
+
body = func.child_by_field_name("body")
|
|
841
|
+
if body is None:
|
|
842
|
+
return None
|
|
843
|
+
found = []
|
|
844
|
+
stack = [body]
|
|
845
|
+
while stack:
|
|
846
|
+
n = stack.pop()
|
|
847
|
+
if n.type == "return_statement":
|
|
848
|
+
found.append(n)
|
|
849
|
+
elif n.type != "func_literal":
|
|
850
|
+
stack.extend(n.children)
|
|
851
|
+
if len(found) != 1:
|
|
852
|
+
return None
|
|
853
|
+
exprs = [c for c in found[0].named_children]
|
|
854
|
+
value = exprs[0].named_children[0] if exprs and exprs[0].type == "expression_list" and exprs[0].named_children else None
|
|
855
|
+
res = gf.resolve(value, found[0], 0) if value is not None else None
|
|
856
|
+
if res is None or res.dynamic or not re.fullmatch(r"[\w.\"`]+", res.text):
|
|
857
|
+
return None
|
|
858
|
+
return res.text.strip("\"`")
|
|
859
|
+
|
|
860
|
+
def _xorm_model(self, ref: TypeRef, key: tuple[str, str]) -> Model:
|
|
861
|
+
gf, spec = self.decls[key[0]][key[1]]
|
|
862
|
+
mapper = gonic_name if self.xorm_gonic else snake_name
|
|
863
|
+
named = self._table_name(ref, key)
|
|
864
|
+
m = Model(name=key[1].split("@")[0], dir=key[0], lib="xorm", table=named or mapper(key[1].split("@")[0]),
|
|
865
|
+
table_basis="TableName" if named else "convention", defined_at=f"{gf.rel}:{spec.start_point[0] + 1}")
|
|
866
|
+
groups: dict[tuple[str, bool], list[str]] = {}
|
|
867
|
+
self._xorm_fields(ref, m, groups, mapper, 0)
|
|
868
|
+
for (name, unique), cols in groups.items():
|
|
869
|
+
m.indexes.append({"name": name, "columns": cols, "unique": unique})
|
|
870
|
+
m.indexes.extend(self._table_indices(key))
|
|
871
|
+
return m
|
|
872
|
+
|
|
873
|
+
def _xorm_fields(self, ref: TypeRef, m: Model, groups: dict, mapper, depth: int) -> None:
|
|
874
|
+
for fname, ftype, tags, fgf, _fd in self.fields(ref):
|
|
875
|
+
tag = tags.get("xorm")
|
|
876
|
+
if tag is not None:
|
|
877
|
+
m.tagged = True
|
|
878
|
+
tokens = re.findall(r"'[^']*'|[^\s]+\([^)]*\)|[^\s]+", tag or "")
|
|
879
|
+
low = [tok.lower() for tok in tokens]
|
|
880
|
+
if "-" in low:
|
|
881
|
+
continue
|
|
882
|
+
if "extends" in low:
|
|
883
|
+
if depth < 4:
|
|
884
|
+
self._xorm_fields(TypeRef(ftype, fgf), m, groups, mapper, depth + 1)
|
|
885
|
+
continue
|
|
886
|
+
if not fname or not fname[0].isupper():
|
|
887
|
+
continue
|
|
888
|
+
quoted = next((tok[1:-1] for tok in tokens if tok.startswith("'") and tok.endswith("'") and len(tok) > 2), "")
|
|
889
|
+
if not quoted:
|
|
890
|
+
for i, tok in enumerate(tokens):
|
|
891
|
+
word = tok.split("(")[0].lower()
|
|
892
|
+
if word in _XORM_WORDS or word in _XORM_TYPES or (i and low[i - 1] == "default") or tok in ("<-", "->"):
|
|
893
|
+
continue
|
|
894
|
+
if re.fullmatch(r"[A-Za-z_]\w*", tok):
|
|
895
|
+
quoted = tok
|
|
896
|
+
break
|
|
897
|
+
col = Col(name=quoted or mapper(fname), field=fname, type=ftype)
|
|
898
|
+
col.pk = "pk" in low
|
|
899
|
+
col.autoincr = "autoincr" in low
|
|
900
|
+
col.role = next((r for r in ("created", "updated", "deleted", "version") if r in low), "")
|
|
901
|
+
for tok in tokens:
|
|
902
|
+
im = _XORM_INDEX.match(tok)
|
|
903
|
+
if not im:
|
|
904
|
+
continue
|
|
905
|
+
unique = im.group(1).lower() == "unique"
|
|
906
|
+
name = (im.group(2) or "").strip() or f"{'UQE' if unique else 'IDX'}_{m.table}_{col.name}"
|
|
907
|
+
groups.setdefault((name, unique), []).append(col.name)
|
|
908
|
+
m.cols.append(col)
|
|
909
|
+
|
|
910
|
+
def _table_indices(self, key: tuple[str, str]) -> list[dict]:
|
|
911
|
+
"""Indexes a `TableIndices()` method builds with `schemas.NewIndex(name, type)` and `AddColumn(...)`."""
|
|
912
|
+
hit = self.methods.get(key[0], {}).get((key[1], "TableIndices"))
|
|
913
|
+
if hit is None:
|
|
914
|
+
return []
|
|
915
|
+
text = _txt(hit[1])
|
|
916
|
+
out = []
|
|
917
|
+
for im in re.finditer(r"(\w+)\s*:?=\s*\w+\.NewIndex\(\s*\"([^\"]+)\"\s*,\s*\w+\.(\w+)\s*\)", text):
|
|
918
|
+
cols: list[str] = []
|
|
919
|
+
for am in re.finditer(rf"\b{re.escape(im.group(1))}\.AddColumn\(([^)]*)\)", text):
|
|
920
|
+
cols.extend(re.findall(r"\"([^\"]+)\"", am.group(1)))
|
|
921
|
+
if cols:
|
|
922
|
+
out.append({"name": im.group(2), "columns": cols, "unique": im.group(3).lower().startswith("unique")})
|
|
923
|
+
return out
|
|
924
|
+
|
|
925
|
+
def _gorm_model(self, ref: TypeRef, key: tuple[str, str]) -> Model:
|
|
926
|
+
gf, spec = self.decls[key[0]][key[1]]
|
|
927
|
+
named = self._table_name(ref, key)
|
|
928
|
+
m = Model(name=key[1].split("@")[0], dir=key[0], lib="gorm", table=named or plural(gorm_name(key[1].split("@")[0])),
|
|
929
|
+
table_basis="TableName" if named else "convention", defined_at=f"{gf.rel}:{spec.start_point[0] + 1}")
|
|
930
|
+
groups: dict[tuple[str, bool], list[str]] = {}
|
|
931
|
+
self._gorm_fields(ref, m, groups, "", 0)
|
|
932
|
+
if not any(c.pk for c in m.cols):
|
|
933
|
+
for c in m.cols:
|
|
934
|
+
if c.name == "id":
|
|
935
|
+
c.pk = True
|
|
936
|
+
for (name, unique), cols in groups.items():
|
|
937
|
+
m.indexes.append({"name": name, "columns": cols, "unique": unique})
|
|
938
|
+
return m
|
|
939
|
+
|
|
940
|
+
def _gorm_fields(self, ref: TypeRef, m: Model, groups: dict, prefix: str, depth: int) -> None: # noqa: C901
|
|
941
|
+
for fname, ftype, tags, fgf, _fd in self.fields(ref):
|
|
942
|
+
tag = tags.get("gorm")
|
|
943
|
+
if tag is not None:
|
|
944
|
+
m.tagged = True
|
|
945
|
+
opts: dict[str, str] = {}
|
|
946
|
+
for part in (tag or "").split(";"):
|
|
947
|
+
k, _, v = part.partition(":")
|
|
948
|
+
if k.strip():
|
|
949
|
+
opts[k.strip().lower()] = v.strip()
|
|
950
|
+
if "-" in opts or (tag or "").strip() == "-":
|
|
951
|
+
continue
|
|
952
|
+
fref = TypeRef(ftype, fgf)
|
|
953
|
+
ext = self.external(fref)
|
|
954
|
+
bare, many = base_type(ftype)
|
|
955
|
+
if not fname or "embedded" in opts:
|
|
956
|
+
if ext is not None and import_lib(ext[0]) == "gorm" and ext[1] == "Model":
|
|
957
|
+
m.cols.extend([Col("id", "ID", "uint", pk=True, autoincr=True), Col("created_at", "CreatedAt", "time.Time", role="created"),
|
|
958
|
+
Col("updated_at", "UpdatedAt", "time.Time", role="updated"),
|
|
959
|
+
Col("deleted_at", "DeletedAt", "gorm.DeletedAt", role="deleted")])
|
|
960
|
+
elif depth < 4 and self.struct_node(fref) is not None:
|
|
961
|
+
self._gorm_fields(fref, m, groups, prefix + opts.get("embeddedprefix", ""), depth + 1)
|
|
962
|
+
continue
|
|
963
|
+
if not fname[0].isupper():
|
|
964
|
+
continue
|
|
965
|
+
stored = any(k in opts for k in ("serializer", "type", "column")) or bare in _GO_SCALARS
|
|
966
|
+
target = self.struct_node(fref)
|
|
967
|
+
if target is not None and not stored and not self._is_valuer(fref) and bare != m.name + "_":
|
|
968
|
+
kind = "many2many" if "many2many" in opts else ("has_many" if many else "has_one")
|
|
969
|
+
fk = opts.get("foreignkey", "")
|
|
970
|
+
if not many and "many2many" not in opts:
|
|
971
|
+
own_fk = fk or fname + "ID"
|
|
972
|
+
if any(f[0] == own_fk for f in self.fields(ref)):
|
|
973
|
+
kind = "belongs_to"
|
|
974
|
+
m.relations[fname] = Rel(fname, kind, fref, fk, opts.get("references", ""), opts.get("many2many", ""))
|
|
975
|
+
continue
|
|
976
|
+
col = Col(name=prefix + (opts.get("column") or gorm_name(fname)), field=fname, type=ftype)
|
|
977
|
+
col.pk = "primarykey" in opts or "primary_key" in opts
|
|
978
|
+
col.autoincr = "autoincrement" in opts
|
|
979
|
+
if ext is not None and import_lib(ext[0]) == "gorm" and ext[1] == "DeletedAt":
|
|
980
|
+
col.role = "deleted"
|
|
981
|
+
elif fname in ("CreatedAt", "UpdatedAt") and "autocreatetime" not in opts:
|
|
982
|
+
col.role = "created" if fname == "CreatedAt" else "updated"
|
|
983
|
+
for k, unique in (("index", False), ("uniqueindex", True), ("unique", True)):
|
|
984
|
+
if k in opts:
|
|
985
|
+
spec = opts[k].split(",")
|
|
986
|
+
name = spec[0].strip() or f"idx_{m.table}_{col.name}"
|
|
987
|
+
unique = unique or any(s.strip().lower() == "unique" for s in spec[1:])
|
|
988
|
+
groups.setdefault((name, unique), []).append(col.name)
|
|
989
|
+
m.cols.append(col)
|
|
990
|
+
|
|
991
|
+
# ---- bun -------------------------------------------------------------------------
|
|
992
|
+
def _bun_model(self, ref: TypeRef, key: tuple[str, str]) -> Model:
|
|
993
|
+
"""bun's struct mapping: `bun:"table:name,alias:x"` on the embedded bun.BaseModel, else the struct name
|
|
994
|
+
underscored and pluralised (alias: underscored); a field's column is the first part of its `bun` tag, else
|
|
995
|
+
its name underscored; anonymous structs are embedded; `rel:` fields are relations, not columns."""
|
|
996
|
+
gf, spec = self.decls[key[0]][key[1]]
|
|
997
|
+
name = key[1].split("@")[0]
|
|
998
|
+
m = Model(name=name, dir=key[0], lib="bun", table="", table_basis="convention",
|
|
999
|
+
defined_at=f"{gf.rel}:{spec.start_point[0] + 1}")
|
|
1000
|
+
self._bun_fields(ref, m, "", 0)
|
|
1001
|
+
if not m.table:
|
|
1002
|
+
named = self._table_name(ref, key)
|
|
1003
|
+
m.table, m.table_basis = (named, "TableName") if named else (plural(gonic_name(name)), "convention")
|
|
1004
|
+
else:
|
|
1005
|
+
m.table_basis = "tag"
|
|
1006
|
+
m.alias = m.alias or gonic_name(name)
|
|
1007
|
+
if not any(c.pk for c in m.cols):
|
|
1008
|
+
for c in m.cols:
|
|
1009
|
+
if c.name == "id":
|
|
1010
|
+
c.pk = True
|
|
1011
|
+
return m
|
|
1012
|
+
|
|
1013
|
+
def _bun_fields(self, ref: TypeRef, m: Model, prefix: str, depth: int) -> None: # noqa: C901
|
|
1014
|
+
for fname, ftype, tags, fgf, _fd in self.fields(ref):
|
|
1015
|
+
tag = tags.get("bun", tags.get("ch")) # go-clickhouse models (`ch.CHModel`) are tagged `ch:"..."`
|
|
1016
|
+
parts = [p.strip() for p in (tag or "").split(",")]
|
|
1017
|
+
first = parts[0] if parts else ""
|
|
1018
|
+
opts: dict[str, str] = {}
|
|
1019
|
+
for p in parts[1:]:
|
|
1020
|
+
k, _, v = p.partition(":")
|
|
1021
|
+
if k:
|
|
1022
|
+
opts[k] = v
|
|
1023
|
+
if ":" in first: # `bun:"table:users,alias:u"`: no column name, options only
|
|
1024
|
+
k, _, v = first.partition(":")
|
|
1025
|
+
opts[k] = v
|
|
1026
|
+
first = ""
|
|
1027
|
+
fref = TypeRef(ftype, fgf)
|
|
1028
|
+
ext = self.external(fref)
|
|
1029
|
+
if not fname:
|
|
1030
|
+
if ext is not None and (import_lib(ext[0]) == "bun" and ext[1] == "BaseModel" or ext[1] == "CHModel"):
|
|
1031
|
+
m.tagged = True
|
|
1032
|
+
if first and not m.table: # `bun:"dashboards,alias:d"`: the first part names the table
|
|
1033
|
+
m.table = first.strip("\"'`")
|
|
1034
|
+
if opts.get("table") and not m.table:
|
|
1035
|
+
m.table = opts["table"].strip("\"'`")
|
|
1036
|
+
if opts.get("alias") and not m.alias:
|
|
1037
|
+
m.alias = opts["alias"].strip("\"'`")
|
|
1038
|
+
elif depth < 4 and self.struct_node(fref) is not None:
|
|
1039
|
+
self._bun_fields(fref, m, prefix + opts.get("embed", ""), depth + 1)
|
|
1040
|
+
continue
|
|
1041
|
+
if tag is not None:
|
|
1042
|
+
m.tagged = True
|
|
1043
|
+
if first == "-" or not fname[0].isupper():
|
|
1044
|
+
continue
|
|
1045
|
+
if "rel" in opts:
|
|
1046
|
+
kind = {"has-one": "has_one", "belongs-to": "belongs_to", "has-many": "has_many", "m2m": "many2many"}.get(opts["rel"], opts["rel"])
|
|
1047
|
+
m.relations[fname] = Rel(fname, kind, fref, opts.get("join", ""), "", opts.get("m2m", ""))
|
|
1048
|
+
continue
|
|
1049
|
+
if "embed" in opts and self.struct_node(fref) is not None and depth < 4:
|
|
1050
|
+
self._bun_fields(fref, m, prefix + opts["embed"], depth + 1)
|
|
1051
|
+
continue
|
|
1052
|
+
col = Col(name=prefix + (first or gonic_name(fname)), field=fname, type=opts.get("type") or ftype)
|
|
1053
|
+
col.pk = "pk" in opts
|
|
1054
|
+
col.autoincr = "autoincrement" in opts or "identity" in opts
|
|
1055
|
+
if "soft_delete" in opts:
|
|
1056
|
+
col.role = "deleted"
|
|
1057
|
+
elif "scanonly" in opts:
|
|
1058
|
+
col.role = "scanonly"
|
|
1059
|
+
m.cols.append(col)
|
|
1060
|
+
|
|
1061
|
+
def _is_valuer(self, ref: TypeRef) -> bool:
|
|
1062
|
+
key = self.named(ref)
|
|
1063
|
+
if key is None:
|
|
1064
|
+
return False
|
|
1065
|
+
ms = self.methods.get(key[0], {})
|
|
1066
|
+
return (key[1], "Scan") in ms or (key[1], "Value") in ms or (key[1], "GormDataType") in ms
|
|
1067
|
+
|
|
1068
|
+
def tagged_models(self) -> list[Model]:
|
|
1069
|
+
"""Every struct that carries an ORM tag, as a model: the schema the project declares in Go."""
|
|
1070
|
+
out = []
|
|
1071
|
+
for dir_, names in self.decls.items():
|
|
1072
|
+
for name, (gf, spec) in names.items():
|
|
1073
|
+
typ = spec.child_by_field_name("type")
|
|
1074
|
+
if typ is None or typ.type != "struct_type" or gf.test:
|
|
1075
|
+
continue
|
|
1076
|
+
text = _txt(typ)
|
|
1077
|
+
for lib in ("xorm", "gorm", "bun"):
|
|
1078
|
+
if (f'{lib}:"' in text or lib == "bun" and "CHModel" in text) and lib in self.libs:
|
|
1079
|
+
m = self.model(TypeRef(name, gf), lib)
|
|
1080
|
+
if m is not None and m.cols:
|
|
1081
|
+
out.append(m)
|
|
1082
|
+
return out
|