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,2134 @@
|
|
|
1
|
+
"""Go ORMs and query builders: the SQL a call chain stands for.
|
|
2
|
+
|
|
3
|
+
xorm (sessions, `xorm.io/builder` conditions, model structs), GORM, squirrel, go-sqlbuilder. A chain such as
|
|
4
|
+
`db.GetEngine(ctx).Where("repo_id = ?", id).Find(&issues)` has no SQL string anywhere; this module follows the
|
|
5
|
+
chain, the variables it is assembled in, and the model struct behind it, and writes the statement the library
|
|
6
|
+
would send. ent reads are translated in orm_ent.py, bun chains in orm_go_bun.py; goqu is counted, not translated.
|
|
7
|
+
|
|
8
|
+
What is written follows the shared convention for ORM sites:
|
|
9
|
+
|
|
10
|
+
- a site is a RawSite with `resolution: "orm"` and an `orm` object {library, model_or_table, operation,
|
|
11
|
+
confidence, notes};
|
|
12
|
+
- tables and columns are the real ones (TableName(), struct tags, the library's naming rule);
|
|
13
|
+
- a part that an `if` decides, or a value the source does not say, is a «run-time part». A conditional filter
|
|
14
|
+
is written `AND («predicate»)` so the predicate stays readable;
|
|
15
|
+
- a call the library runs as several statements (FindAndCount, Preload) gives one site per statement;
|
|
16
|
+
- when the model, the table or the base of a builder cannot be determined nothing is written: the call is
|
|
17
|
+
counted with its reason in `summary.orm`.
|
|
18
|
+
|
|
19
|
+
A function that runs a statement on a model its caller chooses (`func Find[T any](ctx, opts FindOptions)`,
|
|
20
|
+
`func Insert(ctx, beans ...any)`) is a wrapper: the site is written at each caller, with the caller's model and
|
|
21
|
+
conditions. A call inside a loop to a function that loads rows is reported at the loop, once per statement it
|
|
22
|
+
runs, as the N+1 it is.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import copy
|
|
28
|
+
import re
|
|
29
|
+
from collections import Counter, defaultdict
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
|
|
32
|
+
from tree_sitter import Node
|
|
33
|
+
|
|
34
|
+
from .base import PLACEHOLDER, RawSite, trim
|
|
35
|
+
from .go import (CASE_TYPES, FUNC_DECL, STRING_TYPES, GoFile, _strip_parens, _txt, _within, call_args,
|
|
36
|
+
callee_name, decode_string, param_names, param_type)
|
|
37
|
+
from . import orm_go_types as T
|
|
38
|
+
from .orm_go_types import Model, TypeRef, Types
|
|
39
|
+
|
|
40
|
+
# ---- settings (`[discover]` in codecop.toml) --------------------------------------------------------------------
|
|
41
|
+
# Longest source text kept inside one run-time part: `orm_marker_chars`.
|
|
42
|
+
DEFAULT_MARKER_CHARS = 240
|
|
43
|
+
MARKER_CHARS = DEFAULT_MARKER_CHARS
|
|
44
|
+
# How many rounds wrappers of wrappers are followed: `orm_wrapper_rounds`.
|
|
45
|
+
DEFAULT_WRAPPER_ROUNDS = 4
|
|
46
|
+
WRAPPER_ROUNDS = DEFAULT_WRAPPER_ROUNDS
|
|
47
|
+
# How many calls down from a loop a row-loading function is looked for, and the most statements one call in a
|
|
48
|
+
# loop is reported with: `orm_loop_hops`, `orm_loop_statements`. 0 hops turns the loop sites off.
|
|
49
|
+
DEFAULT_LOOP_HOPS = 2
|
|
50
|
+
LOOP_HOPS = DEFAULT_LOOP_HOPS
|
|
51
|
+
DEFAULT_LOOP_STATEMENTS = 12
|
|
52
|
+
LOOP_STATEMENTS = DEFAULT_LOOP_STATEMENTS
|
|
53
|
+
# Whether test files are translated too: `orm_in_tests`. Off by default: a test's statements are never ranked, and
|
|
54
|
+
# test suites of ORM projects hold several times more calls than the application.
|
|
55
|
+
IN_TESTS = False
|
|
56
|
+
|
|
57
|
+
TRANSLATED = ("xorm", "gorm", "squirrel", "sqlbuilder", "xbuilder", "bun")
|
|
58
|
+
MUTABLE = ("xorm", "sqlbuilder", "bun") # a method call changes the receiver; the others return a new value
|
|
59
|
+
|
|
60
|
+
TERMINALS = {
|
|
61
|
+
"xorm": {"Find", "Get", "Count", "Exist", "Iterate", "Rows", "FindAndCount", "Insert", "InsertOne", "InsertMulti",
|
|
62
|
+
"Update", "Delete", "Truncate", "Sum", "SumInt", "Sums", "SumsInt"},
|
|
63
|
+
"gorm": {"First", "Take", "Last", "Find", "FindInBatches", "Count", "Pluck", "Scan", "Row", "Rows", "Create",
|
|
64
|
+
"CreateInBatches", "Save", "Update", "Updates", "UpdateColumn", "UpdateColumns", "Delete", "FirstOrCreate",
|
|
65
|
+
"FirstOrInit"},
|
|
66
|
+
"squirrel": {"ToSql", "MustSql", "Query", "QueryRow", "Exec", "Scan", "QueryContext", "QueryRowContext", "ExecContext",
|
|
67
|
+
"ScanContext"},
|
|
68
|
+
"sqlbuilder": {"Build", "BuildWithFlavor"},
|
|
69
|
+
"xbuilder": {"ToSQL", "ToBoundSQL"},
|
|
70
|
+
"bun": {"Scan", "Exec", "Count", "Exists", "ScanAndCount", "Rows"},
|
|
71
|
+
"goqu": {"ToSQL", "Executor", "ScanStructs", "ScanStruct", "ScanVals", "ScanVal", "Exec", "Count", "Pluck"},
|
|
72
|
+
}
|
|
73
|
+
RAW_TERMINALS = {"xorm": {"Exec", "Query", "QueryString", "QueryInterface", "QuerySliceString"}, "gorm": {"Exec", "Raw"}}
|
|
74
|
+
ALL_TERMINALS = set().union(*TERMINALS.values())
|
|
75
|
+
T.NOT_CHAINING.update(ALL_TERMINALS - {"Update", "Delete", "Insert"}) # squirrel and bun build with these names
|
|
76
|
+
ASSOC_TERMINALS = {"Find", "Append", "Replace", "Delete", "Clear", "Count"}
|
|
77
|
+
ENT_BUILD = {"Query", "Create", "CreateBulk", "Update", "UpdateOne", "UpdateOneID", "Delete", "DeleteOne", "DeleteOneID"}
|
|
78
|
+
ENT_TERMINALS = {"All", "AllX", "Only", "OnlyX", "First", "FirstX", "Count", "CountX", "Exist", "ExistX", "IDs", "IDsX", "Save",
|
|
79
|
+
"SaveX", "Exec", "ExecX", "OnlyID", "FirstID"}
|
|
80
|
+
EXECUTOR = re.compile(r"Builder|Sqlizer")
|
|
81
|
+
FLAVORS = {"ClickHouse": "clickhouse", "PostgreSQL": "postgres", "MySQL": "mysql", "SQLite": "sqlite", "SQLServer": "mssql",
|
|
82
|
+
"Oracle": "oracle"}
|
|
83
|
+
TOK = "\x01"
|
|
84
|
+
TOKEN = re.compile(r"\x01([PM]):([^\x01]*)\x01")
|
|
85
|
+
DEFER_OPEN, DEFER_CLOSE, EMPTY = "\x03", "\x04", "\x05"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def marker(text: str) -> str:
|
|
89
|
+
"""A run-time part: one line, no nested markers, no closing mark inside."""
|
|
90
|
+
text = PLACEHOLDER.sub("…", " ".join(text.split())).replace("«", "<").replace("»", ">").replace("{", "{ ").replace("*/", "* /")
|
|
91
|
+
if len(text) > MARKER_CHARS:
|
|
92
|
+
text = text[: MARKER_CHARS - 1] + "…"
|
|
93
|
+
return "«" + text + "»"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _is_marker(text: str) -> bool:
|
|
97
|
+
return bool(re.fullmatch(r"«[^»]*»", text.strip()))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _has_top_or(text: str) -> bool:
|
|
101
|
+
depth = 0
|
|
102
|
+
for m in re.finditer(r"[()]|\bOR\b", PLACEHOLDER.sub("x", text), re.I):
|
|
103
|
+
if m.group(0) == "(":
|
|
104
|
+
depth += 1
|
|
105
|
+
elif m.group(0) == ")":
|
|
106
|
+
depth -= 1
|
|
107
|
+
elif depth == 0:
|
|
108
|
+
return True
|
|
109
|
+
return False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _paren(text: str) -> str:
|
|
113
|
+
return f"({text})" if _has_top_or(text) or _is_marker(text) else text
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class Cond:
|
|
117
|
+
"""A predicate: SQL text, "" for the empty condition."""
|
|
118
|
+
__slots__ = ("text",)
|
|
119
|
+
|
|
120
|
+
def __init__(self, text: str = ""):
|
|
121
|
+
self.text = text
|
|
122
|
+
|
|
123
|
+
def clone(self) -> "Cond":
|
|
124
|
+
return Cond(self.text)
|
|
125
|
+
|
|
126
|
+
def and_(self, other: str) -> None:
|
|
127
|
+
if other:
|
|
128
|
+
self.text = f"{_paren(self.text)} AND {_paren(other)}" if self.text else other
|
|
129
|
+
|
|
130
|
+
def or_(self, other: str) -> None:
|
|
131
|
+
if other:
|
|
132
|
+
self.text = f"({self.text}) OR ({other})" if self.text else other
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Q:
|
|
136
|
+
"""A statement under construction."""
|
|
137
|
+
|
|
138
|
+
def __init__(self, lib: str, kind: str = ""):
|
|
139
|
+
self.lib = lib
|
|
140
|
+
self.kind = kind # select | insert | update | delete | "" (not decided yet)
|
|
141
|
+
self.table = "" # as written after FROM / INTO / UPDATE
|
|
142
|
+
self.alias = ""
|
|
143
|
+
self.model: Model | None = None
|
|
144
|
+
self.cols: list[str] = []
|
|
145
|
+
self.omit: list[str] = []
|
|
146
|
+
self.distinct = False
|
|
147
|
+
self.joins: list[str] = []
|
|
148
|
+
self.where = ""
|
|
149
|
+
self.use_pk = False # xorm .ID(x): the model's primary key = ?
|
|
150
|
+
self.group: list[str] = []
|
|
151
|
+
self.having: list[str] = []
|
|
152
|
+
self.order: list[str] = []
|
|
153
|
+
self.limit = ""
|
|
154
|
+
self.offset = ""
|
|
155
|
+
self.sets: list[str] = []
|
|
156
|
+
self.ins_cols: list[str] | None = None
|
|
157
|
+
self.ins_select = ""
|
|
158
|
+
self.options: list[str] = []
|
|
159
|
+
self.prefix: list[str] = []
|
|
160
|
+
self.suffix: list[str] = []
|
|
161
|
+
self.tail: list[str] = [] # run-time parts that are not predicates
|
|
162
|
+
self.preloads: list[str] = []
|
|
163
|
+
self.flags: set[str] = set()
|
|
164
|
+
self.notes: list[str] = []
|
|
165
|
+
self.opaque = "" # why the base of this builder is unknown ("" when it is known)
|
|
166
|
+
self.cond_mode = False # operations applied now are decided at run time
|
|
167
|
+
self.engine = ""
|
|
168
|
+
self.assoc = ""
|
|
169
|
+
self.union = "" # a complete statement text (UNION of builders)
|
|
170
|
+
self.dynamic = False # something other than a conditional filter is a run-time part
|
|
171
|
+
|
|
172
|
+
def clone(self) -> "Q":
|
|
173
|
+
c = copy.copy(self)
|
|
174
|
+
for k, v in self.__dict__.items():
|
|
175
|
+
if isinstance(v, (list, set)):
|
|
176
|
+
setattr(c, k, type(v)(v))
|
|
177
|
+
return c
|
|
178
|
+
|
|
179
|
+
TEXT_FIELDS = ("table", "alias", "where", "limit", "offset", "ins_select", "union")
|
|
180
|
+
LIST_FIELDS = ("cols", "joins", "group", "having", "order", "sets", "prefix", "suffix", "tail")
|
|
181
|
+
|
|
182
|
+
def map_text(self, fn) -> None:
|
|
183
|
+
"""Rewrite every piece of SQL text this statement holds."""
|
|
184
|
+
for k in self.TEXT_FIELDS:
|
|
185
|
+
setattr(self, k, fn(getattr(self, k)))
|
|
186
|
+
for k in self.LIST_FIELDS:
|
|
187
|
+
setattr(self, k, [fn(x) for x in getattr(self, k)])
|
|
188
|
+
if self.ins_cols is not None:
|
|
189
|
+
self.ins_cols = [fn(x) for x in self.ins_cols]
|
|
190
|
+
|
|
191
|
+
def all_text(self) -> str:
|
|
192
|
+
parts = [getattr(self, k) for k in self.TEXT_FIELDS]
|
|
193
|
+
for k in self.LIST_FIELDS:
|
|
194
|
+
parts.extend(getattr(self, k))
|
|
195
|
+
return "\n".join(parts + (self.ins_cols or []))
|
|
196
|
+
|
|
197
|
+
def and_(self, text: str) -> None:
|
|
198
|
+
if text:
|
|
199
|
+
self.where = f"{_paren(self.where)} AND {_paren(text)}" if self.where else _paren(text) if _is_marker(text) else text
|
|
200
|
+
|
|
201
|
+
def or_(self, text: str) -> None:
|
|
202
|
+
if text:
|
|
203
|
+
self.where = f"({self.where}) OR ({text})" if self.where else text
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@dataclass
|
|
207
|
+
class Stmt:
|
|
208
|
+
sql: str
|
|
209
|
+
operation: str
|
|
210
|
+
target: str # model or table
|
|
211
|
+
confidence: str = "high"
|
|
212
|
+
notes: list[str] = field(default_factory=list)
|
|
213
|
+
engine: str = ""
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@dataclass
|
|
217
|
+
class OrmSite(RawSite):
|
|
218
|
+
orm: dict | None = None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class Env:
|
|
222
|
+
"""Values that stand in for names while an expression is evaluated."""
|
|
223
|
+
__slots__ = ("cur", "params")
|
|
224
|
+
|
|
225
|
+
def __init__(self, cur: dict | None = None, params: dict | None = None):
|
|
226
|
+
self.cur = cur or {} # the variable being folded: its state so far
|
|
227
|
+
self.params = params or {} # arguments bound to the parameters of a function being read
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@dataclass
|
|
231
|
+
class Template:
|
|
232
|
+
"""A statement inside a wrapper: its model or conditions come from the wrapper's caller."""
|
|
233
|
+
gf: GoFile
|
|
234
|
+
func: Node
|
|
235
|
+
q: Q
|
|
236
|
+
name: str
|
|
237
|
+
args: list[Node]
|
|
238
|
+
call: Node
|
|
239
|
+
lib: str
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@dataclass
|
|
243
|
+
class Stats:
|
|
244
|
+
seen: Counter = field(default_factory=Counter)
|
|
245
|
+
seen_tests: Counter = field(default_factory=Counter)
|
|
246
|
+
emitted: Counter = field(default_factory=Counter)
|
|
247
|
+
statements: Counter = field(default_factory=Counter)
|
|
248
|
+
reasons: dict = field(default_factory=lambda: defaultdict(Counter))
|
|
249
|
+
untranslated: list = field(default_factory=list) # (library, file, line, reason, detail)
|
|
250
|
+
raw: Counter = field(default_factory=Counter) # raw SQL sent through the library: the string extractor's
|
|
251
|
+
errors: int = 0
|
|
252
|
+
loop_sites: int = 0
|
|
253
|
+
wrapper_calls: int = 0
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class Unresolved(Exception):
|
|
257
|
+
"""This call cannot be written as SQL; the message is the reason that is counted."""
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class Ev:
|
|
261
|
+
def __init__(self, ctx, types: Types):
|
|
262
|
+
self.ctx = ctx
|
|
263
|
+
self.types = types
|
|
264
|
+
self.stats = Stats()
|
|
265
|
+
self.sites: list[OrmSite] = []
|
|
266
|
+
self.templates: dict[tuple[str, str, str], list[Template]] = defaultdict(list)
|
|
267
|
+
self.template_names: set[str] = set()
|
|
268
|
+
self._muts: dict[str, dict[tuple[int, str], list[Node]]] = {}
|
|
269
|
+
self._inline_memo: dict[int, object] = {}
|
|
270
|
+
self._inline_busy: set[int] = set()
|
|
271
|
+
self._field_inits: dict[str, dict[str, list[tuple[GoFile, Node, Node]]]] = {}
|
|
272
|
+
self.by_func: dict[tuple[str, int], list[OrmSite]] = defaultdict(list) # (file, function node id) -> sites
|
|
273
|
+
self.replaced: set[tuple[str, str, str]] = set() # (file, symbol, variable) a builder's SQL went to
|
|
274
|
+
self.replaced_by: dict[tuple[str, str, str], object] = {} # ... and the builder's site that stands for it
|
|
275
|
+
self._depth = 0
|
|
276
|
+
|
|
277
|
+
# ================================================================ evaluation
|
|
278
|
+
def eval(self, gf: GoFile, node: Node | None, at: Node | None, env: Env | None = None, depth: int = 0):
|
|
279
|
+
"""A Q or a Cond for an expression, or None when it is neither."""
|
|
280
|
+
node = _strip_parens(node)
|
|
281
|
+
if node is None or depth > T.DEPTH:
|
|
282
|
+
return None
|
|
283
|
+
at = at if at is not None else node
|
|
284
|
+
t = node.type
|
|
285
|
+
if t == "identifier":
|
|
286
|
+
return self._ident(gf, node, at, env, depth)
|
|
287
|
+
if t == "call_expression":
|
|
288
|
+
return self._call(gf, node, at, env, depth)
|
|
289
|
+
if t == "composite_literal":
|
|
290
|
+
return self._literal(gf, node, at, env, depth)
|
|
291
|
+
if t == "selector_expression":
|
|
292
|
+
return self._selector(gf, node, at, env, depth)
|
|
293
|
+
if t == "unary_expression":
|
|
294
|
+
return self.eval(gf, node.child_by_field_name("operand"), at, env, depth)
|
|
295
|
+
return None
|
|
296
|
+
|
|
297
|
+
def _typed_root(self, gf: GoFile, node: Node, at: Node, param: str = ""):
|
|
298
|
+
ref = self.types.type_of(gf, node, at)
|
|
299
|
+
hit = self.types.lib_of(ref)
|
|
300
|
+
if hit is None:
|
|
301
|
+
return None
|
|
302
|
+
lib, kind = hit
|
|
303
|
+
if kind == "cond":
|
|
304
|
+
return Cond(f"{TOK}P:{param}{TOK}" if param else marker(_txt(node)))
|
|
305
|
+
if kind == "assoc":
|
|
306
|
+
return None
|
|
307
|
+
q = Q(lib)
|
|
308
|
+
if lib == "bun":
|
|
309
|
+
key = self.types.named(ref)
|
|
310
|
+
if key is not None and self.types.bun_shaped(key[0]):
|
|
311
|
+
from .base import path_engine
|
|
312
|
+
q.engine = path_engine(key[0] + "/x.go") # a repository's own bun-shaped client: `pkg/clickhouse/ch`
|
|
313
|
+
if kind in ("select", "insert", "update", "delete", "builder", "cte"):
|
|
314
|
+
q.kind = kind if kind in ("select", "insert", "update", "delete") else ""
|
|
315
|
+
# a new(sqlbuilder.SelectBuilder)-style value has no base to miss; a parameter or a field does
|
|
316
|
+
q.opaque = f"the builder is {'a parameter' if param else 'built elsewhere'} ({trim(_txt(node), 40)})"
|
|
317
|
+
return q
|
|
318
|
+
|
|
319
|
+
def _ident(self, gf: GoFile, node: Node, at: Node, env: Env | None, depth: int):
|
|
320
|
+
name = _txt(node)
|
|
321
|
+
if env is not None and name in env.cur:
|
|
322
|
+
return env.cur[name]
|
|
323
|
+
local = gf._local(name, at)
|
|
324
|
+
if local is None:
|
|
325
|
+
hit = self.ctx.pkg_decls.get(gf.dir, {}).get(name)
|
|
326
|
+
if hit is not None:
|
|
327
|
+
owner = hit[0]
|
|
328
|
+
value = owner.decls.get(name, (None,))[0]
|
|
329
|
+
if value is not None:
|
|
330
|
+
v = self.eval(owner, value, value, None, depth + 1)
|
|
331
|
+
if v is not None:
|
|
332
|
+
return v
|
|
333
|
+
return self._typed_root(gf, node, at)
|
|
334
|
+
top, decl, later = local
|
|
335
|
+
state = None
|
|
336
|
+
if decl.kind == "param":
|
|
337
|
+
if env is not None and name in env.params:
|
|
338
|
+
state = env.params[name].clone()
|
|
339
|
+
else:
|
|
340
|
+
state = self._typed_root(gf, node, at, param=name)
|
|
341
|
+
elif decl.kind != "range":
|
|
342
|
+
if decl.value is not None and decl.index <= 0:
|
|
343
|
+
state = self.eval(gf, decl.value, decl.node, env, depth + 1)
|
|
344
|
+
if state is None:
|
|
345
|
+
state = self._typed_root(gf, node, at)
|
|
346
|
+
if isinstance(state, Q) and state.opaque and decl.value is None:
|
|
347
|
+
state.flags.add("zero") # declared without a value: whatever is assigned first is the statement
|
|
348
|
+
if isinstance(state, Q) and state.opaque and decl.value is not None:
|
|
349
|
+
v = _strip_parens(decl.value)
|
|
350
|
+
if v is not None and v.type in ("composite_literal", "unary_expression") or (
|
|
351
|
+
v is not None and v.type == "call_expression" and callee_name(v.child_by_field_name("function"))[0] == "new"):
|
|
352
|
+
state.opaque = "" # a zero value: an empty builder
|
|
353
|
+
if state is None:
|
|
354
|
+
return None
|
|
355
|
+
events: list[tuple[int, str, object]] = [(e.node.start_byte, "assign", e) for e in later if e.kind == "assign" and e.value is not None]
|
|
356
|
+
# a bun DB or Tx is not changed by its methods (tx.Rollback(), db.NewSelect()...): only a query is
|
|
357
|
+
if isinstance(state, Q) and state.lib in MUTABLE and not (state.lib == "bun" and not state.kind):
|
|
358
|
+
lo = decl.node.end_byte if decl.kind != "param" else 0
|
|
359
|
+
for m in self.muts(gf).get((top.id, name), ()):
|
|
360
|
+
if lo <= m.start_byte and m.end_byte <= at.start_byte:
|
|
361
|
+
events.append((m.start_byte, "mut", m))
|
|
362
|
+
for m in self.muts(gf).get((top.id, "\x00" + name), ()):
|
|
363
|
+
if lo <= m.start_byte and m.end_byte <= at.start_byte:
|
|
364
|
+
events.append((m.start_byte, "passed", m))
|
|
365
|
+
events.sort(key=lambda e: e[0])
|
|
366
|
+
for _pos, kind, e in events:
|
|
367
|
+
anchor = e.node if kind == "assign" else e
|
|
368
|
+
if self._exclusive(anchor, at) or self._returns_before(anchor, at, top):
|
|
369
|
+
continue
|
|
370
|
+
cond = gf._conditional(anchor, at, top)
|
|
371
|
+
if kind == "passed":
|
|
372
|
+
if isinstance(state, Q):
|
|
373
|
+
state.tail.append(marker(_txt(e))) # a helper that takes the builder: what it adds is not followed
|
|
374
|
+
state.dynamic = True
|
|
375
|
+
continue
|
|
376
|
+
if kind == "assign":
|
|
377
|
+
state = self._assign(gf, name, state, e, cond, env, depth)
|
|
378
|
+
elif isinstance(state, Q):
|
|
379
|
+
state = self._mutate(gf, state, e, cond, env, depth)
|
|
380
|
+
if state is None:
|
|
381
|
+
return None
|
|
382
|
+
return state
|
|
383
|
+
|
|
384
|
+
def _assign(self, gf: GoFile, name: str, state, e, cond: bool, env: Env | None, depth: int):
|
|
385
|
+
if isinstance(state, Q):
|
|
386
|
+
state.cond_mode = cond
|
|
387
|
+
probe = state.clone() if cond and isinstance(state, Cond) else state
|
|
388
|
+
inner = Env({**(env.cur if env else {}), name: probe}, env.params if env else None)
|
|
389
|
+
new = self.eval(gf, e.value, e.node, inner, depth + 1)
|
|
390
|
+
if isinstance(state, Q):
|
|
391
|
+
state.cond_mode = False
|
|
392
|
+
if new is state and isinstance(state, Q):
|
|
393
|
+
return state
|
|
394
|
+
if isinstance(state, Cond) and new is probe:
|
|
395
|
+
if cond: # `if x { cond = cond.And(...) }`: what was added is the optional part
|
|
396
|
+
added = _added(state.text, probe.text)
|
|
397
|
+
state.and_("(" + marker(added) + ")")
|
|
398
|
+
return state
|
|
399
|
+
if cond and isinstance(state, Q) and "zero" in state.flags and isinstance(new, Q) and not new.opaque:
|
|
400
|
+
new.notes.append("assigned in one branch of several: this is the first branch")
|
|
401
|
+
new.dynamic = True
|
|
402
|
+
return new
|
|
403
|
+
if new is None:
|
|
404
|
+
if cond:
|
|
405
|
+
self._runtime_note(state, _txt(e.node))
|
|
406
|
+
return state
|
|
407
|
+
return None
|
|
408
|
+
if cond:
|
|
409
|
+
# replaced on one path only: the base stays, the replacement is a run-time part
|
|
410
|
+
self._runtime_note(state, _txt(e.node))
|
|
411
|
+
return state
|
|
412
|
+
return new
|
|
413
|
+
|
|
414
|
+
def _runtime_note(self, state, text: str) -> None:
|
|
415
|
+
if isinstance(state, Q):
|
|
416
|
+
state.tail.append(marker(text))
|
|
417
|
+
state.dynamic = True
|
|
418
|
+
elif isinstance(state, Cond):
|
|
419
|
+
state.and_("(" + marker(text) + ")")
|
|
420
|
+
|
|
421
|
+
def _mutate(self, gf: GoFile, state: Q, outer: Node, cond: bool, env: Env | None, depth: int) -> Q | None:
|
|
422
|
+
_root, ops = chain_of(outer)
|
|
423
|
+
if any(name in TERMINALS.get(state.lib, ()) or name in RAW_TERMINALS.get(state.lib, ()) for name, _a, _c in ops):
|
|
424
|
+
# a chain that runs a statement: xorm clears the session afterwards, so nothing it added stays
|
|
425
|
+
if state.lib == "xorm" and not cond:
|
|
426
|
+
fresh = Q(state.lib)
|
|
427
|
+
fresh.engine = state.engine
|
|
428
|
+
return fresh
|
|
429
|
+
return state
|
|
430
|
+
for name, args, call in ops:
|
|
431
|
+
if state.lib == "sqlbuilder" and name in self.SB_VALUES:
|
|
432
|
+
break # sb.E(...), sb.Var(...): a value, not a change
|
|
433
|
+
state.cond_mode = cond
|
|
434
|
+
out = self.apply(state, name, args, call, gf, outer, env, depth + 1)
|
|
435
|
+
state.cond_mode = False
|
|
436
|
+
if not isinstance(out, Q):
|
|
437
|
+
break # sb.E(...), sb.Var(...): a value, not a change
|
|
438
|
+
state = out
|
|
439
|
+
return state
|
|
440
|
+
|
|
441
|
+
@staticmethod
|
|
442
|
+
def _returns_before(a: Node, b: Node, top: Node) -> bool:
|
|
443
|
+
"""`a` sits in a block that ends in a return and does not hold `b`: control never gets from `a` to `b`."""
|
|
444
|
+
n = a.parent
|
|
445
|
+
while n is not None and n.id != top.id:
|
|
446
|
+
if n.type == "block" and not _within(b, n):
|
|
447
|
+
stmts = n.named_children[0].named_children if n.named_children and n.named_children[0].type == "statement_list" \
|
|
448
|
+
else n.named_children
|
|
449
|
+
if stmts and stmts[-1].type == "return_statement" and stmts[-1].start_byte >= a.end_byte:
|
|
450
|
+
return True
|
|
451
|
+
n = n.parent
|
|
452
|
+
return False
|
|
453
|
+
|
|
454
|
+
@staticmethod
|
|
455
|
+
def _exclusive(a: Node, b: Node) -> bool:
|
|
456
|
+
"""`a` and `b` sit in different arms of one if or switch: `a` never runs before `b`."""
|
|
457
|
+
anc = set()
|
|
458
|
+
n = b
|
|
459
|
+
while n is not None:
|
|
460
|
+
anc.add(n.id)
|
|
461
|
+
n = n.parent
|
|
462
|
+
prev, n = a, a.parent
|
|
463
|
+
while n is not None and n.id not in anc:
|
|
464
|
+
prev, n = n, n.parent
|
|
465
|
+
if n is None:
|
|
466
|
+
return False
|
|
467
|
+
if n.type == "if_statement":
|
|
468
|
+
cons, alt = n.child_by_field_name("consequence"), n.child_by_field_name("alternative")
|
|
469
|
+
if cons is None or alt is None:
|
|
470
|
+
return False
|
|
471
|
+
return (_within(a, cons) and _within(b, alt)) or (_within(a, alt) and _within(b, cons))
|
|
472
|
+
return prev.type in CASE_TYPES and not _within(b, prev) and any(_within(b, c) for c in n.children if c.type in CASE_TYPES)
|
|
473
|
+
|
|
474
|
+
def muts(self, gf: GoFile) -> dict[tuple[int, str], list[Node]]:
|
|
475
|
+
"""Per (function, variable): the method chains called on the variable as statements."""
|
|
476
|
+
got = self._muts.get(gf.rel)
|
|
477
|
+
if got is not None:
|
|
478
|
+
return got
|
|
479
|
+
got = defaultdict(list)
|
|
480
|
+
for c in gf.calls:
|
|
481
|
+
p = c.parent
|
|
482
|
+
if p is not None and p.type == "selector_expression" and p.parent is not None and p.parent.type == "call_expression":
|
|
483
|
+
continue # not the end of its chain
|
|
484
|
+
root, ops = chain_of(c)
|
|
485
|
+
if p is not None and p.type == "expression_statement":
|
|
486
|
+
top = gf._top_func(c)
|
|
487
|
+
for a in call_args(c): # `applyFilters(sb, opts)` as a statement: the builder goes into a helper
|
|
488
|
+
if a.type == "identifier" and top is not None:
|
|
489
|
+
got[(top.id, "\x00" + _txt(a))].append(c)
|
|
490
|
+
if not ops or root is None or root.type != "identifier":
|
|
491
|
+
continue
|
|
492
|
+
name = _txt(root)
|
|
493
|
+
if p is not None and p.type == "expression_list" and p.parent is not None and \
|
|
494
|
+
p.parent.type in ("assignment_statement", "short_var_declaration"):
|
|
495
|
+
left = p.parent.child_by_field_name("left")
|
|
496
|
+
if left is not None and any(_txt(x) == name for x in left.named_children):
|
|
497
|
+
continue # `q = q.Where(...)`: an assignment, read as one
|
|
498
|
+
top = gf._top_func(c)
|
|
499
|
+
if top is not None:
|
|
500
|
+
got[(top.id, name)].append(c)
|
|
501
|
+
self._muts[gf.rel] = got
|
|
502
|
+
return got
|
|
503
|
+
|
|
504
|
+
# ---- selectors and fields ------------------------------------------------------------------
|
|
505
|
+
def _selector(self, gf: GoFile, node: Node, at: Node, env: Env | None, depth: int):
|
|
506
|
+
operand, fld = node.child_by_field_name("operand"), node.child_by_field_name("field")
|
|
507
|
+
if operand is None or fld is None:
|
|
508
|
+
return None
|
|
509
|
+
name = _txt(fld)
|
|
510
|
+
if operand.type == "identifier" and _txt(operand) in gf.imports and gf._local(_txt(operand), at) is None:
|
|
511
|
+
path = gf.imports[_txt(operand)]
|
|
512
|
+
lib = T.import_lib(path)
|
|
513
|
+
if lib == "squirrel" and name == "StatementBuilder":
|
|
514
|
+
return Q("squirrel")
|
|
515
|
+
if lib == "sqlbuilder" and (name in FLAVORS or name == "DefaultFlavor"):
|
|
516
|
+
q = Q("sqlbuilder")
|
|
517
|
+
q.engine = FLAVORS.get(name, "")
|
|
518
|
+
q.flags.add("factory")
|
|
519
|
+
return q
|
|
520
|
+
if lib:
|
|
521
|
+
return None
|
|
522
|
+
target = self.ctx.import_dir(gf.dir, path)
|
|
523
|
+
hit = self.ctx.pkg_decls.get(target, {}).get(name) if target is not None else None
|
|
524
|
+
if hit is not None:
|
|
525
|
+
value = hit[0].decls.get(name, (None,))[0]
|
|
526
|
+
v = self.eval(hit[0], value, value, None, depth + 1) if value is not None else None
|
|
527
|
+
if v is not None:
|
|
528
|
+
return v
|
|
529
|
+
return self._typed_root(gf, node, at)
|
|
530
|
+
ref = self.types.type_of(gf, node, at)
|
|
531
|
+
hit = self.types.lib_of(ref)
|
|
532
|
+
if hit is None:
|
|
533
|
+
return None
|
|
534
|
+
if hit[1] in ("select", "insert", "update", "delete", "builder", "cond"):
|
|
535
|
+
v = self._field_value(gf, operand, name, at, depth)
|
|
536
|
+
if v is not None:
|
|
537
|
+
return v
|
|
538
|
+
return self._typed_root(gf, node, at)
|
|
539
|
+
|
|
540
|
+
def _field_value(self, gf: GoFile, operand: Node, name: str, at: Node, depth: int):
|
|
541
|
+
"""A builder kept in a struct field: the one value the package assigns to that field."""
|
|
542
|
+
owner = self.types.named(self.types.type_of(gf, operand, at))
|
|
543
|
+
inits = self.field_inits(gf.dir).get(name, [])
|
|
544
|
+
if owner is not None and owner[0] != gf.dir:
|
|
545
|
+
inits = self.field_inits(owner[0]).get(name, [])
|
|
546
|
+
values = []
|
|
547
|
+
for igf, value, stmt, target in inits:
|
|
548
|
+
if owner is not None:
|
|
549
|
+
if isinstance(target, str):
|
|
550
|
+
if target and target != owner[1]:
|
|
551
|
+
continue
|
|
552
|
+
else:
|
|
553
|
+
holder = self.types.named(self.types.type_of(igf, target, stmt))
|
|
554
|
+
if holder is not None and holder != owner:
|
|
555
|
+
continue
|
|
556
|
+
v = self.eval(igf, value, stmt, None, depth + 1)
|
|
557
|
+
if v is not None:
|
|
558
|
+
values.append(v)
|
|
559
|
+
if not values:
|
|
560
|
+
return None
|
|
561
|
+
first = values[0]
|
|
562
|
+
if len(values) > 1:
|
|
563
|
+
texts = {render(v) if isinstance(v, Q) else v.text for v in values}
|
|
564
|
+
if len(texts) != 1:
|
|
565
|
+
return None
|
|
566
|
+
return first
|
|
567
|
+
|
|
568
|
+
def field_inits(self, dir_: str) -> dict[str, list[tuple]]:
|
|
569
|
+
got = self._field_inits.get(dir_)
|
|
570
|
+
if got is not None:
|
|
571
|
+
return got
|
|
572
|
+
got = defaultdict(list)
|
|
573
|
+
for gf in self.ctx.dir_files.get(dir_, ()):
|
|
574
|
+
if gf.test:
|
|
575
|
+
continue
|
|
576
|
+
stack = [gf.root]
|
|
577
|
+
while stack:
|
|
578
|
+
n = stack.pop()
|
|
579
|
+
if n.type == "assignment_statement":
|
|
580
|
+
left, right = n.child_by_field_name("left"), n.child_by_field_name("right")
|
|
581
|
+
if left is not None and right is not None and len(left.named_children) == 1 == len(right.named_children):
|
|
582
|
+
target = left.named_children[0]
|
|
583
|
+
if target.type == "selector_expression" and target.child_by_field_name("field") is not None \
|
|
584
|
+
and target.child_by_field_name("operand") is not None:
|
|
585
|
+
got[_txt(target.child_by_field_name("field"))].append(
|
|
586
|
+
(gf, right.named_children[0], n, target.child_by_field_name("operand")))
|
|
587
|
+
continue
|
|
588
|
+
if n.type == "keyed_element":
|
|
589
|
+
key, value = n.child_by_field_name("key"), n.child_by_field_name("value")
|
|
590
|
+
if key is not None and value is not None and key.named_children and value.named_children \
|
|
591
|
+
and key.named_children[0].type == "identifier":
|
|
592
|
+
v = value.named_children[0]
|
|
593
|
+
if v.type in ("call_expression", "selector_expression", "identifier"):
|
|
594
|
+
got[_txt(key.named_children[0])].append((gf, v, n, gf._literal_type(n)))
|
|
595
|
+
stack.extend(n.children)
|
|
596
|
+
self._field_inits[dir_] = got
|
|
597
|
+
return got
|
|
598
|
+
|
|
599
|
+
# ---- calls -------------------------------------------------------------------------------
|
|
600
|
+
def _call(self, gf: GoFile, node: Node, at: Node, env: Env | None, depth: int):
|
|
601
|
+
fn = node.child_by_field_name("function")
|
|
602
|
+
name, recv, _dotted = callee_name(fn)
|
|
603
|
+
if not name:
|
|
604
|
+
return None
|
|
605
|
+
args = call_args(node)
|
|
606
|
+
if recv is None:
|
|
607
|
+
return self._user_call(gf, node, at, env, depth)
|
|
608
|
+
if recv.type == "identifier" and _txt(recv) in gf.imports and gf._local(_txt(recv), at) is None \
|
|
609
|
+
and not (env is not None and _txt(recv) in env.cur):
|
|
610
|
+
lib = T.import_lib(gf.imports[_txt(recv)])
|
|
611
|
+
if lib:
|
|
612
|
+
return self._lib_func(lib, name, args, node, gf, at, env, depth)
|
|
613
|
+
return self._user_call(gf, node, at, env, depth)
|
|
614
|
+
base = self.eval(gf, recv, at, env, depth + 1)
|
|
615
|
+
if base is None:
|
|
616
|
+
return self._user_call(gf, node, at, env, depth)
|
|
617
|
+
return self.apply(base, name, args, node, gf, at, env, depth)
|
|
618
|
+
|
|
619
|
+
def _user_call(self, gf: GoFile, node: Node, at: Node, env: Env | None, depth: int):
|
|
620
|
+
hit = self.types.callee(gf, node, at)
|
|
621
|
+
if hit is None:
|
|
622
|
+
return self._typed_root(gf, node, at)
|
|
623
|
+
cgf, func = hit
|
|
624
|
+
rt = self.types.result_type(cgf, func)
|
|
625
|
+
lib = self.types.lib_of(rt)
|
|
626
|
+
if lib is None:
|
|
627
|
+
return None
|
|
628
|
+
name, recv, _dotted = callee_name(node.child_by_field_name("function"))
|
|
629
|
+
if func.type not in FUNC_DECL or func.child_by_field_name("body") is None:
|
|
630
|
+
if lib[1] == "cond":
|
|
631
|
+
root = _strip_parens(recv)
|
|
632
|
+
if root is not None and root.type == "identifier":
|
|
633
|
+
local = gf._local(_txt(root), at)
|
|
634
|
+
if local is not None and local[1].kind == "param":
|
|
635
|
+
return Cond(f"{TOK}M:{_txt(root)}.{name}{TOK}")
|
|
636
|
+
return Cond(marker(_txt(node)))
|
|
637
|
+
return self._typed_root(gf, node, at)
|
|
638
|
+
bindings = {}
|
|
639
|
+
names = param_names(func)
|
|
640
|
+
passed = None
|
|
641
|
+
for i, a in enumerate(call_args(node)):
|
|
642
|
+
if i >= len(names) or not names[i]:
|
|
643
|
+
continue
|
|
644
|
+
pt = param_type(func, names[i])
|
|
645
|
+
if not pt or self.types.lib_of(TypeRef(pt, cgf)) is None:
|
|
646
|
+
continue
|
|
647
|
+
v = self.eval(gf, a, at, env, depth + 1)
|
|
648
|
+
if v is not None:
|
|
649
|
+
bindings[names[i]] = v
|
|
650
|
+
if passed is None and isinstance(v, Q) and self.types.lib_of(TypeRef(pt, cgf)) == lib:
|
|
651
|
+
passed = v
|
|
652
|
+
if not bindings and lib[1] == "stmt":
|
|
653
|
+
return self._typed_root(gf, node, at) # a fresh statement builder
|
|
654
|
+
v = self._inline(cgf, func, bindings, depth)
|
|
655
|
+
if v is not None:
|
|
656
|
+
return v
|
|
657
|
+
if passed is not None:
|
|
658
|
+
# `sess = paginate(sess, opts)`: the helper returns the builder it was given, changed in ways not followed
|
|
659
|
+
passed.tail.append(marker(_txt(node)))
|
|
660
|
+
passed.dynamic = True
|
|
661
|
+
return passed
|
|
662
|
+
out = self._typed_root(gf, node, at)
|
|
663
|
+
if isinstance(out, Q) and out.opaque:
|
|
664
|
+
out.opaque = f"the builder comes from {trim(_txt(node.child_by_field_name('function')), 50)}(), which was not followed"
|
|
665
|
+
return out
|
|
666
|
+
|
|
667
|
+
def _inline(self, cgf: GoFile, func: Node, bindings: dict, depth: int):
|
|
668
|
+
"""The value a function returns: its last return statement, read in its own file."""
|
|
669
|
+
if not bindings and func.id in self._inline_memo:
|
|
670
|
+
v = self._inline_memo[func.id]
|
|
671
|
+
return v.clone() if v is not None else None
|
|
672
|
+
if func.id in self._inline_busy or depth > T.DEPTH:
|
|
673
|
+
return None
|
|
674
|
+
self._inline_busy.add(func.id)
|
|
675
|
+
try:
|
|
676
|
+
body = func.child_by_field_name("body")
|
|
677
|
+
returns = []
|
|
678
|
+
stack = [body] if body is not None else []
|
|
679
|
+
while stack:
|
|
680
|
+
n = stack.pop()
|
|
681
|
+
if n.type == "return_statement":
|
|
682
|
+
returns.append(n)
|
|
683
|
+
elif n.type != "func_literal":
|
|
684
|
+
stack.extend(n.children)
|
|
685
|
+
returns.sort(key=lambda n: n.start_byte)
|
|
686
|
+
v = None
|
|
687
|
+
if returns:
|
|
688
|
+
last = returns[-1]
|
|
689
|
+
exprs = last.named_children[0].named_children if last.named_children and last.named_children[0].type == "expression_list" else []
|
|
690
|
+
if exprs:
|
|
691
|
+
v = self.eval(cgf, exprs[0], last, Env(None, bindings), depth + 1)
|
|
692
|
+
if isinstance(v, Q) and len(returns) > 1 and (v.where or v.table or v.joins or v.cols or v.model is not None):
|
|
693
|
+
v.notes.append("the builder function has several returns: the last one is shown")
|
|
694
|
+
finally:
|
|
695
|
+
self._inline_busy.discard(func.id)
|
|
696
|
+
if not bindings:
|
|
697
|
+
self._inline_memo[func.id] = v.clone() if v is not None else None
|
|
698
|
+
return v
|
|
699
|
+
|
|
700
|
+
# ---- text of arguments -------------------------------------------------------------------
|
|
701
|
+
def text(self, gf: GoFile, node: Node | None, at: Node, env: Env | None = None, depth: int = 0) -> str:
|
|
702
|
+
"""A SQL fragment for an argument: the string it resolves to, a sub-statement, or a run-time part."""
|
|
703
|
+
node = _strip_parens(node)
|
|
704
|
+
if node is None:
|
|
705
|
+
return ""
|
|
706
|
+
t = node.type
|
|
707
|
+
if t in STRING_TYPES:
|
|
708
|
+
return decode_string(node)
|
|
709
|
+
if t in ("int_literal", "float_literal"):
|
|
710
|
+
return _txt(node)
|
|
711
|
+
if t == "variadic_argument":
|
|
712
|
+
return ", ".join(self.texts(gf, [node], at, env, depth))
|
|
713
|
+
if t in ("identifier", "selector_expression", "binary_expression", "index_expression"):
|
|
714
|
+
res = gf.resolve(node, at, 0)
|
|
715
|
+
if res is not None and not (t in ("identifier", "selector_expression") and _is_marker(res.text)):
|
|
716
|
+
return self._helpers(res.text)
|
|
717
|
+
if t in ("identifier", "call_expression", "composite_literal", "selector_expression", "unary_expression"):
|
|
718
|
+
v = self.eval(gf, node, at, env, depth + 1)
|
|
719
|
+
if isinstance(v, Cond):
|
|
720
|
+
return v.text
|
|
721
|
+
if isinstance(v, Q):
|
|
722
|
+
sub = render(v)
|
|
723
|
+
return f"({sub})" if sub else marker(_txt(node))
|
|
724
|
+
if t == "call_expression":
|
|
725
|
+
res = gf.resolve(node, at, 0)
|
|
726
|
+
if res is not None:
|
|
727
|
+
return self._helpers(res.text)
|
|
728
|
+
name, recv, _dotted = callee_name(node.child_by_field_name("function"))
|
|
729
|
+
if recv is not None and recv.type == "identifier" and name and not call_args(node):
|
|
730
|
+
local = gf._local(_txt(recv), at)
|
|
731
|
+
if local is not None and local[1].kind == "param" and (env is None or _txt(recv) not in env.params):
|
|
732
|
+
return f"{TOK}M:{_txt(recv)}.{name}{TOK}"
|
|
733
|
+
return marker(_txt(node))
|
|
734
|
+
|
|
735
|
+
def _helpers(self, text: str) -> str:
|
|
736
|
+
"""Run-time parts that are a go-sqlbuilder helper call have a known text: `sb.Var(x)` is a bound value,
|
|
737
|
+
`sb.E("col", x)` is `col = ?`."""
|
|
738
|
+
if "sqlbuilder" not in self.types.libs or "«" not in text:
|
|
739
|
+
return text
|
|
740
|
+
|
|
741
|
+
def swap(m: re.Match) -> str:
|
|
742
|
+
name, rest = m.group(1), m.group(2)
|
|
743
|
+
if name == "Var":
|
|
744
|
+
return "?"
|
|
745
|
+
col = re.match(r'\s*"([^"]+)"\s*,', rest)
|
|
746
|
+
if col and name in self.SB_COMPARE:
|
|
747
|
+
return f"{col.group(1)} {self.SB_COMPARE[name]} ?"
|
|
748
|
+
if col and name in ("In", "NotIn"):
|
|
749
|
+
return f"{col.group(1)} {'IN' if name == 'In' else 'NOT IN'} (?)"
|
|
750
|
+
return m.group(0)
|
|
751
|
+
|
|
752
|
+
return re.sub(r"«\w+\.(\w+)\(([^»]*)\)»", swap, text)
|
|
753
|
+
|
|
754
|
+
def texts(self, gf: GoFile, args: list[Node], at: Node, env: Env | None = None, depth: int = 0) -> list[str]:
|
|
755
|
+
out: list[str] = []
|
|
756
|
+
for a in args:
|
|
757
|
+
if a.type == "variadic_argument":
|
|
758
|
+
inner = a.named_children[0] if a.named_children else None
|
|
759
|
+
items = gf._list(inner, at, 0) if inner is not None else None
|
|
760
|
+
if items is None and inner is not None:
|
|
761
|
+
items = self._list_helper(gf, inner, at)
|
|
762
|
+
if items is not None and not items[1]:
|
|
763
|
+
out.extend(self._helpers(r.text) for r in items[0])
|
|
764
|
+
else:
|
|
765
|
+
out.append(marker(_txt(a)))
|
|
766
|
+
continue
|
|
767
|
+
s = _strip_parens(a)
|
|
768
|
+
if s is not None and s.type == "composite_literal":
|
|
769
|
+
items = gf._list(s, at, 0)
|
|
770
|
+
if items is not None:
|
|
771
|
+
out.extend(self._helpers(r.text) for r in items[0])
|
|
772
|
+
continue
|
|
773
|
+
out.append(self.text(gf, a, at, env, depth))
|
|
774
|
+
return out
|
|
775
|
+
|
|
776
|
+
def _list_helper(self, gf: GoFile, node: Node, at: Node):
|
|
777
|
+
"""`channelColumns()...`: the []string literal a helper of this repository returns."""
|
|
778
|
+
node = _strip_parens(node)
|
|
779
|
+
if node is None or node.type != "call_expression":
|
|
780
|
+
return None
|
|
781
|
+
hit = self.types.callee(gf, node, at)
|
|
782
|
+
if hit is None or hit[1].type not in FUNC_DECL:
|
|
783
|
+
return None
|
|
784
|
+
body = hit[1].child_by_field_name("body")
|
|
785
|
+
returns = []
|
|
786
|
+
stack = [body] if body is not None else []
|
|
787
|
+
while stack:
|
|
788
|
+
n = stack.pop()
|
|
789
|
+
if n.type == "return_statement":
|
|
790
|
+
returns.append(n)
|
|
791
|
+
elif n.type != "func_literal":
|
|
792
|
+
stack.extend(n.children)
|
|
793
|
+
if len(returns) != 1 or not returns[0].named_children or not returns[0].named_children[0].named_children:
|
|
794
|
+
return None
|
|
795
|
+
return hit[0]._list(returns[0].named_children[0].named_children[0], returns[0], 0)
|
|
796
|
+
|
|
797
|
+
@staticmethod
|
|
798
|
+
def num(node: Node | None) -> str:
|
|
799
|
+
node = _strip_parens(node)
|
|
800
|
+
if node is None:
|
|
801
|
+
return ""
|
|
802
|
+
return _txt(node) if node.type == "int_literal" else "?"
|
|
803
|
+
|
|
804
|
+
def pred(self, gf: GoFile, args: list[Node], at: Node, env: Env | None, lib: str, q: Q | None = None, depth: int = 0) -> str:
|
|
805
|
+
"""The predicate a Where-like call adds: a string with bound values, a condition value, a struct or a map."""
|
|
806
|
+
if not args:
|
|
807
|
+
return ""
|
|
808
|
+
a0 = _strip_parens(args[0])
|
|
809
|
+
if a0 is None:
|
|
810
|
+
return ""
|
|
811
|
+
if a0.type not in STRING_TYPES:
|
|
812
|
+
v = self.eval(gf, a0, at, env, depth + 1)
|
|
813
|
+
if isinstance(v, Cond):
|
|
814
|
+
return v.text
|
|
815
|
+
if isinstance(v, Q):
|
|
816
|
+
sub = render(v)
|
|
817
|
+
return f"({sub})" if sub else marker(_txt(a0))
|
|
818
|
+
if lib == "gorm":
|
|
819
|
+
got = self._gorm_struct_cond(gf, a0, at)
|
|
820
|
+
if got is not None:
|
|
821
|
+
return got
|
|
822
|
+
s = self.text(gf, a0, at, env, depth)
|
|
823
|
+
if lib == "gorm" and len(args) > 1 and re.fullmatch(r"[\w.\"`]+", s):
|
|
824
|
+
return f"{s} = ?"
|
|
825
|
+
if len(args) > 1 and lib in ("gorm", "xorm", "squirrel") and s.count("?") == len(args) - 1:
|
|
826
|
+
subs = {}
|
|
827
|
+
for i, a in enumerate(args[1:]):
|
|
828
|
+
a = _strip_parens(a)
|
|
829
|
+
if a is not None and a.type in ("identifier", "call_expression"):
|
|
830
|
+
v = self.eval(gf, a, at, env, depth + 1)
|
|
831
|
+
sub = self._subquery(v) if isinstance(v, Q) else ""
|
|
832
|
+
if sub:
|
|
833
|
+
subs[i] = sub
|
|
834
|
+
if subs:
|
|
835
|
+
parts = s.split("?")
|
|
836
|
+
s = parts[0] + "".join((subs.get(i, "?")) + p for i, p in enumerate(parts[1:]))
|
|
837
|
+
s = re.sub(r"\(\((SELECT\b[^()]*(?:\([^()]*\)[^()]*)*)\)\)", r"(\1)", s)
|
|
838
|
+
return s
|
|
839
|
+
|
|
840
|
+
def _subquery(self, q: Q) -> str:
|
|
841
|
+
"""A builder used as a value inside another statement."""
|
|
842
|
+
if q.lib == "bun":
|
|
843
|
+
from . import orm_go_bun
|
|
844
|
+
out = orm_go_bun.select_text(q)
|
|
845
|
+
return f"({out})" if out else ""
|
|
846
|
+
if q.lib == "gorm":
|
|
847
|
+
s = q.clone()
|
|
848
|
+
s.kind = "select"
|
|
849
|
+
if not s.table and s.model is None:
|
|
850
|
+
return ""
|
|
851
|
+
s.cols = s.cols or ["*"]
|
|
852
|
+
deleted = s.model.role("deleted") if s.model is not None and not s.table and "unscoped" not in s.flags else ""
|
|
853
|
+
if deleted:
|
|
854
|
+
s.and_(f"{s.model.table}.{deleted} IS NULL")
|
|
855
|
+
out = render(s)
|
|
856
|
+
else:
|
|
857
|
+
out = render(q)
|
|
858
|
+
return f"({out})" if out else ""
|
|
859
|
+
|
|
860
|
+
def _keyed(self, gf: GoFile, lit: Node, at: Node) -> list[tuple[str, Node, Node]] | None:
|
|
861
|
+
"""(key text, key node, value node) of a keyed literal; None when an element is not keyed."""
|
|
862
|
+
body = lit.child_by_field_name("body")
|
|
863
|
+
out = []
|
|
864
|
+
for el in (body.named_children if body is not None else ()):
|
|
865
|
+
if el.type != "keyed_element":
|
|
866
|
+
return None
|
|
867
|
+
k, v = el.child_by_field_name("key"), el.child_by_field_name("value")
|
|
868
|
+
if k is None or v is None or not k.named_children or not v.named_children:
|
|
869
|
+
return None
|
|
870
|
+
kn = k.named_children[0]
|
|
871
|
+
out.append((self.text(gf, kn, at) if kn.type != "identifier" or gf._local(_txt(kn), at) is not None
|
|
872
|
+
or gf.resolve(kn, at, 0) is not None else _txt(kn), kn, v.named_children[0]))
|
|
873
|
+
return out
|
|
874
|
+
|
|
875
|
+
def _gorm_struct_cond(self, gf: GoFile, node: Node, at: Node) -> str | None:
|
|
876
|
+
lit = node
|
|
877
|
+
if lit.type == "unary_expression":
|
|
878
|
+
lit = _strip_parens(lit.child_by_field_name("operand"))
|
|
879
|
+
if lit is None or lit.type != "composite_literal":
|
|
880
|
+
return None
|
|
881
|
+
typ = lit.child_by_field_name("type")
|
|
882
|
+
if typ is None:
|
|
883
|
+
return None
|
|
884
|
+
keyed = self._keyed(gf, lit, at)
|
|
885
|
+
if keyed is None:
|
|
886
|
+
return None
|
|
887
|
+
if typ.type == "map_type":
|
|
888
|
+
return " AND ".join(f"{k} = ?" for k, _kn, _v in keyed)
|
|
889
|
+
model = self.types.model(TypeRef(_txt(typ), gf), "gorm")
|
|
890
|
+
if model is None:
|
|
891
|
+
return None
|
|
892
|
+
parts = []
|
|
893
|
+
for _k, kn, _v in keyed:
|
|
894
|
+
col = model.col(_txt(kn))
|
|
895
|
+
parts.append(f"{T.ident(col.name)} = ?" if col is not None else marker(_txt(kn)) + " = ?")
|
|
896
|
+
return " AND ".join(parts)
|
|
897
|
+
|
|
898
|
+
# ---- literals: sq.Eq{...}, builder.Eq{...} ---------------------------------------------------
|
|
899
|
+
def _literal(self, gf: GoFile, node: Node, at: Node, env: Env | None, depth: int):
|
|
900
|
+
typ = node.child_by_field_name("type")
|
|
901
|
+
if typ is None or typ.type != "qualified_type":
|
|
902
|
+
return None
|
|
903
|
+
pkg, name = _txt(typ).split(".", 1)
|
|
904
|
+
lib = T.import_lib(gf.imports.get(pkg, ""))
|
|
905
|
+
if lib not in ("squirrel", "xbuilder"):
|
|
906
|
+
return None
|
|
907
|
+
body = node.child_by_field_name("body")
|
|
908
|
+
elems = [e for e in (body.named_children if body is not None else ()) if e.type in ("keyed_element", "literal_element")]
|
|
909
|
+
ops = {"Eq": "=", "NotEq": "<>", "Neq": "<>", "Lt": "<", "Gt": ">", "LtOrEq": "<=", "GtOrEq": ">=", "Lte": "<=", "Gte": ">=",
|
|
910
|
+
"Like": "LIKE", "NotLike": "NOT LIKE", "ILike": "ILIKE", "NotILike": "NOT ILIKE"}
|
|
911
|
+
if name in ("And", "Or") and lib == "squirrel":
|
|
912
|
+
parts = []
|
|
913
|
+
for e in elems:
|
|
914
|
+
inner = e.named_children[0] if e.type == "literal_element" and e.named_children else None
|
|
915
|
+
p = self.pred(gf, [inner], at, env, lib, None, depth + 1) if inner is not None else ""
|
|
916
|
+
if p:
|
|
917
|
+
parts.append(p)
|
|
918
|
+
joiner = f" {name.upper()} "
|
|
919
|
+
return Cond(joiner.join(f"({p})" if len(parts) > 1 and (_has_top_or(p) or name == "Or" and " AND " in p) else p for p in parts))
|
|
920
|
+
if name == "Like" and lib == "xbuilder":
|
|
921
|
+
vals = [e.named_children[0] for e in elems if e.type == "literal_element" and e.named_children]
|
|
922
|
+
return Cond(f"{self.text(gf, vals[0], at, env)} LIKE ?") if vals else Cond(marker(_txt(node)))
|
|
923
|
+
if name in ("IsNull", "NotNull") and lib == "xbuilder":
|
|
924
|
+
vals = [e.named_children[0] for e in elems if e.type == "literal_element" and e.named_children]
|
|
925
|
+
return Cond(f"{self.text(gf, vals[0], at, env)} IS {'NOT ' if name == 'NotNull' else ''}NULL") if vals else Cond(marker(_txt(node)))
|
|
926
|
+
if name == "Not" and lib == "xbuilder":
|
|
927
|
+
vals = [e.named_children[0] for e in elems if e.type == "literal_element" and e.named_children]
|
|
928
|
+
return Cond(f"NOT ({self.pred(gf, vals[:1], at, env, lib)})") if vals else Cond(marker(_txt(node)))
|
|
929
|
+
if name == "Between" and lib == "xbuilder":
|
|
930
|
+
keyed = self._keyed(gf, node, at) or []
|
|
931
|
+
col = next((self.text(gf, v, at, env) for k, _kn, v in keyed if k == "Col"), "")
|
|
932
|
+
return Cond(f"{col} BETWEEN ? AND ?") if col else Cond(marker(_txt(node)))
|
|
933
|
+
if name in ops:
|
|
934
|
+
keyed = self._keyed(gf, node, at)
|
|
935
|
+
if keyed is None:
|
|
936
|
+
return Cond(marker(_txt(node)))
|
|
937
|
+
parts = []
|
|
938
|
+
for k, _kn, v in sorted(keyed, key=lambda kv: kv[0]):
|
|
939
|
+
parts.append(self._compare(gf, k, ops[name], v, at, env, depth))
|
|
940
|
+
return Cond(" AND ".join(parts))
|
|
941
|
+
return None
|
|
942
|
+
|
|
943
|
+
def _compare(self, gf: GoFile, col: str, op: str, value: Node, at: Node, env: Env | None, depth: int) -> str:
|
|
944
|
+
value = _strip_parens(value)
|
|
945
|
+
if value is not None and value.type == "nil":
|
|
946
|
+
return f"{col} IS NULL" if op == "=" else f"{col} IS NOT NULL"
|
|
947
|
+
if value is not None and value.type in ("call_expression", "identifier") and op in ("=", "<>"):
|
|
948
|
+
v = self.eval(gf, value, at, env, depth + 1) if value.type == "call_expression" or \
|
|
949
|
+
(gf._local(_txt(value), at) is not None) else None
|
|
950
|
+
if isinstance(v, Q):
|
|
951
|
+
sub = render(v)
|
|
952
|
+
if sub:
|
|
953
|
+
return f"{col} {'IN' if op == '=' else 'NOT IN'} ({sub})"
|
|
954
|
+
if isinstance(v, Cond) and v.text:
|
|
955
|
+
return f"{col} {op} {v.text}"
|
|
956
|
+
if op in ("=", "<>") and value is not None:
|
|
957
|
+
many = value.type == "composite_literal" and (value.child_by_field_name("type") is not None
|
|
958
|
+
and value.child_by_field_name("type").type in ("slice_type", "array_type"))
|
|
959
|
+
if not many and value.type in ("identifier", "selector_expression", "call_expression"):
|
|
960
|
+
ref = self.types.type_of(gf, value, at)
|
|
961
|
+
many = ref is not None and ref.text.lstrip("*").startswith("[]") and not ref.text.endswith("byte")
|
|
962
|
+
if many:
|
|
963
|
+
return f"{col} {'IN' if op == '=' else 'NOT IN'} (?)"
|
|
964
|
+
return f"{col} {op} ?"
|
|
965
|
+
|
|
966
|
+
# ---- library functions: sq.Select(...), builder.In(...), sqlbuilder.NewSelectBuilder() ------------
|
|
967
|
+
def _lib_func(self, lib: str, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env: Env | None, depth: int): # noqa: C901
|
|
968
|
+
tx = lambda n: self.text(gf, n, at, env, depth) # noqa: E731
|
|
969
|
+
if lib == "squirrel":
|
|
970
|
+
if name in ("Select", "Insert", "Update", "Delete", "Replace"):
|
|
971
|
+
return self.apply(Q("squirrel"), name, args, call, gf, at, env, depth)
|
|
972
|
+
if name == "Expr":
|
|
973
|
+
return Cond(tx(args[0])) if args else Cond()
|
|
974
|
+
if name == "Alias" and len(args) == 2:
|
|
975
|
+
return Cond(f"{_sub(tx(args[0]))} AS {tx(args[1])}")
|
|
976
|
+
if name == "ConcatExpr":
|
|
977
|
+
return Cond("".join(tx(a) for a in args))
|
|
978
|
+
if name in ("Case", "Placeholders"):
|
|
979
|
+
return Cond(marker(_txt(call)))
|
|
980
|
+
return None
|
|
981
|
+
if lib == "xbuilder":
|
|
982
|
+
if name in ("Select", "Insert", "Update", "Delete", "Dialect"):
|
|
983
|
+
q = Q("xbuilder")
|
|
984
|
+
return q if name == "Dialect" else self.apply(q, name, args, call, gf, at, env, depth)
|
|
985
|
+
if name == "NewCond":
|
|
986
|
+
return Cond()
|
|
987
|
+
if name in ("And", "Or"):
|
|
988
|
+
parts = [p for p in (self.pred(gf, [a], at, env, lib, None, depth + 1) for a in args) if p]
|
|
989
|
+
if any(a.type == "variadic_argument" for a in args):
|
|
990
|
+
return Cond(marker(_txt(call)))
|
|
991
|
+
return Cond(f" {name.upper()} ".join(f"({p})" if len(parts) > 1 and (_has_top_or(p) or " AND " in p) else p for p in parts))
|
|
992
|
+
if name in ("In", "NotIn") and args:
|
|
993
|
+
col = tx(args[0])
|
|
994
|
+
kw = "IN" if name == "In" else "NOT IN"
|
|
995
|
+
if len(args) == 2:
|
|
996
|
+
v = self.eval(gf, args[1], at, env, depth + 1)
|
|
997
|
+
if isinstance(v, Q):
|
|
998
|
+
sub = render(v)
|
|
999
|
+
if sub:
|
|
1000
|
+
return Cond(f"{col} {kw} ({sub})")
|
|
1001
|
+
return Cond(f"{col} {kw} (?)")
|
|
1002
|
+
if name == "Expr":
|
|
1003
|
+
return Cond(tx(args[0])) if args else Cond()
|
|
1004
|
+
if name in ("Exists", "NotExists") and args:
|
|
1005
|
+
v = self.eval(gf, args[0], at, env, depth + 1)
|
|
1006
|
+
sub = render(v) if isinstance(v, Q) else ""
|
|
1007
|
+
return Cond(f"{'NOT ' if name == 'NotExists' else ''}EXISTS ({sub or marker(_txt(args[0]))})")
|
|
1008
|
+
if name == "If":
|
|
1009
|
+
return Cond(marker(_txt(call)))
|
|
1010
|
+
return None
|
|
1011
|
+
if lib == "sqlbuilder":
|
|
1012
|
+
ctor = {"NewSelectBuilder": "select", "Select": "select", "NewInsertBuilder": "insert", "InsertInto": "insert",
|
|
1013
|
+
"NewUpdateBuilder": "update", "Update": "update", "NewDeleteBuilder": "delete", "DeleteFrom": "delete"}
|
|
1014
|
+
if name in ctor:
|
|
1015
|
+
q = Q("sqlbuilder", ctor[name])
|
|
1016
|
+
if not name.startswith("New"):
|
|
1017
|
+
return self.apply(q, name, args, call, gf, at, env, depth)
|
|
1018
|
+
return q
|
|
1019
|
+
if name in ("Escape", "Raw"):
|
|
1020
|
+
return Cond(tx(args[0])) if args else Cond()
|
|
1021
|
+
if name == "List":
|
|
1022
|
+
return Cond("?")
|
|
1023
|
+
if name in ("UnionAll", "Union"):
|
|
1024
|
+
q = Q("sqlbuilder", "select")
|
|
1025
|
+
parts = [self.text(gf, a, at, env, depth) for a in args]
|
|
1026
|
+
if any(_is_marker(p) or not p for p in parts) or not parts:
|
|
1027
|
+
q.opaque = "the parts of the UNION are not known"
|
|
1028
|
+
else:
|
|
1029
|
+
q.union = (" UNION ALL " if name == "UnionAll" else " UNION ").join(_unsub(p) for p in parts)
|
|
1030
|
+
return q
|
|
1031
|
+
if name == "With":
|
|
1032
|
+
q = Q("sqlbuilder")
|
|
1033
|
+
q.prefix.append("WITH " + ", ".join(self.text(gf, a, at, env, depth) for a in args))
|
|
1034
|
+
return q
|
|
1035
|
+
if name == "CTEQuery" or name == "CTETable":
|
|
1036
|
+
q = Q("sqlbuilder")
|
|
1037
|
+
q.flags.add("cte")
|
|
1038
|
+
q.alias = tx(args[0]) if args else ""
|
|
1039
|
+
return q
|
|
1040
|
+
if name == "NewWhereClause":
|
|
1041
|
+
return Cond()
|
|
1042
|
+
return None
|
|
1043
|
+
if lib in ("goqu", "bun", "ent"):
|
|
1044
|
+
return Q(lib)
|
|
1045
|
+
if (lib == "gorm" and name == "Open") or (lib == "xorm" and name.startswith("NewEngine")):
|
|
1046
|
+
return Q(lib)
|
|
1047
|
+
return None
|
|
1048
|
+
|
|
1049
|
+
# ================================================================ operations
|
|
1050
|
+
def apply(self, base, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env: Env | None, depth: int):
|
|
1051
|
+
if isinstance(base, Cond):
|
|
1052
|
+
if name in ("And", "Or"):
|
|
1053
|
+
if any(a.type == "variadic_argument" for a in args):
|
|
1054
|
+
parts = [marker(_txt(call))]
|
|
1055
|
+
else:
|
|
1056
|
+
parts = [p for p in (self.pred(gf, [a], at, env, "xbuilder", None, depth + 1) for a in args) if p]
|
|
1057
|
+
for p in parts:
|
|
1058
|
+
(base.and_ if name == "And" else base.or_)(p)
|
|
1059
|
+
return base
|
|
1060
|
+
return None
|
|
1061
|
+
q: Q = base
|
|
1062
|
+
if q.lib == "gorm" and name == "Association":
|
|
1063
|
+
q.assoc = self.text(gf, args[0], at, env, depth) if args else ""
|
|
1064
|
+
return q
|
|
1065
|
+
if name in TERMINALS.get(q.lib, ()):
|
|
1066
|
+
# `q.QueryRow().Scan(&x)` is one statement, reported at the outer call; a GORM or xorm result is not a session
|
|
1067
|
+
return q if q.lib in ("squirrel", "bun", "goqu") else None
|
|
1068
|
+
if q.cond_mode and not (q.lib == "sqlbuilder" and name in self.SB_VALUES):
|
|
1069
|
+
return self._runtime(q, name, args, call, gf, at, env, depth)
|
|
1070
|
+
fn = {"xorm": self._xorm, "gorm": self._gorm, "squirrel": self._squirrel, "sqlbuilder": self._sqlbuilder, "bun": self._bun,
|
|
1071
|
+
"xbuilder": self._xbuilder}.get(q.lib)
|
|
1072
|
+
if fn is None:
|
|
1073
|
+
return q
|
|
1074
|
+
return fn(q, name, args, call, gf, at, env, depth)
|
|
1075
|
+
|
|
1076
|
+
WHERE_OPS = {"Where", "And", "Or", "In", "NotIn", "Not", "Having", "ID", "AddWhereClause"}
|
|
1077
|
+
|
|
1078
|
+
def _runtime(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env: Env | None, depth: int) -> Q:
|
|
1079
|
+
"""An operation inside an `if`: a run-time part. A filter keeps its predicate inside the marker."""
|
|
1080
|
+
fn = call.child_by_field_name("function")
|
|
1081
|
+
src = "." + name + _txt(call.child_by_field_name("arguments")) if fn is not None else _txt(call)
|
|
1082
|
+
if (name in self.WHERE_OPS or q.lib == "bun" and name in ("WhereOr", "WhereGroup", "WherePK")) and name != "Having":
|
|
1083
|
+
probe = Q(q.lib, q.kind)
|
|
1084
|
+
probe.model, probe.table = q.model, q.table
|
|
1085
|
+
handler = {"xorm": self._xorm, "gorm": self._gorm, "squirrel": self._squirrel, "sqlbuilder": self._sqlbuilder, "bun": self._bun,
|
|
1086
|
+
"xbuilder": self._xbuilder}.get(q.lib)
|
|
1087
|
+
text = ""
|
|
1088
|
+
try:
|
|
1089
|
+
out = handler(probe, name, args, call, gf, at, env, depth) if handler else None
|
|
1090
|
+
text = out.where if isinstance(out, Q) else ""
|
|
1091
|
+
if isinstance(out, Q) and out.use_pk:
|
|
1092
|
+
text = "id = ?"
|
|
1093
|
+
except Unresolved:
|
|
1094
|
+
text = ""
|
|
1095
|
+
if text and TOKEN.search(text):
|
|
1096
|
+
q.and_("(" + DEFER_OPEN + text + DEFER_CLOSE + ")") # a marker once the caller's conditions are filled in
|
|
1097
|
+
else:
|
|
1098
|
+
q.and_("(" + marker(text or src) + ")")
|
|
1099
|
+
return q
|
|
1100
|
+
if name in ("Join", "InnerJoin", "LeftJoin", "RightJoin", "CrossJoin", "FullJoin", "Joins", "JoinWithOption", "JoinClause",
|
|
1101
|
+
"InnerJoins"):
|
|
1102
|
+
q.joins.append(f"/* {marker(src)} */")
|
|
1103
|
+
elif name in ("Select", "Columns", "Column", "Cols", "MustCols", "SelectMore") and q.kind in ("", "select"):
|
|
1104
|
+
q.cols.append(marker(src))
|
|
1105
|
+
else:
|
|
1106
|
+
q.tail.append(marker(src))
|
|
1107
|
+
q.dynamic = q.dynamic or name not in ("Limit", "Offset", "OrderBy", "Order", "Asc", "Desc", "Clauses")
|
|
1108
|
+
return q
|
|
1109
|
+
|
|
1110
|
+
# ---- xorm ----------------------------------------------------------------------------------
|
|
1111
|
+
XORM_NOOP = {"Context", "NoCache", "NoCascade", "Cascade", "NoAutoTime", "UseBool", "Nullable", "AllCols", "Prepare",
|
|
1112
|
+
"Charset", "StoreEngine", "BufferSize", "MustLogSQL", "Clone", "IndexHint", "NoVersionCheck",
|
|
1113
|
+
"Begin", "NewSession", "Ping", "PingContext", "ShowSQL", "Close", "SetExpr_"}
|
|
1114
|
+
|
|
1115
|
+
def _xorm(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env: Env | None, depth: int): # noqa: C901
|
|
1116
|
+
tx = lambda n: self.text(gf, n, at, env, depth) # noqa: E731
|
|
1117
|
+
if name in ("Where", "And"):
|
|
1118
|
+
q.and_(self.pred(gf, args, at, env, "xorm", q, depth))
|
|
1119
|
+
elif name == "Or":
|
|
1120
|
+
q.or_(self.pred(gf, args, at, env, "xorm", q, depth))
|
|
1121
|
+
elif name in ("In", "NotIn") and args:
|
|
1122
|
+
col = tx(args[0])
|
|
1123
|
+
kw = "IN" if name == "In" else "NOT IN"
|
|
1124
|
+
sub = ""
|
|
1125
|
+
if len(args) == 2:
|
|
1126
|
+
v = self.eval(gf, args[1], at, env, depth + 1)
|
|
1127
|
+
sub = render(v) if isinstance(v, Q) else ""
|
|
1128
|
+
q.and_(f"{col} {kw} ({sub or '?'})")
|
|
1129
|
+
elif name == "ID":
|
|
1130
|
+
q.use_pk = True
|
|
1131
|
+
elif name == "Table" and args:
|
|
1132
|
+
self._set_table(q, gf, args[0], at, env, "xorm")
|
|
1133
|
+
elif name == "Alias" and args:
|
|
1134
|
+
q.alias = tx(args[0])
|
|
1135
|
+
elif name in ("Cols", "MustCols"):
|
|
1136
|
+
q.cols.extend(self.texts(gf, args, at, env))
|
|
1137
|
+
elif name == "Select" and args:
|
|
1138
|
+
q.cols = [tx(args[0])]
|
|
1139
|
+
q.flags.add("select")
|
|
1140
|
+
elif name == "Distinct":
|
|
1141
|
+
q.distinct = True
|
|
1142
|
+
q.cols.extend(self.texts(gf, args, at, env))
|
|
1143
|
+
elif name == "Omit":
|
|
1144
|
+
q.omit.extend(self.texts(gf, args, at, env))
|
|
1145
|
+
elif name == "Join" and len(args) >= 3:
|
|
1146
|
+
kind = tx(args[0]).strip().upper()
|
|
1147
|
+
if _is_marker(kind) or not re.fullmatch(r"[A-Z ]*", kind):
|
|
1148
|
+
kind = marker(_txt(args[0]))
|
|
1149
|
+
q.joins.append(f"{kind} JOIN {self._join_table(gf, args[1], at, env, 'xorm')} ON {self.pred(gf, args[2:], at, env, 'xorm', q, depth)}".strip())
|
|
1150
|
+
elif name == "OrderBy" and args:
|
|
1151
|
+
q.order.append(tx(args[0]))
|
|
1152
|
+
elif name in ("Asc", "Desc"):
|
|
1153
|
+
q.order.extend(f"{c} {name.upper()}" for c in self.texts(gf, args, at, env))
|
|
1154
|
+
elif name == "GroupBy" and args:
|
|
1155
|
+
q.group.append(tx(args[0]))
|
|
1156
|
+
elif name == "Having" and args:
|
|
1157
|
+
q.having.append(tx(args[0]))
|
|
1158
|
+
elif name == "Limit" and args:
|
|
1159
|
+
q.limit = self.num(args[0])
|
|
1160
|
+
if len(args) > 1:
|
|
1161
|
+
q.offset = self.num(args[1])
|
|
1162
|
+
elif name in ("Incr", "Decr") and args:
|
|
1163
|
+
col = tx(args[0])
|
|
1164
|
+
q.sets.append(f"{col} = {col} {'+' if name == 'Incr' else '-'} ?")
|
|
1165
|
+
elif name == "SetExpr" and len(args) >= 2:
|
|
1166
|
+
q.sets.append(f"{tx(args[0])} = {_sub(tx(args[1]))}")
|
|
1167
|
+
elif name == "NoAutoCondition":
|
|
1168
|
+
q.flags.add("noauto")
|
|
1169
|
+
elif name == "Unscoped":
|
|
1170
|
+
q.flags.add("unscoped")
|
|
1171
|
+
elif name == "ForUpdate":
|
|
1172
|
+
q.suffix.append("FOR UPDATE")
|
|
1173
|
+
elif name == "SQL":
|
|
1174
|
+
q.flags.add("raw")
|
|
1175
|
+
elif name not in self.XORM_NOOP:
|
|
1176
|
+
q.notes.append(f".{name}() is not shown")
|
|
1177
|
+
return q
|
|
1178
|
+
|
|
1179
|
+
# ---- bun (orm_go_bun) -----------------------------------------------------------------------------
|
|
1180
|
+
def _bun(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env: Env | None, depth: int):
|
|
1181
|
+
from . import orm_go_bun
|
|
1182
|
+
return orm_go_bun.apply(self, q, name, args, call, gf, at, env, depth)
|
|
1183
|
+
|
|
1184
|
+
def _bun_final(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, bind: dict | None) -> list[Stmt]:
|
|
1185
|
+
from . import orm_go_bun
|
|
1186
|
+
return orm_go_bun.final(self, q, name, args, call, gf, bind)
|
|
1187
|
+
|
|
1188
|
+
def _set_table(self, q: Q, gf: GoFile, arg: Node, at: Node, env: Env | None, lib: str) -> None:
|
|
1189
|
+
a = _strip_parens(arg)
|
|
1190
|
+
if a is not None and (a.type in STRING_TYPES or gf.resolve(a, at, 0) is not None):
|
|
1191
|
+
q.table = self.text(gf, a, at, env)
|
|
1192
|
+
return
|
|
1193
|
+
model = self.types.model(self.types.type_of(gf, arg, at), lib)
|
|
1194
|
+
if model is not None:
|
|
1195
|
+
q.model = model
|
|
1196
|
+
q.table = ""
|
|
1197
|
+
else:
|
|
1198
|
+
q.table = marker(_txt(arg))
|
|
1199
|
+
|
|
1200
|
+
def _join_table(self, gf: GoFile, arg: Node, at: Node, env: Env | None, lib: str) -> str:
|
|
1201
|
+
a = _strip_parens(arg)
|
|
1202
|
+
if a is None:
|
|
1203
|
+
return ""
|
|
1204
|
+
if a.type == "composite_literal": # []string{"repository", "r"}
|
|
1205
|
+
parts = self.texts(gf, [a], at, env)
|
|
1206
|
+
return " AS ".join(parts[:2]) if parts else marker(_txt(a))
|
|
1207
|
+
if a.type in STRING_TYPES or gf.resolve(a, at, 0) is not None:
|
|
1208
|
+
return self.text(gf, a, at, env)
|
|
1209
|
+
model = self.types.model(self.types.type_of(gf, a, at), lib)
|
|
1210
|
+
if model is not None:
|
|
1211
|
+
return model.table
|
|
1212
|
+
return self.text(gf, a, at, env)
|
|
1213
|
+
|
|
1214
|
+
# ---- gorm ----------------------------------------------------------------------------------
|
|
1215
|
+
GORM_NOOP = {"WithContext", "Session", "Debug", "Begin", "Set", "InstanceSet", "Get", "InstanceGet", "Statement", "Callback",
|
|
1216
|
+
"Use", "Assign", "Attrs", "Unscoped_", "Commit", "Rollback", "SavePoint", "RollbackTo", "Connection", "DB",
|
|
1217
|
+
"Error", "AddError", "Migrator", "AutoMigrate", "MapColumns"}
|
|
1218
|
+
|
|
1219
|
+
def _gorm(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env: Env | None, depth: int): # noqa: C901
|
|
1220
|
+
tx = lambda n: self.text(gf, n, at, env, depth) # noqa: E731
|
|
1221
|
+
if name == "Where":
|
|
1222
|
+
q.and_(self.pred(gf, args, at, env, "gorm", q, depth))
|
|
1223
|
+
elif name == "Or":
|
|
1224
|
+
q.or_(self.pred(gf, args, at, env, "gorm", q, depth))
|
|
1225
|
+
elif name == "Not":
|
|
1226
|
+
p = self.pred(gf, args, at, env, "gorm", q, depth)
|
|
1227
|
+
if p:
|
|
1228
|
+
q.and_(f"NOT ({p})")
|
|
1229
|
+
elif name == "Model" and args:
|
|
1230
|
+
model = self.types.model(self.types.type_of(gf, args[0], at), "gorm")
|
|
1231
|
+
if model is not None:
|
|
1232
|
+
q.model = model
|
|
1233
|
+
if not _empty_value(gf, args[0], at):
|
|
1234
|
+
q.flags.add("model_instance")
|
|
1235
|
+
else:
|
|
1236
|
+
q.flags.add("model_unknown")
|
|
1237
|
+
q.notes.append(f"Model({trim(_txt(args[0]), 40)}) is not a struct this scan can read")
|
|
1238
|
+
elif name == "Table" and args:
|
|
1239
|
+
q.table = tx(args[0])
|
|
1240
|
+
elif name == "Select" and args:
|
|
1241
|
+
q.cols = _split_cols(self.texts(gf, args[:1], at, env))
|
|
1242
|
+
q.flags.add("select")
|
|
1243
|
+
elif name == "Omit":
|
|
1244
|
+
q.omit.extend(self.texts(gf, args, at, env))
|
|
1245
|
+
elif name == "Distinct":
|
|
1246
|
+
q.distinct = True
|
|
1247
|
+
if args:
|
|
1248
|
+
q.cols = self.texts(gf, args, at, env)
|
|
1249
|
+
elif name in ("Joins", "InnerJoins") and args:
|
|
1250
|
+
s = tx(args[0])
|
|
1251
|
+
rel = q.model.relations.get(s) if q.model is not None else None
|
|
1252
|
+
if rel is not None:
|
|
1253
|
+
target = self.types.model(rel.target, "gorm")
|
|
1254
|
+
q.joins.append(f"{'INNER' if name == 'InnerJoins' else 'LEFT'} JOIN {target.table if target else marker(s)} "
|
|
1255
|
+
f"ON {marker('the keys of relation ' + s)}")
|
|
1256
|
+
else:
|
|
1257
|
+
q.joins.append(s)
|
|
1258
|
+
elif name == "Preload" and args:
|
|
1259
|
+
a0 = _strip_parens(args[0])
|
|
1260
|
+
q.preloads.append("*" if a0 is not None and _txt(a0).endswith(".Associations") else tx(args[0]))
|
|
1261
|
+
elif name == "Order" and args:
|
|
1262
|
+
q.order.append(tx(args[0]))
|
|
1263
|
+
elif name == "Limit" and args:
|
|
1264
|
+
q.limit = self.num(args[0])
|
|
1265
|
+
elif name == "Offset" and args:
|
|
1266
|
+
q.offset = self.num(args[0])
|
|
1267
|
+
elif name == "Group" and args:
|
|
1268
|
+
q.group.append(tx(args[0]))
|
|
1269
|
+
elif name == "Having" and args:
|
|
1270
|
+
q.having.append(self.pred(gf, args, at, env, "gorm", q, depth))
|
|
1271
|
+
elif name == "Unscoped":
|
|
1272
|
+
q.flags.add("unscoped")
|
|
1273
|
+
elif name == "Clauses":
|
|
1274
|
+
for a in args:
|
|
1275
|
+
self._gorm_clause(q, gf, a, at, env)
|
|
1276
|
+
elif name == "Scopes":
|
|
1277
|
+
q.tail.append(marker("." + name + _txt(call.child_by_field_name("arguments"))))
|
|
1278
|
+
q.dynamic = True
|
|
1279
|
+
elif name in ("Raw", "Exec"):
|
|
1280
|
+
q.flags.add("raw")
|
|
1281
|
+
elif name not in self.GORM_NOOP:
|
|
1282
|
+
q.notes.append(f".{name}() is not shown")
|
|
1283
|
+
return q
|
|
1284
|
+
|
|
1285
|
+
def _gorm_clause(self, q: Q, gf: GoFile, arg: Node, at: Node, env: Env | None) -> None:
|
|
1286
|
+
a = _strip_parens(arg)
|
|
1287
|
+
typ = a.child_by_field_name("type") if a is not None and a.type == "composite_literal" else None
|
|
1288
|
+
name = _txt(typ).split(".")[-1] if typ is not None else ""
|
|
1289
|
+
keyed = dict((k, v) for k, _kn, v in (self._keyed(gf, a, at) or [])) if typ is not None else {}
|
|
1290
|
+
if name == "Locking":
|
|
1291
|
+
strength = self.text(gf, keyed["Strength"], at, env) if "Strength" in keyed else "UPDATE"
|
|
1292
|
+
if _is_marker(strength) or "«" in strength:
|
|
1293
|
+
q.tail.append(marker("FOR " + _txt(keyed["Strength"])))
|
|
1294
|
+
else:
|
|
1295
|
+
q.suffix.append("FOR " + strength.upper())
|
|
1296
|
+
elif name == "OnConflict" and "DoNothing" in keyed and _txt(keyed["DoNothing"]) == "true":
|
|
1297
|
+
q.suffix.append("ON CONFLICT DO NOTHING")
|
|
1298
|
+
elif name == "Returning":
|
|
1299
|
+
q.suffix.append("RETURNING *")
|
|
1300
|
+
else:
|
|
1301
|
+
q.tail.append(marker(_txt(arg)))
|
|
1302
|
+
|
|
1303
|
+
# ---- squirrel ------------------------------------------------------------------------------
|
|
1304
|
+
SQ_NOOP = {"PlaceholderFormat", "RunWith", "RemoveLimit_", "Prepare"}
|
|
1305
|
+
|
|
1306
|
+
def _squirrel(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env: Env | None, depth: int): # noqa: C901
|
|
1307
|
+
tx = lambda n: self.text(gf, n, at, env, depth) # noqa: E731
|
|
1308
|
+
if not q.kind and name in ("Select", "Insert", "Update", "Delete", "Replace"):
|
|
1309
|
+
q.kind = "insert" if name == "Replace" else name.lower()
|
|
1310
|
+
if name == "Select":
|
|
1311
|
+
q.cols = self.texts(gf, args, at, env)
|
|
1312
|
+
elif args:
|
|
1313
|
+
q.table = tx(args[0])
|
|
1314
|
+
if name == "Replace":
|
|
1315
|
+
q.flags.add("replace")
|
|
1316
|
+
return q
|
|
1317
|
+
if name in ("Where", "Having"):
|
|
1318
|
+
p = self.pred(gf, args, at, env, "squirrel", q, depth)
|
|
1319
|
+
if name == "Where":
|
|
1320
|
+
q.and_(p)
|
|
1321
|
+
elif p:
|
|
1322
|
+
q.having.append(p)
|
|
1323
|
+
elif name in ("Columns", "Column") and q.kind == "insert":
|
|
1324
|
+
q.ins_cols = (q.ins_cols or []) + self.texts(gf, args, at, env)
|
|
1325
|
+
elif name == "Columns":
|
|
1326
|
+
q.cols.extend(self.texts(gf, args, at, env))
|
|
1327
|
+
elif name == "Column" and args:
|
|
1328
|
+
q.cols.append(_unsub_alias(tx(args[0])))
|
|
1329
|
+
elif name == "Select" and q.kind == "insert" and args:
|
|
1330
|
+
q.ins_select = _unsub(tx(args[0]))
|
|
1331
|
+
elif name == "From" and q.kind == "update" and args:
|
|
1332
|
+
q.joins.append("FROM " + tx(args[0]))
|
|
1333
|
+
elif name in ("From", "Into", "Table") and args:
|
|
1334
|
+
q.table = tx(args[0])
|
|
1335
|
+
elif name == "FromSelect" and len(args) >= 2:
|
|
1336
|
+
q.table = f"{_sub(tx(args[0]))} AS {tx(args[1])}"
|
|
1337
|
+
elif name in ("Join", "InnerJoin", "LeftJoin", "RightJoin", "CrossJoin", "FullJoin") and args:
|
|
1338
|
+
kind = {"Join": "JOIN", "InnerJoin": "INNER JOIN", "LeftJoin": "LEFT JOIN", "RightJoin": "RIGHT JOIN",
|
|
1339
|
+
"CrossJoin": "CROSS JOIN", "FullJoin": "FULL JOIN"}[name]
|
|
1340
|
+
q.joins.append(f"{kind} {tx(args[0])}")
|
|
1341
|
+
elif name == "JoinClause" and args:
|
|
1342
|
+
q.joins.append(tx(args[0]))
|
|
1343
|
+
elif name == "GroupBy":
|
|
1344
|
+
q.group.extend(self.texts(gf, args, at, env))
|
|
1345
|
+
elif name == "OrderBy":
|
|
1346
|
+
q.order.extend(self.texts(gf, args, at, env))
|
|
1347
|
+
elif name == "OrderByClause" and args:
|
|
1348
|
+
q.order.append(tx(args[0]))
|
|
1349
|
+
elif name == "Limit" and args:
|
|
1350
|
+
q.limit = self.num(args[0])
|
|
1351
|
+
elif name == "Offset" and args:
|
|
1352
|
+
q.offset = self.num(args[0])
|
|
1353
|
+
elif name == "Distinct":
|
|
1354
|
+
q.distinct = True
|
|
1355
|
+
elif name == "Options":
|
|
1356
|
+
q.options.extend(self.texts(gf, args, at, env))
|
|
1357
|
+
elif name in ("Prefix", "PrefixExpr") and args:
|
|
1358
|
+
q.prefix.append(tx(args[0]))
|
|
1359
|
+
elif name in ("Suffix", "SuffixExpr") and args:
|
|
1360
|
+
q.suffix.append(tx(args[0]))
|
|
1361
|
+
elif name == "Values":
|
|
1362
|
+
q.flags.add("values")
|
|
1363
|
+
if q.ins_cols is None:
|
|
1364
|
+
q.sets = ["?"] * len(args) if not any(a.type == "variadic_argument" for a in args) else [marker(_txt(args[0]))]
|
|
1365
|
+
elif name == "Set" and len(args) >= 2:
|
|
1366
|
+
v = self.eval(gf, args[1], at, env, depth + 1)
|
|
1367
|
+
rhs = _sub(render(v)) if isinstance(v, Q) and render(v) else v.text if isinstance(v, Cond) and v.text else "?"
|
|
1368
|
+
q.sets.append(f"{tx(args[0])} = {rhs}")
|
|
1369
|
+
elif name == "SetMap" and args:
|
|
1370
|
+
a0 = _strip_parens(args[0])
|
|
1371
|
+
keyed = self._keyed(gf, a0, at) if a0 is not None and a0.type == "composite_literal" else None
|
|
1372
|
+
if keyed is None:
|
|
1373
|
+
(q.sets if q.kind == "update" else q.tail).append(marker(_txt(args[0])) + (" = ?" if q.kind == "update" else ""))
|
|
1374
|
+
if q.kind == "insert":
|
|
1375
|
+
q.ins_cols = [marker(_txt(args[0]))]
|
|
1376
|
+
elif q.kind == "insert":
|
|
1377
|
+
q.ins_cols = [k for k, _kn, _v in sorted(keyed, key=lambda kv: kv[0])]
|
|
1378
|
+
else:
|
|
1379
|
+
q.sets.extend(f"{k} = ?" for k, _kn, _v in sorted(keyed, key=lambda kv: kv[0]))
|
|
1380
|
+
elif name == "RemoveLimit":
|
|
1381
|
+
q.limit = ""
|
|
1382
|
+
elif name == "RemoveOffset":
|
|
1383
|
+
q.offset = ""
|
|
1384
|
+
elif name == "RemoveColumns":
|
|
1385
|
+
q.cols = []
|
|
1386
|
+
elif name not in self.SQ_NOOP:
|
|
1387
|
+
q.notes.append(f".{name}() is not shown")
|
|
1388
|
+
return q
|
|
1389
|
+
|
|
1390
|
+
# ---- go-sqlbuilder ---------------------------------------------------------------------------
|
|
1391
|
+
SB_COMPARE = {"E": "=", "EQ": "=", "Equal": "=", "NE": "<>", "NEQ": "<>", "NotEqual": "<>", "G": ">", "GT": ">", "GreaterThan": ">",
|
|
1392
|
+
"GE": ">=", "GTE": ">=", "GreaterEqualThan": ">=", "L": "<", "LT": "<", "LessThan": "<", "LE": "<=", "LTE": "<=",
|
|
1393
|
+
"LessEqualThan": "<=", "Like": "LIKE", "ILike": "ILIKE", "NotLike": "NOT LIKE", "NotILike": "NOT ILIKE"}
|
|
1394
|
+
SB_VALUES = set(SB_COMPARE) | {"In", "NotIn", "IsNull", "IsNotNull", "Between", "NotBetween", "Or", "And", "Exists", "NotExists",
|
|
1395
|
+
"Var", "Args", "As", "BuilderAs", "Assign", "Incr", "Decr", "Add", "Sub", "Mul", "Div", "Any", "All",
|
|
1396
|
+
"Some", "Not"}
|
|
1397
|
+
SB_JOIN = {"InnerJoin": "INNER JOIN", "LeftJoin": "LEFT JOIN", "RightJoin": "RIGHT JOIN", "FullJoin": "FULL JOIN",
|
|
1398
|
+
"FullOuterJoin": "FULL OUTER JOIN", "LeftOuterJoin": "LEFT OUTER JOIN", "RightOuterJoin": "RIGHT OUTER JOIN"}
|
|
1399
|
+
|
|
1400
|
+
def _sqlbuilder(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env: Env | None, depth: int): # noqa: C901
|
|
1401
|
+
tx = lambda n: self.text(gf, n, at, env, depth) # noqa: E731
|
|
1402
|
+
if "factory" in q.flags:
|
|
1403
|
+
kinds = {"NewSelectBuilder": "select", "NewInsertBuilder": "insert", "NewUpdateBuilder": "update", "NewDeleteBuilder": "delete"}
|
|
1404
|
+
if name in kinds:
|
|
1405
|
+
out = Q("sqlbuilder", kinds[name])
|
|
1406
|
+
out.engine = q.engine
|
|
1407
|
+
return out
|
|
1408
|
+
return None
|
|
1409
|
+
if "cte" in q.flags:
|
|
1410
|
+
if name == "As" and args:
|
|
1411
|
+
return Cond(f"{q.alias} AS {_sub(tx(args[0]))}")
|
|
1412
|
+
return q
|
|
1413
|
+
# values: comparison helpers return SQL text
|
|
1414
|
+
if name in self.SB_COMPARE and args:
|
|
1415
|
+
return Cond(f"{tx(args[0])} {self.SB_COMPARE[name]} ?")
|
|
1416
|
+
if name in ("In", "NotIn") and args:
|
|
1417
|
+
return Cond(f"{tx(args[0])} {'IN' if name == 'In' else 'NOT IN'} (?)")
|
|
1418
|
+
if name in ("IsNull", "IsNotNull") and args:
|
|
1419
|
+
return Cond(f"{tx(args[0])} IS {'NOT ' if name == 'IsNotNull' else ''}NULL")
|
|
1420
|
+
if name in ("Between", "NotBetween") and args:
|
|
1421
|
+
return Cond(f"{tx(args[0])} {'NOT ' if name == 'NotBetween' else ''}BETWEEN ? AND ?")
|
|
1422
|
+
if name in ("Or", "And"):
|
|
1423
|
+
parts = self.texts(gf, args, at, env)
|
|
1424
|
+
return Cond("(" + f" {name.upper()} ".join(parts) + ")") if parts else Cond()
|
|
1425
|
+
if name in ("Exists", "NotExists") and args:
|
|
1426
|
+
return Cond(f"{'NOT ' if name == 'NotExists' else ''}EXISTS {_sub(tx(args[0]))}")
|
|
1427
|
+
if name == "Var" and args:
|
|
1428
|
+
v = self.eval(gf, args[0], at, env, depth + 1)
|
|
1429
|
+
sub = render(v) if isinstance(v, Q) else ""
|
|
1430
|
+
return Cond(f"({sub})" if sub else "?")
|
|
1431
|
+
if name in ("Args",):
|
|
1432
|
+
return None
|
|
1433
|
+
if name == "As" and len(args) == 2:
|
|
1434
|
+
return Cond(f"{tx(args[0])} AS {tx(args[1])}")
|
|
1435
|
+
if name == "BuilderAs" and len(args) == 2:
|
|
1436
|
+
return Cond(f"{_sub(tx(args[0]))} AS {tx(args[1])}")
|
|
1437
|
+
if name == "Assign" and args:
|
|
1438
|
+
return Cond(f"{tx(args[0])} = ?")
|
|
1439
|
+
if name in ("Incr", "Decr") and args:
|
|
1440
|
+
return Cond(f"{tx(args[0])} = {tx(args[0])} {'+' if name == 'Incr' else '-'} 1")
|
|
1441
|
+
if name in ("Add", "Sub", "Mul", "Div") and args:
|
|
1442
|
+
op = {"Add": "+", "Sub": "-", "Mul": "*", "Div": "/"}[name]
|
|
1443
|
+
return Cond(f"{tx(args[0])} = {tx(args[0])} {op} ?")
|
|
1444
|
+
# changes
|
|
1445
|
+
if name == "Select":
|
|
1446
|
+
q.kind, q.cols = "select", self.texts(gf, args, at, env)
|
|
1447
|
+
elif name == "SelectMore":
|
|
1448
|
+
q.cols.extend(self.texts(gf, args, at, env))
|
|
1449
|
+
elif name == "Distinct":
|
|
1450
|
+
q.distinct = True
|
|
1451
|
+
elif name == "From":
|
|
1452
|
+
q.table = ", ".join(self.texts(gf, args, at, env))
|
|
1453
|
+
elif name in ("InsertInto", "InsertIgnoreInto", "ReplaceInto", "Update", "DeleteFrom") and args:
|
|
1454
|
+
q.kind = {"InsertInto": "insert", "InsertIgnoreInto": "insert", "ReplaceInto": "insert", "Update": "update",
|
|
1455
|
+
"DeleteFrom": "delete"}[name]
|
|
1456
|
+
q.table = tx(args[0])
|
|
1457
|
+
elif name == "Cols":
|
|
1458
|
+
q.ins_cols = self.texts(gf, args, at, env)
|
|
1459
|
+
elif name == "Values":
|
|
1460
|
+
q.flags.add("values")
|
|
1461
|
+
elif name in ("Set", "SetMore"):
|
|
1462
|
+
if name == "Set":
|
|
1463
|
+
q.sets = []
|
|
1464
|
+
q.sets.extend(self.texts(gf, args, at, env))
|
|
1465
|
+
elif name == "Where":
|
|
1466
|
+
for p in self.texts(gf, args, at, env):
|
|
1467
|
+
q.and_(p)
|
|
1468
|
+
elif name == "AddWhereClause" and args:
|
|
1469
|
+
q.and_("(" + marker(_txt(args[0])) + ")")
|
|
1470
|
+
elif name == "Join" and args:
|
|
1471
|
+
q.joins.append(f"JOIN {tx(args[0])}" + (" ON " + " AND ".join(self.texts(gf, args[1:], at, env)) if len(args) > 1 else ""))
|
|
1472
|
+
elif name == "JoinWithOption" and len(args) >= 2:
|
|
1473
|
+
kind = self.SB_JOIN.get(_txt(args[0]).split(".")[-1], "")
|
|
1474
|
+
kind = kind or marker(_txt(args[0])) + " JOIN"
|
|
1475
|
+
q.joins.append(f"{kind} {tx(args[1])}" + (" ON " + " AND ".join(self.texts(gf, args[2:], at, env)) if len(args) > 2 else ""))
|
|
1476
|
+
elif name == "GroupBy":
|
|
1477
|
+
q.group.extend(self.texts(gf, args, at, env))
|
|
1478
|
+
elif name == "Having":
|
|
1479
|
+
q.having.extend(self.texts(gf, args, at, env))
|
|
1480
|
+
elif name == "OrderBy":
|
|
1481
|
+
q.order.extend(self.texts(gf, args, at, env))
|
|
1482
|
+
elif name in ("OrderByAsc", "OrderByDesc") and args:
|
|
1483
|
+
q.order.append(f"{tx(args[0])} {'ASC' if name == 'OrderByAsc' else 'DESC'}")
|
|
1484
|
+
elif name in ("Asc", "Desc"):
|
|
1485
|
+
if q.order:
|
|
1486
|
+
q.order[-1] = f"{q.order[-1]} {name.upper()}"
|
|
1487
|
+
elif name == "Limit" and args:
|
|
1488
|
+
q.limit = self.num(args[0])
|
|
1489
|
+
elif name == "Offset" and args:
|
|
1490
|
+
q.offset = self.num(args[0])
|
|
1491
|
+
elif name == "SQL" and args:
|
|
1492
|
+
q.suffix.append(tx(args[0]))
|
|
1493
|
+
elif name == "With" and args:
|
|
1494
|
+
q.prefix.append("WITH " + ", ".join(self.texts(gf, args, at, env)))
|
|
1495
|
+
elif name in ("SetFlavor", "Clone", "TableNames", "NumCol", "WhereClause"):
|
|
1496
|
+
pass
|
|
1497
|
+
else:
|
|
1498
|
+
q.notes.append(f".{name}() is not shown")
|
|
1499
|
+
return q
|
|
1500
|
+
|
|
1501
|
+
# ---- xorm.io/builder -------------------------------------------------------------------------
|
|
1502
|
+
def _xbuilder(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, at: Node, env: Env | None, depth: int):
|
|
1503
|
+
tx = lambda n: self.text(gf, n, at, env, depth) # noqa: E731
|
|
1504
|
+
if name == "Select":
|
|
1505
|
+
q.kind, q.cols = "select", self.texts(gf, args, at, env)
|
|
1506
|
+
elif name in ("From", "Into") and args:
|
|
1507
|
+
q.table = _sub_from(tx(args[0]))
|
|
1508
|
+
if len(args) > 1:
|
|
1509
|
+
q.alias = tx(args[1])
|
|
1510
|
+
elif name in ("Where", "And"):
|
|
1511
|
+
q.and_(self.pred(gf, args, at, env, "xbuilder", q, depth))
|
|
1512
|
+
elif name == "Or":
|
|
1513
|
+
q.or_(self.pred(gf, args, at, env, "xbuilder", q, depth))
|
|
1514
|
+
elif name == "Join" and len(args) >= 3:
|
|
1515
|
+
q.joins.append(f"{tx(args[0]).upper()} JOIN {self._join_table(gf, args[1], at, env, 'xorm')} ON {self.pred(gf, args[2:], at, env, 'xbuilder', q, depth)}")
|
|
1516
|
+
elif name in ("InnerJoin", "LeftJoin", "RightJoin", "CrossJoin", "FullJoin") and len(args) >= 2:
|
|
1517
|
+
q.joins.append(f"{name[:-4].upper()} JOIN {self._join_table(gf, args[0], at, env, 'xorm')} ON {self.pred(gf, args[1:], at, env, 'xbuilder', q, depth)}")
|
|
1518
|
+
elif name == "GroupBy" and args:
|
|
1519
|
+
q.group.append(tx(args[0]))
|
|
1520
|
+
elif name == "Having" and args:
|
|
1521
|
+
q.having.append(tx(args[0]))
|
|
1522
|
+
elif name == "OrderBy" and args:
|
|
1523
|
+
q.order.append(tx(args[0]))
|
|
1524
|
+
elif name == "Limit" and args:
|
|
1525
|
+
q.limit = self.num(args[0])
|
|
1526
|
+
if len(args) > 1:
|
|
1527
|
+
q.offset = self.num(args[1])
|
|
1528
|
+
elif name == "Delete":
|
|
1529
|
+
q.kind = "delete"
|
|
1530
|
+
for a in args:
|
|
1531
|
+
q.and_(self.pred(gf, [a], at, env, "xbuilder", q, depth))
|
|
1532
|
+
elif name in ("Insert", "Update"):
|
|
1533
|
+
q.kind = name.lower()
|
|
1534
|
+
q.tail.append(marker(_txt(call.child_by_field_name("arguments")))) if args else None
|
|
1535
|
+
else:
|
|
1536
|
+
q.notes.append(f".{name}() is not shown")
|
|
1537
|
+
return q
|
|
1538
|
+
|
|
1539
|
+
# ================================================================ statements
|
|
1540
|
+
def model_token(self, gf: GoFile, node: Node, at: Node) -> tuple[str, str] | None:
|
|
1541
|
+
"""What a caller must supply for the model behind `node`: a type parameter, or a parameter of type any."""
|
|
1542
|
+
n = _strip_parens(node)
|
|
1543
|
+
while n is not None and n.type in ("unary_expression", "variadic_argument", "index_expression", "slice_expression"):
|
|
1544
|
+
n = _strip_parens(n.child_by_field_name("operand") or (n.named_children[0] if n.named_children else None))
|
|
1545
|
+
func = gf._enclosing(node, FUNC_DECL)
|
|
1546
|
+
if func is None:
|
|
1547
|
+
return None
|
|
1548
|
+
ref = self.types.type_of(gf, node, at)
|
|
1549
|
+
if ref is not None:
|
|
1550
|
+
base = T.base_type(ref.text)[0]
|
|
1551
|
+
if base in self.types.type_params(func):
|
|
1552
|
+
return ("typeparam", base)
|
|
1553
|
+
if n is not None and n.type == "identifier":
|
|
1554
|
+
local = gf._local(_txt(n), at)
|
|
1555
|
+
if local is not None and local[1].kind == "param" and local[1].node.id == func.id:
|
|
1556
|
+
base = T.base_type(param_type(func, _txt(n)))[0]
|
|
1557
|
+
if base in ("any", "interface{}"):
|
|
1558
|
+
return ("param", _txt(n))
|
|
1559
|
+
return None
|
|
1560
|
+
|
|
1561
|
+
def targets(self, gf: GoFile, node: Node, at: Node, lib: str, bind: dict | None):
|
|
1562
|
+
"""(model, file, node, anchor) for a bean or destination argument: one per value a wrapper's caller passed.
|
|
1563
|
+
Raises Unresolved("wrapper") with the token when the caller is not known yet."""
|
|
1564
|
+
ref = self.types.type_of(gf, node, at)
|
|
1565
|
+
model = self.types.model(ref, lib)
|
|
1566
|
+
if model is not None or ref is not None and self.types.lib_of(ref) is None and T.base_type(ref.text)[0] in T._GO_SCALARS - {"any", "interface{}"}:
|
|
1567
|
+
return [(model, gf, node, at)]
|
|
1568
|
+
tok = self.model_token(gf, node, at)
|
|
1569
|
+
if tok is None:
|
|
1570
|
+
return [(None, gf, node, at)]
|
|
1571
|
+
if not bind or tok not in bind:
|
|
1572
|
+
err = Unresolved("wrapper")
|
|
1573
|
+
err.token = tok
|
|
1574
|
+
raise err
|
|
1575
|
+
out = []
|
|
1576
|
+
for b in bind[tok]:
|
|
1577
|
+
if isinstance(b, TypeRef):
|
|
1578
|
+
out.append((self.types.model(b, lib), None, None, None))
|
|
1579
|
+
else:
|
|
1580
|
+
bgf, bnode, bat = b
|
|
1581
|
+
out.append((self.types.model(self.types.type_of(bgf, bnode, bat), lib), bgf, bnode, bat))
|
|
1582
|
+
return out
|
|
1583
|
+
|
|
1584
|
+
def bean_conds(self, gf: GoFile | None, node: Node | None, at: Node | None, model: Model | None) -> str:
|
|
1585
|
+
"""Conditions xorm adds from the non-zero fields of a bean, as far as the source shows them."""
|
|
1586
|
+
if gf is None or node is None or model is None:
|
|
1587
|
+
return ""
|
|
1588
|
+
n = _strip_parens(node)
|
|
1589
|
+
if n is not None and n.type == "unary_expression":
|
|
1590
|
+
n = _strip_parens(n.child_by_field_name("operand"))
|
|
1591
|
+
if n is None:
|
|
1592
|
+
return ""
|
|
1593
|
+
fields: list[str] = []
|
|
1594
|
+
if n.type == "composite_literal":
|
|
1595
|
+
keyed = self._keyed(gf, n, at) or []
|
|
1596
|
+
fields = [_txt(kn) for _k, kn, _v in keyed]
|
|
1597
|
+
elif n.type == "call_expression":
|
|
1598
|
+
return "" if callee_name(n.child_by_field_name("function"))[0] == "new" else "(" + marker("non-zero fields of " + _txt(n)) + ")"
|
|
1599
|
+
elif n.type == "identifier":
|
|
1600
|
+
local = gf._local(_txt(n), at)
|
|
1601
|
+
if local is None or local[1].kind in ("param", "range"):
|
|
1602
|
+
return "(" + marker("non-zero fields of " + _txt(n)) + ")"
|
|
1603
|
+
_top, decl, _later = local
|
|
1604
|
+
v = _strip_parens(decl.value) if decl.value is not None else None
|
|
1605
|
+
if v is not None and v.type == "unary_expression":
|
|
1606
|
+
v = _strip_parens(v.child_by_field_name("operand"))
|
|
1607
|
+
if v is not None and v.type == "composite_literal":
|
|
1608
|
+
fields = [_txt(kn) for _k, kn, _v in (self._keyed(gf, v, decl.node) or [])]
|
|
1609
|
+
elif v is not None and not (v.type == "call_expression" and callee_name(v.child_by_field_name("function"))[0] == "new"):
|
|
1610
|
+
return "(" + marker("non-zero fields of " + _txt(n)) + ")"
|
|
1611
|
+
between = gf.src[decl.node.end_byte: at.start_byte].decode("utf-8", "replace")
|
|
1612
|
+
for m in re.finditer(rf"\b{re.escape(_txt(n))}\.(\w+)\s*=[^=]", between):
|
|
1613
|
+
if m.group(1) not in fields:
|
|
1614
|
+
fields.append(m.group(1))
|
|
1615
|
+
else:
|
|
1616
|
+
return "(" + marker("non-zero fields of " + _txt(n)) + ")"
|
|
1617
|
+
parts = []
|
|
1618
|
+
for f in fields:
|
|
1619
|
+
col = model.col(f)
|
|
1620
|
+
parts.append(f"{T.ident(col.name)} = ?" if col is not None else "(" + marker("non-zero fields of " + f) + ")")
|
|
1621
|
+
return " AND ".join(parts)
|
|
1622
|
+
|
|
1623
|
+
def statements(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, bind: dict | None = None) -> list[Stmt]:
|
|
1624
|
+
if q.opaque:
|
|
1625
|
+
raise Unresolved(q.opaque)
|
|
1626
|
+
if "raw" in q.flags:
|
|
1627
|
+
raise Unresolved("raw SQL in the chain: the string extractor reports it")
|
|
1628
|
+
fn = {"xorm": self._xorm_final, "gorm": self._gorm_final, "bun": self._bun_final}.get(q.lib)
|
|
1629
|
+
if fn is not None:
|
|
1630
|
+
return fn(q, name, args, call, gf, bind)
|
|
1631
|
+
if q.lib in ("squirrel", "sqlbuilder", "xbuilder"):
|
|
1632
|
+
if name == "BuildWithFlavor" and args and not q.engine:
|
|
1633
|
+
q.engine = FLAVORS.get(_txt(args[0]).split(".")[-1], "")
|
|
1634
|
+
sql = render(q)
|
|
1635
|
+
if not sql:
|
|
1636
|
+
raise Unresolved(_why_not(q))
|
|
1637
|
+
if q.lib == "sqlbuilder":
|
|
1638
|
+
sql = sql.replace("$$", "$") # go-sqlbuilder's escape for a literal dollar sign
|
|
1639
|
+
notes = list(q.notes)
|
|
1640
|
+
return [Stmt(sql, q.kind or "select", _table_word(q.table), "medium" if q.dynamic or notes else "high", notes, q.engine)]
|
|
1641
|
+
raise Unresolved("library not translated")
|
|
1642
|
+
|
|
1643
|
+
def _xorm_final(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, bind: dict | None) -> list[Stmt]: # noqa: C901
|
|
1644
|
+
out: list[Stmt] = []
|
|
1645
|
+
if name in ("Insert", "InsertOne", "InsertMulti"):
|
|
1646
|
+
beans = [t for a in args for t in self.targets(gf, a, call, "xorm", bind)]
|
|
1647
|
+
if not beans:
|
|
1648
|
+
raise Unresolved("no bean")
|
|
1649
|
+
for model, _g, node, _a in beans:
|
|
1650
|
+
if model is None and not q.table:
|
|
1651
|
+
raise Unresolved("the inserted value is not a model this scan can read" + _what(node))
|
|
1652
|
+
cols = [T.ident(c.name) for c in model.cols if not c.autoincr] if model is not None else []
|
|
1653
|
+
table = q.table or T.ident(model.table)
|
|
1654
|
+
out.append(self._stmt(q, f"INSERT INTO {table} ({', '.join(cols) or marker('columns')}) VALUES ({', '.join('?' for _ in cols) or marker('values')})",
|
|
1655
|
+
"insert", model, table))
|
|
1656
|
+
return out
|
|
1657
|
+
bean = args[0] if args else None
|
|
1658
|
+
tlist = self.targets(gf, bean, call, "xorm", bind) if bean is not None else [(None, None, None, None)]
|
|
1659
|
+
cond_bean = args[1] if name in ("Find", "FindAndCount", "Update") and len(args) > 1 else None
|
|
1660
|
+
for model, bgf, bnode, bat in tlist:
|
|
1661
|
+
s = q.clone()
|
|
1662
|
+
use = s.model if s.model is not None else model # the model whose table is read
|
|
1663
|
+
table = s.table or (T.ident(use.table) if use is not None else "")
|
|
1664
|
+
if not table:
|
|
1665
|
+
raise Unresolved("no table: the destination is not a model this scan can read" + _what(bnode or bean))
|
|
1666
|
+
if "«" in table and "(" not in table:
|
|
1667
|
+
raise Unresolved("the table name is decided at run time")
|
|
1668
|
+
s.table = table
|
|
1669
|
+
shape = model if model is not None else s.model # the struct whose fields are the columns
|
|
1670
|
+
if s.use_pk:
|
|
1671
|
+
pk = (shape.pk if shape is not None else []) or ["id"]
|
|
1672
|
+
s.where = f"{T.ident(pk[0])} = ?" + (f" AND {_paren(s.where)}" if s.where else "")
|
|
1673
|
+
if "noauto" not in s.flags and name in ("Get", "Count", "Exist", "Delete", "Iterate", "Rows", "Sum", "SumInt", "Sums", "SumsInt") \
|
|
1674
|
+
and bnode is not None and model is not None:
|
|
1675
|
+
s.and_(self.bean_conds(bgf, bnode, bat, model))
|
|
1676
|
+
if cond_bean is not None and "noauto" not in s.flags:
|
|
1677
|
+
cm = self.types.model(self.types.type_of(gf, cond_bean, call), "xorm") or shape
|
|
1678
|
+
s.and_(self.bean_conds(gf, cond_bean, call, cm))
|
|
1679
|
+
use = shape
|
|
1680
|
+
deleted = use.role("deleted") if use is not None and "unscoped" not in s.flags else ""
|
|
1681
|
+
if deleted and name not in ("Insert", "Truncate"):
|
|
1682
|
+
s.and_(f"{deleted} IS NULL")
|
|
1683
|
+
if name in ("Find", "Iterate", "Rows", "Get", "FindAndCount"):
|
|
1684
|
+
if not s.cols:
|
|
1685
|
+
if s.joins and not s.group:
|
|
1686
|
+
s.cols = ["*"]
|
|
1687
|
+
elif use is not None:
|
|
1688
|
+
s.cols = [T.ident(c.name) for c in use.cols if c.name not in s.omit]
|
|
1689
|
+
else:
|
|
1690
|
+
s.cols = ["*"]
|
|
1691
|
+
if name == "FindAndCount":
|
|
1692
|
+
c = s.clone()
|
|
1693
|
+
c.cols, c.order, c.limit, c.offset = ["count(*)"], [], "", ""
|
|
1694
|
+
c.tail = [t for t in c.tail if not re.match(r"«\.(Limit|OrderBy|Asc|Desc)\b", t)]
|
|
1695
|
+
c.kind = "select"
|
|
1696
|
+
out.append(self._stmt(c, render(c), "count", use, table, ["FindAndCount: the count statement"]))
|
|
1697
|
+
if name == "Get":
|
|
1698
|
+
s.limit = "1"
|
|
1699
|
+
s.kind = "select"
|
|
1700
|
+
out.append(self._stmt(s, render(s), "select", use, table, ["FindAndCount: the rows statement"] if name == "FindAndCount" else None))
|
|
1701
|
+
elif name in ("Count", "Exist"):
|
|
1702
|
+
s.kind = "select"
|
|
1703
|
+
s.order = []
|
|
1704
|
+
if name == "Count":
|
|
1705
|
+
inner = ", ".join(s.cols)
|
|
1706
|
+
s.cols = [f"count({('DISTINCT ' if s.distinct else '') + inner if inner else '*'})"]
|
|
1707
|
+
s.distinct = False
|
|
1708
|
+
elif model is not None and bean is not None:
|
|
1709
|
+
# Exist(&bean) with a struct: xorm runs the Get statement with LIMIT 1
|
|
1710
|
+
s.limit = "1"
|
|
1711
|
+
if not s.cols:
|
|
1712
|
+
s.cols = ["*"] if s.joins else [T.ident(c.name) for c in model.cols if c.name not in s.omit]
|
|
1713
|
+
else:
|
|
1714
|
+
s.cols, s.limit = ["1"], "1"
|
|
1715
|
+
out.append(self._stmt(s, render(s), name.lower(), use, table))
|
|
1716
|
+
elif name in ("Sum", "SumInt", "Sums", "SumsInt"):
|
|
1717
|
+
s.kind = "select"
|
|
1718
|
+
s.cols = [f"COALESCE(sum({c}), 0)" for c in self.texts(gf, args[1:], call)]
|
|
1719
|
+
out.append(self._stmt(s, render(s), "sum", use, table))
|
|
1720
|
+
elif name == "Update":
|
|
1721
|
+
s.kind = "update"
|
|
1722
|
+
lit = _strip_parens(bnode) if bnode is not None else None
|
|
1723
|
+
if lit is not None and lit.type == "unary_expression":
|
|
1724
|
+
lit = _strip_parens(lit.child_by_field_name("operand"))
|
|
1725
|
+
ltype = lit.child_by_field_name("type") if lit is not None and lit.type == "composite_literal" else None
|
|
1726
|
+
if s.cols:
|
|
1727
|
+
s.sets = [f"{c.strip()} = ?" for cs in s.cols for c in (cs.split(",") if "«" not in cs and "(" not in cs else [cs])] + s.sets
|
|
1728
|
+
elif ltype is not None and ltype.type == "map_type":
|
|
1729
|
+
s.sets = [f"{k} = ?" for k, _kn, _v in (self._keyed(bgf, lit, bat) or [])] + s.sets
|
|
1730
|
+
elif bnode is not None and use is not None:
|
|
1731
|
+
keyed = self._keyed(bgf, lit, bat) if lit is not None and lit.type == "composite_literal" else None
|
|
1732
|
+
if keyed is not None:
|
|
1733
|
+
s.sets = [f"{T.ident(use.col(_txt(kn)).name)} = ?" for _k, kn, _v in keyed if use.col(_txt(kn)) is not None] + s.sets
|
|
1734
|
+
elif not s.sets:
|
|
1735
|
+
s.sets = [marker("non-zero fields of " + _txt(bnode)) + " = ?"]
|
|
1736
|
+
updated = use.role("updated") if use is not None else ""
|
|
1737
|
+
if updated and not any(x.startswith(updated + " ") for x in s.sets):
|
|
1738
|
+
s.sets.append(f"{updated} = ?")
|
|
1739
|
+
if not s.sets:
|
|
1740
|
+
s.sets = [marker("columns") + " = ?"]
|
|
1741
|
+
out.append(self._stmt(s, render(s), "update", use, table))
|
|
1742
|
+
elif name == "Delete":
|
|
1743
|
+
s.kind = "delete"
|
|
1744
|
+
if deleted:
|
|
1745
|
+
s.kind, s.sets = "update", [f"{deleted} = ?"]
|
|
1746
|
+
out.append(self._stmt(s, render(s), "delete", use, table, ["soft delete: the model has a deleted column"] if deleted else None))
|
|
1747
|
+
elif name == "Truncate":
|
|
1748
|
+
out.append(self._stmt(s, f"TRUNCATE TABLE {table}", "truncate", use, table))
|
|
1749
|
+
return out
|
|
1750
|
+
|
|
1751
|
+
@staticmethod
|
|
1752
|
+
def _stmt(q: Q, sql: str, op: str, model: Model | None, table: str, notes: list[str] | None = None) -> Stmt:
|
|
1753
|
+
if not sql:
|
|
1754
|
+
raise Unresolved(_why_not(q))
|
|
1755
|
+
if model is not None:
|
|
1756
|
+
model.used = True
|
|
1757
|
+
all_notes = (notes or []) + q.notes
|
|
1758
|
+
conf = "medium" if q.dynamic or q.notes else "high"
|
|
1759
|
+
return Stmt(sql, op, model.name if model is not None else _table_word(table), conf, all_notes, q.engine)
|
|
1760
|
+
|
|
1761
|
+
def _gorm_final(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile, bind: dict | None) -> list[Stmt]: # noqa: C901
|
|
1762
|
+
if q.assoc:
|
|
1763
|
+
return self._gorm_assoc(q, name, args, call, gf)
|
|
1764
|
+
if "model_unknown" in q.flags and not q.table:
|
|
1765
|
+
raise Unresolved("the model is not a struct this scan can read")
|
|
1766
|
+
out: list[Stmt] = []
|
|
1767
|
+
dest = None
|
|
1768
|
+
if name in ("First", "Take", "Last", "Find", "FindInBatches", "Scan", "Create", "CreateInBatches", "Save", "Delete", "FirstOrCreate",
|
|
1769
|
+
"FirstOrInit") and args:
|
|
1770
|
+
dest = args[0]
|
|
1771
|
+
elif name in ("Updates", "UpdateColumns") and args and q.model is None and not q.table:
|
|
1772
|
+
dest = args[0]
|
|
1773
|
+
q.flags.add("model_instance")
|
|
1774
|
+
elif name == "Pluck" and len(args) > 1:
|
|
1775
|
+
dest = None
|
|
1776
|
+
model = q.model
|
|
1777
|
+
dmodel = None
|
|
1778
|
+
if dest is not None:
|
|
1779
|
+
tl = self.targets(gf, dest, call, "gorm", bind)
|
|
1780
|
+
dmodel = tl[0][0]
|
|
1781
|
+
if model is None and not q.table:
|
|
1782
|
+
model = dmodel
|
|
1783
|
+
table = q.table or (T.ident(model.table) if model is not None else "")
|
|
1784
|
+
if not table:
|
|
1785
|
+
raise Unresolved("no table: the destination is not a model this scan can read" + _what(dest))
|
|
1786
|
+
if "«" in table and "(" not in table:
|
|
1787
|
+
raise Unresolved("the table name is decided at run time")
|
|
1788
|
+
s = q.clone()
|
|
1789
|
+
s.table = table
|
|
1790
|
+
tname = _table_word(table) if q.table else table
|
|
1791
|
+
deleted = model.role("deleted") if model is not None and not q.table else ""
|
|
1792
|
+
pk = (model.pk if model is not None else []) or ["id"]
|
|
1793
|
+
notes: list[str] = []
|
|
1794
|
+
|
|
1795
|
+
def inline(conds: list[Node]) -> None:
|
|
1796
|
+
if not conds:
|
|
1797
|
+
return
|
|
1798
|
+
c0 = _strip_parens(conds[0])
|
|
1799
|
+
if c0 is None:
|
|
1800
|
+
return
|
|
1801
|
+
if c0.type in STRING_TYPES or (c0.type in ("identifier", "selector_expression", "binary_expression", "call_expression")
|
|
1802
|
+
and gf.resolve(c0, call, 0) is not None
|
|
1803
|
+
and not re.fullmatch(r"«[^»]*»|\d+", gf.resolve(c0, call, 0).text.strip())):
|
|
1804
|
+
s.and_(self.pred(gf, conds, call, None, "gorm", s))
|
|
1805
|
+
return
|
|
1806
|
+
got = self._gorm_struct_cond(gf, c0, call)
|
|
1807
|
+
if got is not None:
|
|
1808
|
+
s.and_(got)
|
|
1809
|
+
return
|
|
1810
|
+
ref = self.types.type_of(gf, c0, call)
|
|
1811
|
+
if ref is not None and ref.text.lstrip("*").startswith("[]"):
|
|
1812
|
+
s.and_(f"{tname}.{pk[0]} IN (?)")
|
|
1813
|
+
elif ref is not None and ref.text.strip() == "string" and len(conds) > 1:
|
|
1814
|
+
s.and_(marker(_txt(c0)))
|
|
1815
|
+
else:
|
|
1816
|
+
s.and_(f"{tname}.{pk[0]} = ?")
|
|
1817
|
+
|
|
1818
|
+
soft = f"{tname}.{deleted} IS NULL" if deleted and "unscoped" not in s.flags else ""
|
|
1819
|
+
if name in ("First", "Take", "Last", "Find", "FindInBatches", "Scan", "Row", "Rows", "Pluck", "Count", "FirstOrCreate", "FirstOrInit"):
|
|
1820
|
+
s.kind = "select"
|
|
1821
|
+
if name in ("First", "Take", "Last", "Find", "FirstOrCreate", "FirstOrInit"):
|
|
1822
|
+
inline(args[1:])
|
|
1823
|
+
s.and_(soft)
|
|
1824
|
+
if name == "Count":
|
|
1825
|
+
s.cols = [f"count({'DISTINCT ' + ', '.join(s.cols) if s.distinct and s.cols else '*'})"]
|
|
1826
|
+
s.distinct, s.order, s.limit, s.offset = False, [], "", ""
|
|
1827
|
+
out.append(self._stmt(s, render(s), "count", model, table))
|
|
1828
|
+
return out
|
|
1829
|
+
if name == "Pluck" and args and len(s.cols) != 1:
|
|
1830
|
+
s.cols = [self.text(gf, args[0], call)] # one Select() before Pluck is kept (`DISTINCT col`)
|
|
1831
|
+
if name == "FindInBatches":
|
|
1832
|
+
s.order = s.order or [f"{tname}.{pk[0]}"]
|
|
1833
|
+
s.limit = self.num(args[1]) if len(args) > 1 else "?"
|
|
1834
|
+
notes.append("FindInBatches: this statement repeats per batch, continuing after the last primary key")
|
|
1835
|
+
if not s.cols:
|
|
1836
|
+
if model is not None and not s.joins and not q.table and (dmodel is None or dmodel is model):
|
|
1837
|
+
s.cols = [T.ident(c.name) for c in model.cols if c.name not in s.omit]
|
|
1838
|
+
elif dmodel is not None and dmodel is not model and dmodel.cols and name != "Scan":
|
|
1839
|
+
s.cols = [T.ident(c.name) for c in dmodel.cols] # a smaller struct: GORM selects its fields
|
|
1840
|
+
else:
|
|
1841
|
+
s.cols = [f"{tname}.*" if s.joins else "*"]
|
|
1842
|
+
if name in ("First", "Last", "FirstOrCreate", "FirstOrInit") and not s.order:
|
|
1843
|
+
s.order = [f"{tname}.{pk[0]}" + (" DESC" if name == "Last" else "")]
|
|
1844
|
+
if name in ("First", "Take", "Last", "FirstOrCreate", "FirstOrInit"):
|
|
1845
|
+
s.limit = "1"
|
|
1846
|
+
out.append(self._stmt(s, render(s), "select", model, table, notes))
|
|
1847
|
+
if name == "FirstOrCreate" and model is not None:
|
|
1848
|
+
cols = [T.ident(c.name) for c in model.cols if not c.autoincr]
|
|
1849
|
+
out.append(self._stmt(Q("gorm"), f"INSERT INTO {table} ({', '.join(cols)}) VALUES ({', '.join('?' for _ in cols)})", "insert",
|
|
1850
|
+
model, table, ["FirstOrCreate: the insert that runs when no row matched"]))
|
|
1851
|
+
out.extend(self._gorm_preloads(q, model, soft_ok="unscoped" not in s.flags))
|
|
1852
|
+
return out
|
|
1853
|
+
if name in ("Create", "CreateInBatches"):
|
|
1854
|
+
cols = [T.ident(c.name) for c in model.cols if not c.autoincr and c.name not in s.omit] if model is not None else []
|
|
1855
|
+
if s.cols and "select" in s.flags:
|
|
1856
|
+
cols = s.cols
|
|
1857
|
+
sql = f"INSERT INTO {table} ({', '.join(cols) or marker('columns')}) VALUES ({', '.join('?' for _ in cols) or marker('values')})"
|
|
1858
|
+
sql = " ".join([sql] + s.suffix + [f"/* {t} */" for t in s.tail])
|
|
1859
|
+
return [self._stmt(s, sql, "insert", model, table)]
|
|
1860
|
+
if name == "Save":
|
|
1861
|
+
cols = [T.ident(c.name) for c in model.cols if not c.pk and c.name not in s.omit] if model is not None else []
|
|
1862
|
+
s.kind, s.sets = "update", [f"{c} = ?" for c in cols] or [marker("columns") + " = ?"]
|
|
1863
|
+
if not s.where:
|
|
1864
|
+
s.and_(f"{pk[0]} = ?")
|
|
1865
|
+
return [self._stmt(s, render(s), "update", model, table,
|
|
1866
|
+
["Save: an UPDATE by primary key; GORM inserts instead when the key is zero or no row matched"])]
|
|
1867
|
+
if name in ("Update", "Updates", "UpdateColumn", "UpdateColumns"):
|
|
1868
|
+
s.kind = "update"
|
|
1869
|
+
if name in ("Update", "UpdateColumn") and args:
|
|
1870
|
+
v = self.eval(gf, args[1], call, None) if len(args) > 1 else None
|
|
1871
|
+
s.sets = [f"{self.text(gf, args[0], call)} = {v.text if isinstance(v, Cond) and v.text else '?'}"]
|
|
1872
|
+
elif args:
|
|
1873
|
+
a0 = _strip_parens(args[0])
|
|
1874
|
+
lit = a0
|
|
1875
|
+
if lit is not None and lit.type == "unary_expression":
|
|
1876
|
+
lit = _strip_parens(lit.child_by_field_name("operand"))
|
|
1877
|
+
keyed = self._keyed(gf, lit, call) if lit is not None and lit.type == "composite_literal" else None
|
|
1878
|
+
if keyed is not None and lit.child_by_field_name("type") is not None and lit.child_by_field_name("type").type == "map_type":
|
|
1879
|
+
s.sets = [f"{k} = ?" for k, _kn, _v in keyed]
|
|
1880
|
+
elif keyed is not None and model is not None:
|
|
1881
|
+
um = self.types.model(TypeRef(_txt(lit.child_by_field_name("type")), gf), "gorm") or model
|
|
1882
|
+
s.sets = [f"{T.ident(um.col(_txt(kn)).name)} = ?" for _k, kn, _v in keyed if um.col(_txt(kn)) is not None]
|
|
1883
|
+
if not s.sets:
|
|
1884
|
+
if s.cols and "select" in s.flags and "*" not in s.cols:
|
|
1885
|
+
s.sets = [f"{c} = ?" for c in s.cols]
|
|
1886
|
+
else:
|
|
1887
|
+
s.sets = [marker("non-zero fields of " + _txt(args[0])) + " = ?"]
|
|
1888
|
+
updated = model.role("updated") if model is not None else ""
|
|
1889
|
+
if updated and name in ("Update", "Updates") and not any(x.startswith(updated + " ") for x in s.sets):
|
|
1890
|
+
s.sets.append(f"{updated} = ?")
|
|
1891
|
+
if "model_instance" in s.flags and not s.where:
|
|
1892
|
+
s.and_(f"{pk[0]} = ?")
|
|
1893
|
+
notes.append("no Where: GORM uses the primary key of the value given to Model()")
|
|
1894
|
+
s.and_(soft)
|
|
1895
|
+
return [self._stmt(s, render(s), "update", model, table, notes)]
|
|
1896
|
+
if name == "Delete":
|
|
1897
|
+
inline(args[1:])
|
|
1898
|
+
if not s.where and dest is not None and not _empty_value(gf, dest, call):
|
|
1899
|
+
s.and_(f"{tname}.{pk[0]} = ?")
|
|
1900
|
+
notes.append("no Where: GORM uses the primary key of the value given to Delete()")
|
|
1901
|
+
if deleted and "unscoped" not in s.flags:
|
|
1902
|
+
s.kind, s.sets = "update", [f"{deleted} = ?"]
|
|
1903
|
+
s.and_(soft)
|
|
1904
|
+
notes.append("soft delete: the model has a DeletedAt column")
|
|
1905
|
+
else:
|
|
1906
|
+
s.kind = "delete"
|
|
1907
|
+
return [self._stmt(s, render(s), "delete", model, table, notes)]
|
|
1908
|
+
raise Unresolved(f".{name}() is not translated")
|
|
1909
|
+
|
|
1910
|
+
def _gorm_preloads(self, q: Q, model: Model | None, soft_ok: bool) -> list[Stmt]:
|
|
1911
|
+
out: list[Stmt] = []
|
|
1912
|
+
if not q.preloads:
|
|
1913
|
+
return out
|
|
1914
|
+
names: list[str] = []
|
|
1915
|
+
for p in q.preloads:
|
|
1916
|
+
if p == "*":
|
|
1917
|
+
names.extend(model.relations if model is not None else [])
|
|
1918
|
+
else:
|
|
1919
|
+
names.append(p)
|
|
1920
|
+
for full in names:
|
|
1921
|
+
owner = model
|
|
1922
|
+
path = full.split(".")
|
|
1923
|
+
for i, part in enumerate(path):
|
|
1924
|
+
rel = owner.relations.get(part) if owner is not None else None
|
|
1925
|
+
target = self.types.model(rel.target, "gorm") if rel is not None else None
|
|
1926
|
+
if rel is None or target is None:
|
|
1927
|
+
self.stats.reasons["gorm"]["Preload of a relation this scan cannot read"] += 1
|
|
1928
|
+
break
|
|
1929
|
+
if i == len(path) - 1:
|
|
1930
|
+
out.extend(self._preload_stmts(owner, rel, target, full, soft_ok))
|
|
1931
|
+
owner = target
|
|
1932
|
+
return out
|
|
1933
|
+
|
|
1934
|
+
@staticmethod
|
|
1935
|
+
def _preload_stmts(owner: Model, rel, target: Model, full: str, soft_ok: bool) -> list[Stmt]:
|
|
1936
|
+
cols = ", ".join(T.ident(c.name) for c in target.cols) or "*"
|
|
1937
|
+
note = f"Preload({full}): one IN query per relation, after the main statement"
|
|
1938
|
+
soft = target.role("deleted")
|
|
1939
|
+
tail = f" AND {target.table}.{soft} IS NULL" if soft and soft_ok else ""
|
|
1940
|
+
target.used = True
|
|
1941
|
+
if rel.kind == "many2many":
|
|
1942
|
+
jt = rel.join_table
|
|
1943
|
+
okey = T.gonic_name(owner.name) + "_" + (owner.pk[0] if owner.pk else "id")
|
|
1944
|
+
tkey = T.gonic_name(target.name) + "_" + (target.pk[0] if target.pk else "id")
|
|
1945
|
+
return [Stmt(f"SELECT * FROM {jt} WHERE {jt}.{okey} IN (?)", "select", jt, "medium", [note + " (the join table)"]),
|
|
1946
|
+
Stmt(f"SELECT {cols} FROM {target.table} WHERE {target.table}.{target.pk[0] if target.pk else 'id'} IN (?){tail}",
|
|
1947
|
+
"select", target.name, "medium", [note, f"join table key assumed {tkey}"])]
|
|
1948
|
+
if rel.kind == "belongs_to":
|
|
1949
|
+
ref = rel.references and target.col(rel.references)
|
|
1950
|
+
key = ref.name if ref else (target.pk[0] if target.pk else "id")
|
|
1951
|
+
return [Stmt(f"SELECT {cols} FROM {target.table} WHERE {target.table}.{key} IN (?){tail}", "select", target.name, "high", [note])]
|
|
1952
|
+
fk_field = rel.foreign_key or owner.name + "ID"
|
|
1953
|
+
col = target.col(fk_field)
|
|
1954
|
+
key = col.name if col is not None else T.gonic_name(fk_field)
|
|
1955
|
+
conf = "high" if col is not None else "medium"
|
|
1956
|
+
notes = [note] if col is not None else [note, f"foreign key assumed {key}"]
|
|
1957
|
+
return [Stmt(f"SELECT {cols} FROM {target.table} WHERE {target.table}.{key} IN (?){tail}", "select", target.name, conf, notes)]
|
|
1958
|
+
|
|
1959
|
+
def _gorm_assoc(self, q: Q, name: str, args: list[Node], call: Node, gf: GoFile) -> list[Stmt]:
|
|
1960
|
+
if name not in ("Find", "Count") or q.model is None:
|
|
1961
|
+
raise Unresolved("association call: only Find and Count on a known model are translated")
|
|
1962
|
+
rel = q.model.relations.get(q.assoc)
|
|
1963
|
+
target = self.types.model(rel.target, "gorm") if rel is not None else None
|
|
1964
|
+
if rel is None or target is None:
|
|
1965
|
+
raise Unresolved("association of a relation this scan cannot read")
|
|
1966
|
+
stmts = self._preload_stmts(q.model, rel, target, q.assoc, True)
|
|
1967
|
+
for s in stmts:
|
|
1968
|
+
s.sql = s.sql.replace(" IN (?)", " = ?")
|
|
1969
|
+
s.confidence = "low"
|
|
1970
|
+
s.notes = [f"Association({q.assoc}).{name}: rows of the relation for one owner; fires once per call"]
|
|
1971
|
+
if name == "Count":
|
|
1972
|
+
s.sql = re.sub(r"^SELECT .*? FROM", "SELECT count(*) FROM", s.sql)
|
|
1973
|
+
return stmts[-1:]
|
|
1974
|
+
|
|
1975
|
+
|
|
1976
|
+
# ==================================================================== rendering
|
|
1977
|
+
|
|
1978
|
+
def _sub(text: str) -> str:
|
|
1979
|
+
text = text.strip()
|
|
1980
|
+
return text if text.startswith("(") or _is_marker(text) or not re.match(r"(?i)\s*(select|with)\b", text) else f"({text})"
|
|
1981
|
+
|
|
1982
|
+
|
|
1983
|
+
def _unsub(text: str) -> str:
|
|
1984
|
+
text = text.strip()
|
|
1985
|
+
if text.startswith("(") and text.endswith(")") and re.match(r"(?i)\(\s*(select|with)\b", text):
|
|
1986
|
+
return text[1:-1]
|
|
1987
|
+
return text
|
|
1988
|
+
|
|
1989
|
+
|
|
1990
|
+
def _unsub_alias(text: str) -> str:
|
|
1991
|
+
return text
|
|
1992
|
+
|
|
1993
|
+
|
|
1994
|
+
def _sub_from(text: str) -> str:
|
|
1995
|
+
return text
|
|
1996
|
+
|
|
1997
|
+
|
|
1998
|
+
def _split_cols(parts: list[str]) -> list[str]:
|
|
1999
|
+
return [p.strip() for p in parts if p.strip()]
|
|
2000
|
+
|
|
2001
|
+
|
|
2002
|
+
def _table_word(table: str) -> str:
|
|
2003
|
+
"""`Users u` -> Users; `db.t AS x` -> db.t."""
|
|
2004
|
+
if (table or "").lstrip().startswith("("):
|
|
2005
|
+
return "(subquery)"
|
|
2006
|
+
m = re.match(r"\s*((?:[\w.\"`-]|«[^»]*»)+)", table or "")
|
|
2007
|
+
return m.group(1).strip("\"`") if m else table
|
|
2008
|
+
|
|
2009
|
+
|
|
2010
|
+
def _what(node: Node | None) -> str:
|
|
2011
|
+
"""Detail for the list of calls that were not translated; the counted reason is the text before it."""
|
|
2012
|
+
return f" | {trim(_txt(node), 60)}" if node is not None else ""
|
|
2013
|
+
|
|
2014
|
+
|
|
2015
|
+
def _empty_value(gf: GoFile, node: Node, at: Node) -> bool:
|
|
2016
|
+
"""`&User{}`, `new(User)`, `User{}`, a nil pointer of the type: a value that only names the model."""
|
|
2017
|
+
n = _strip_parens(node)
|
|
2018
|
+
if n is not None and n.type == "unary_expression":
|
|
2019
|
+
n = _strip_parens(n.child_by_field_name("operand"))
|
|
2020
|
+
if n is None:
|
|
2021
|
+
return True
|
|
2022
|
+
if n.type == "composite_literal":
|
|
2023
|
+
body = n.child_by_field_name("body")
|
|
2024
|
+
return body is None or not body.named_children
|
|
2025
|
+
if n.type == "call_expression":
|
|
2026
|
+
return callee_name(n.child_by_field_name("function"))[0] == "new"
|
|
2027
|
+
if n.type == "identifier":
|
|
2028
|
+
local = gf._local(_txt(n), at)
|
|
2029
|
+
if local is not None and local[1].kind == "decl":
|
|
2030
|
+
spec = local[1].node
|
|
2031
|
+
if local[1].value is None:
|
|
2032
|
+
return True
|
|
2033
|
+
return _empty_value(gf, local[1].value, spec) and not re.search(
|
|
2034
|
+
rf"\b{re.escape(_txt(n))}\.\w+\s*=[^=]", gf.src[spec.end_byte: at.start_byte].decode("utf-8", "replace"))
|
|
2035
|
+
return False
|
|
2036
|
+
|
|
2037
|
+
|
|
2038
|
+
def _added(before: str, after: str) -> str:
|
|
2039
|
+
"""What a conditional `.And(...)` added to a condition."""
|
|
2040
|
+
if before and after.startswith(before):
|
|
2041
|
+
return re.sub(r"^\s*AND\s*", "", after[len(before):]).strip() or after
|
|
2042
|
+
if before and after.startswith(f"({before})"):
|
|
2043
|
+
return re.sub(r"^\s*(?:AND|OR)\s*", "", after[len(before) + 2:]).strip() or after
|
|
2044
|
+
return after
|
|
2045
|
+
|
|
2046
|
+
|
|
2047
|
+
def _why_not(q: Q) -> str:
|
|
2048
|
+
if q.opaque:
|
|
2049
|
+
return q.opaque
|
|
2050
|
+
if not q.table and q.model is None:
|
|
2051
|
+
return "no table named in the chain"
|
|
2052
|
+
return "the statement kind is not known"
|
|
2053
|
+
|
|
2054
|
+
|
|
2055
|
+
def render(q) -> str: # noqa: C901
|
|
2056
|
+
"""The statement text, or "" when it has no table to name."""
|
|
2057
|
+
if not isinstance(q, Q) or q.opaque:
|
|
2058
|
+
return ""
|
|
2059
|
+
if q.union:
|
|
2060
|
+
return " ".join(q.prefix + [q.union] + (["ORDER BY " + ", ".join(q.order)] if q.order else []) +
|
|
2061
|
+
([f"LIMIT {q.limit}"] if q.limit else []) + ([f"OFFSET {q.offset}"] if q.offset else []))
|
|
2062
|
+
table = q.table or (T.ident(q.model.table) if q.model is not None else "")
|
|
2063
|
+
if not table:
|
|
2064
|
+
return ""
|
|
2065
|
+
if q.alias and q.lib in ("xorm", "xbuilder") and not re.search(r"\s", table.strip()):
|
|
2066
|
+
table = f"{table} AS {q.alias}"
|
|
2067
|
+
kind = q.kind or "select"
|
|
2068
|
+
parts: list[str] = list(q.prefix)
|
|
2069
|
+
where = f"WHERE {q.where}" if q.where else ""
|
|
2070
|
+
if kind == "select":
|
|
2071
|
+
cols = ", ".join(c for c in q.cols if c) or "*"
|
|
2072
|
+
head = "SELECT " + (" ".join(q.options) + " " if q.options else "") + ("DISTINCT " if q.distinct else "") + cols
|
|
2073
|
+
parts += [head, f"FROM {table}", *q.joins]
|
|
2074
|
+
if where:
|
|
2075
|
+
parts.append(where)
|
|
2076
|
+
if any(q.group):
|
|
2077
|
+
parts.append("GROUP BY " + ", ".join(x for x in q.group if x))
|
|
2078
|
+
if any(q.having):
|
|
2079
|
+
parts.append("HAVING " + " AND ".join(x for x in q.having if x))
|
|
2080
|
+
if any(q.order):
|
|
2081
|
+
parts.append("ORDER BY " + ", ".join(x for x in q.order if x))
|
|
2082
|
+
if q.limit:
|
|
2083
|
+
parts.append(f"LIMIT {q.limit}")
|
|
2084
|
+
if q.offset:
|
|
2085
|
+
parts.append(f"OFFSET {q.offset}")
|
|
2086
|
+
elif kind == "insert":
|
|
2087
|
+
cols = f" ({', '.join(q.ins_cols)})" if q.ins_cols else ""
|
|
2088
|
+
head = ("REPLACE" if "replace" in q.flags else "INSERT") + (" " + " ".join(q.options) if q.options else "") + f" INTO {table}{cols}"
|
|
2089
|
+
if q.ins_select:
|
|
2090
|
+
parts += [head, q.ins_select]
|
|
2091
|
+
else:
|
|
2092
|
+
n = len(q.ins_cols) if q.ins_cols and not any("«" in c for c in q.ins_cols) else 0
|
|
2093
|
+
values = ", ".join("?" for _ in range(n)) if n else (", ".join(q.sets) if q.sets else marker("values"))
|
|
2094
|
+
parts += [head, f"VALUES ({values})"]
|
|
2095
|
+
elif kind == "update":
|
|
2096
|
+
if not q.sets:
|
|
2097
|
+
return ""
|
|
2098
|
+
parts += [f"UPDATE {table}", "SET " + ", ".join(q.sets), *q.joins]
|
|
2099
|
+
if where:
|
|
2100
|
+
parts.append(where)
|
|
2101
|
+
if q.order:
|
|
2102
|
+
parts.append("ORDER BY " + ", ".join(q.order))
|
|
2103
|
+
if q.limit:
|
|
2104
|
+
parts.append(f"LIMIT {q.limit}")
|
|
2105
|
+
elif kind == "delete":
|
|
2106
|
+
parts += [f"DELETE FROM {table}", *q.joins]
|
|
2107
|
+
if where:
|
|
2108
|
+
parts.append(where)
|
|
2109
|
+
if q.order:
|
|
2110
|
+
parts.append("ORDER BY " + ", ".join(q.order))
|
|
2111
|
+
if q.limit:
|
|
2112
|
+
parts.append(f"LIMIT {q.limit}")
|
|
2113
|
+
parts += q.suffix
|
|
2114
|
+
# a run-time part that is not a predicate (a conditional ORDER BY, a scope function) rides in a comment: the
|
|
2115
|
+
# statement still parses, and the part is still in the text
|
|
2116
|
+
parts += [f"/* {t} */" for t in q.tail if t]
|
|
2117
|
+
return " ".join(p for p in parts if p)
|
|
2118
|
+
|
|
2119
|
+
|
|
2120
|
+
def chain_of(call: Node) -> tuple[Node | None, list[tuple[str, list[Node], Node]]]:
|
|
2121
|
+
"""(root expression, [(method, arguments, call node)] from the root outwards) of a method chain."""
|
|
2122
|
+
ops: list[tuple[str, list[Node], Node]] = []
|
|
2123
|
+
n: Node | None = call
|
|
2124
|
+
while n is not None and n.type == "call_expression":
|
|
2125
|
+
fn = n.child_by_field_name("function")
|
|
2126
|
+
if fn is None or fn.type != "selector_expression":
|
|
2127
|
+
break
|
|
2128
|
+
fld = fn.child_by_field_name("field")
|
|
2129
|
+
if fld is None:
|
|
2130
|
+
break
|
|
2131
|
+
ops.append((_txt(fld), call_args(n), n))
|
|
2132
|
+
n = _strip_parens(fn.child_by_field_name("operand"))
|
|
2133
|
+
ops.reverse()
|
|
2134
|
+
return n, ops
|