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,1401 @@
|
|
|
1
|
+
"""Sequelize model calls as SQL sites.
|
|
2
|
+
|
|
3
|
+
Models are read from their definitions: sequelize-typescript classes (`@Table({ tableName })`, `@Column`,
|
|
4
|
+
`@PrimaryKey`, `@DeletedAt`, `@BelongsTo` / `@HasMany` / `@HasOne` / `@BelongsToMany`, base classes followed),
|
|
5
|
+
`X.init({...}, { tableName })` and `sequelize.define("name", {...}, {...})`. A call is translated when its receiver
|
|
6
|
+
is a model: `User.findAll({...})`, `this.findOne(...)` in a static method of a model, `X.unscoped().findByPk(id)`,
|
|
7
|
+
`X.scope("s").count(...)`, and instance methods (`doc.save()`, `doc.destroy()`, `doc.reload()`, `doc.update({...})`)
|
|
8
|
+
on a variable whose model is visible (a type annotation, or a value from `X.findByPk(...)`, `X.create(...)`,
|
|
9
|
+
`X.build(...)`, `new X(...)`).
|
|
10
|
+
|
|
11
|
+
Options read: `where` (plain values, arrays as IN, `null` as IS NULL, `Op.*` and the legacy `$op` keys, `Op.or` /
|
|
12
|
+
`Op.and` / `Op.not`, `$assoc.column$` keys), `attributes` (lists, `[expr, alias]`, `include` / `exclude`), `order`,
|
|
13
|
+
`group`, `limit`, `offset`, `include` (one LEFT / INNER JOIN per association, `separate: true` as its own statement),
|
|
14
|
+
`paranoid`. A model with a `@DeletedAt` column (or `paranoid: true`) adds `deletedAt IS NULL` to reads and turns
|
|
15
|
+
`destroy` into an UPDATE unless `force: true`. Whatever is only known at run time is a «run-time part»; a default or
|
|
16
|
+
named scope is not applied and says so in the notes.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
|
|
24
|
+
from tree_sitter import Node, Parser
|
|
25
|
+
|
|
26
|
+
from . import orm_ts as o
|
|
27
|
+
from .orm_ts import as_object, mark, mark_node, txt, unwrap
|
|
28
|
+
|
|
29
|
+
NAME = "sequelize"
|
|
30
|
+
MECHANISM = "orm_api"
|
|
31
|
+
STATIC = {"findAll", "findOne", "findByPk", "findAndCountAll", "findOrCreate", "findOrBuild", "findCreateFind", "count",
|
|
32
|
+
"sum", "max", "min", "create", "bulkCreate", "update", "destroy", "upsert", "increment", "decrement", "restore",
|
|
33
|
+
"aggregate", "truncate"}
|
|
34
|
+
INSTANCE = {"save", "destroy", "reload", "update", "increment", "decrement", "restore"}
|
|
35
|
+
# names that only Sequelize uses: a call of one of these on an unknown receiver is counted as a Sequelize call not translated
|
|
36
|
+
OWN = {"findAll", "findByPk", "findAndCountAll", "findOrCreate", "findOrBuild", "findCreateFind", "bulkCreate"}
|
|
37
|
+
SCOPE_CALLS = {"scope", "unscoped", "schema", "withScope"}
|
|
38
|
+
PRE = re.compile(rb"\.\s*(?:" + "|".join(sorted(STATIC | INSTANCE)).encode() + rb")\s*\(")
|
|
39
|
+
MODEL_HINT = re.compile(rb"@(?:Table|Column|DeletedAt|PrimaryKey|CreatedAt|BelongsTo|HasMany|HasOne|BelongsToMany|DefaultScope)\b|\.init\s*\(|\.define\s*\(")
|
|
40
|
+
OPS = {"eq": "=", "ne": "<>", "gt": ">", "gte": ">=", "lt": "<", "lte": "<=", "like": "LIKE", "notLike": "NOT LIKE",
|
|
41
|
+
"iLike": "ILIKE", "notILike": "NOT ILIKE", "regexp": "~", "notRegexp": "!~", "iRegexp": "~*", "notIRegexp": "!~*",
|
|
42
|
+
"overlap": "&&", "contains": "@>", "contained": "<@", "match": "@@", "adjacent": "-|-", "strictLeft": "<<",
|
|
43
|
+
"strictRight": ">>"}
|
|
44
|
+
LIKE_WRAP = {"startsWith": ("", "%"), "endsWith": ("%", ""), "substring": ("%", "%")}
|
|
45
|
+
COLUMN_DECORATORS = {"Column", "PrimaryKey", "ForeignKey", "CreatedAt", "UpdatedAt", "DeletedAt", "AutoIncrement",
|
|
46
|
+
"AllowNull", "Default", "Unique", "Index"}
|
|
47
|
+
ASSOC_DECORATORS = {"BelongsTo": "belongsTo", "HasMany": "hasMany", "HasOne": "hasOne", "BelongsToMany": "belongsToMany"}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _snake(name: str) -> str:
|
|
51
|
+
return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _lower_first(name: str) -> str:
|
|
55
|
+
return name[:1].lower() + name[1:]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def pluralize(word: str) -> str:
|
|
59
|
+
"""Sequelize's default table name for a model name (inflection's plural, for the regular cases)."""
|
|
60
|
+
low = word.lower()
|
|
61
|
+
if re.search(r"[^aeiou]y$", low):
|
|
62
|
+
return word[:-1] + "ies"
|
|
63
|
+
if re.search(r"(s|x|z|ch|sh)$", low):
|
|
64
|
+
return word + "es"
|
|
65
|
+
return word + "s"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Model:
|
|
69
|
+
def __init__(self, cls: str, rel: str, line: int):
|
|
70
|
+
self.cls, self.rel, self.line = cls, rel, line
|
|
71
|
+
self.table = ""
|
|
72
|
+
self.table_basis = "" # "" until known: "sql" when written, "plural" when derived
|
|
73
|
+
self.model_name = ""
|
|
74
|
+
self.is_model = False
|
|
75
|
+
self.base = ""
|
|
76
|
+
self.columns: dict[str, str] = {} # attribute -> column
|
|
77
|
+
self.types: dict[str, str] = {}
|
|
78
|
+
self.pk: list[str] = []
|
|
79
|
+
self.deleted_at = "" # attribute of the @DeletedAt / paranoid column
|
|
80
|
+
self.paranoid: bool | None = None
|
|
81
|
+
self.timestamps: bool | None = None
|
|
82
|
+
self.underscored: bool | None = None
|
|
83
|
+
self.created_at = "createdAt"
|
|
84
|
+
self.updated_at = "updatedAt"
|
|
85
|
+
self.assocs: dict[str, dict] = {} # alias -> {kind, target, fk, through, other}
|
|
86
|
+
self.default_scope = False
|
|
87
|
+
|
|
88
|
+
def column(self, attr: str) -> str:
|
|
89
|
+
if attr in self.columns:
|
|
90
|
+
return self.columns[attr]
|
|
91
|
+
return _snake(attr) if self.underscored else attr
|
|
92
|
+
|
|
93
|
+
def pk_column(self) -> str:
|
|
94
|
+
return self.column(self.pk[0]) if self.pk else "id"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# ---- model definitions ----------------------------------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
def _dec_parts(dec: Node) -> tuple[str, list[Node], dict[str, Node]]:
|
|
100
|
+
inner = dec.named_children[0] if dec.named_children else None
|
|
101
|
+
if inner is None:
|
|
102
|
+
return "", [], {}
|
|
103
|
+
if inner.type != "call_expression":
|
|
104
|
+
return txt(inner), [], {}
|
|
105
|
+
a = inner.child_by_field_name("arguments")
|
|
106
|
+
args = [unwrap(x) for x in (a.named_children if a is not None else []) if x.type != "comment"]
|
|
107
|
+
kw: dict[str, Node] = {}
|
|
108
|
+
for x in args:
|
|
109
|
+
if x is not None and x.type == "object":
|
|
110
|
+
for c in x.named_children:
|
|
111
|
+
if c.type == "pair":
|
|
112
|
+
k = c.child_by_field_name("key")
|
|
113
|
+
key = o.string_value(k)
|
|
114
|
+
kw[key if key is not None else txt(k)] = c.child_by_field_name("value")
|
|
115
|
+
return txt(inner.child_by_field_name("function")), [x for x in args if x is not None], kw
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _member_decorators(node: Node) -> list[Node]:
|
|
119
|
+
out = [c for c in node.children if c.type == "decorator"]
|
|
120
|
+
prev = node.prev_named_sibling
|
|
121
|
+
while prev is not None and prev.type in ("decorator", "comment"):
|
|
122
|
+
if prev.type == "decorator":
|
|
123
|
+
out.append(prev)
|
|
124
|
+
prev = prev.prev_named_sibling
|
|
125
|
+
return out
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _target(node: Node | None) -> str:
|
|
129
|
+
"""`() => User` / `User` / `"User"` -> User."""
|
|
130
|
+
node = unwrap(node)
|
|
131
|
+
if node is None:
|
|
132
|
+
return ""
|
|
133
|
+
s = o.string_value(node)
|
|
134
|
+
if s is not None:
|
|
135
|
+
return s
|
|
136
|
+
body = o.callback_body(node)
|
|
137
|
+
return txt(body if body is not None else node).split(".")[-1].strip()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _bool(node: Node | None) -> bool | None:
|
|
141
|
+
t = txt(unwrap(node)) if node is not None else ""
|
|
142
|
+
return True if t == "true" else False if t == "false" else None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _options(m: Model, kw: dict[str, Node]) -> None:
|
|
146
|
+
t = o.string_value(kw.get("tableName"))
|
|
147
|
+
if t:
|
|
148
|
+
m.table, m.table_basis = t, "sql"
|
|
149
|
+
mn = o.string_value(kw.get("modelName"))
|
|
150
|
+
if mn:
|
|
151
|
+
m.model_name = mn
|
|
152
|
+
for key, attr in (("paranoid", "paranoid"), ("timestamps", "timestamps"), ("underscored", "underscored")):
|
|
153
|
+
b = _bool(kw.get(key))
|
|
154
|
+
if b is not None:
|
|
155
|
+
setattr(m, attr, b)
|
|
156
|
+
if _bool(kw.get("freezeTableName")) and not m.table:
|
|
157
|
+
m.table, m.table_basis = m.model_name or m.cls, "sql"
|
|
158
|
+
for key, attr in (("createdAt", "created_at"), ("updatedAt", "updated_at"), ("deletedAt", "deleted_at")):
|
|
159
|
+
s = o.string_value(kw.get(key))
|
|
160
|
+
if s:
|
|
161
|
+
setattr(m, attr, s)
|
|
162
|
+
if kw.get("defaultScope") is not None:
|
|
163
|
+
m.default_scope = True
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _attributes(m: Model, obj: Node | None) -> None:
|
|
167
|
+
"""`{ name: DataTypes.STRING, email: { type: ..., field: "email_address", primaryKey: true } }`."""
|
|
168
|
+
obj = unwrap(obj)
|
|
169
|
+
if obj is None or obj.type != "object":
|
|
170
|
+
return
|
|
171
|
+
for c in obj.named_children:
|
|
172
|
+
if c.type != "pair":
|
|
173
|
+
continue
|
|
174
|
+
k = c.child_by_field_name("key")
|
|
175
|
+
key = o.string_value(k)
|
|
176
|
+
attr = key if key is not None else txt(k)
|
|
177
|
+
v = unwrap(c.child_by_field_name("value"))
|
|
178
|
+
col = None
|
|
179
|
+
if v is not None and v.type == "object":
|
|
180
|
+
for p in v.named_children:
|
|
181
|
+
if p.type != "pair":
|
|
182
|
+
continue
|
|
183
|
+
pk_ = txt(p.child_by_field_name("key")).strip("'\"")
|
|
184
|
+
pv = p.child_by_field_name("value")
|
|
185
|
+
if pk_ == "field":
|
|
186
|
+
col = o.string_value(pv)
|
|
187
|
+
elif pk_ == "primaryKey" and txt(pv) == "true":
|
|
188
|
+
m.pk.append(attr)
|
|
189
|
+
elif pk_ == "type":
|
|
190
|
+
if "VIRTUAL" in txt(pv):
|
|
191
|
+
col = ""
|
|
192
|
+
m.types[attr] = txt(pv)[:40]
|
|
193
|
+
elif v is not None and "VIRTUAL" in txt(v):
|
|
194
|
+
col = ""
|
|
195
|
+
if col == "":
|
|
196
|
+
continue
|
|
197
|
+
if col:
|
|
198
|
+
m.columns[attr] = col
|
|
199
|
+
else:
|
|
200
|
+
m.columns.setdefault(attr, "") # resolved after the options are known (underscored)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def read_models(rel: str, src: bytes) -> list[Model]:
|
|
204
|
+
from .typescript import language_for
|
|
205
|
+
tree = Parser(language_for(rel)).parse(src)
|
|
206
|
+
out: list[Model] = []
|
|
207
|
+
by_var: dict[str, Model] = {}
|
|
208
|
+
stack = [tree.root_node]
|
|
209
|
+
while stack:
|
|
210
|
+
node = stack.pop()
|
|
211
|
+
t = node.type
|
|
212
|
+
if t in ("class_declaration", "abstract_class_declaration", "class"):
|
|
213
|
+
name = txt(node.child_by_field_name("name"))
|
|
214
|
+
if not name and node.parent is not None and node.parent.type == "variable_declarator":
|
|
215
|
+
name = txt(node.parent.child_by_field_name("name"))
|
|
216
|
+
m = Model(name, rel, node.start_point[0] + 1)
|
|
217
|
+
decs = [c for c in node.children if c.type == "decorator"]
|
|
218
|
+
if node.parent is not None and node.parent.type == "export_statement":
|
|
219
|
+
decs += [c for c in node.parent.children if c.type == "decorator"]
|
|
220
|
+
for d in decs:
|
|
221
|
+
dname, args, kw = _dec_parts(d)
|
|
222
|
+
if dname == "Table":
|
|
223
|
+
m.is_model = True
|
|
224
|
+
_options(m, kw)
|
|
225
|
+
elif dname == "DefaultScope":
|
|
226
|
+
m.default_scope = True
|
|
227
|
+
for c in node.children:
|
|
228
|
+
if c.type == "class_heritage":
|
|
229
|
+
mm = re.search(r"extends\s+([A-Za-z_][\w$]*)", txt(c))
|
|
230
|
+
m.base = mm.group(1) if mm else ""
|
|
231
|
+
body = node.child_by_field_name("body")
|
|
232
|
+
for member in (body.named_children if body is not None else ()):
|
|
233
|
+
if member.type != "public_field_definition":
|
|
234
|
+
if member.type in ("class_declaration",):
|
|
235
|
+
stack.append(member)
|
|
236
|
+
continue
|
|
237
|
+
prop = txt(member.child_by_field_name("name")).lstrip("!?").rstrip("!?")
|
|
238
|
+
is_col, field_name = False, None
|
|
239
|
+
for d in _member_decorators(member):
|
|
240
|
+
dname, dargs, dkw = _dec_parts(d)
|
|
241
|
+
if dname in COLUMN_DECORATORS:
|
|
242
|
+
is_col = True
|
|
243
|
+
if dname == "Column":
|
|
244
|
+
field_name = o.string_value(dkw.get("field")) or field_name
|
|
245
|
+
if "VIRTUAL" in txt(d):
|
|
246
|
+
is_col = False
|
|
247
|
+
break
|
|
248
|
+
if _bool(dkw.get("primaryKey")):
|
|
249
|
+
m.pk.append(prop)
|
|
250
|
+
if dname == "PrimaryKey":
|
|
251
|
+
m.pk.append(prop)
|
|
252
|
+
if dname == "DeletedAt":
|
|
253
|
+
m.deleted_at, m.paranoid = prop, True
|
|
254
|
+
if dname == "CreatedAt":
|
|
255
|
+
m.created_at = prop
|
|
256
|
+
if dname == "UpdatedAt":
|
|
257
|
+
m.updated_at = prop
|
|
258
|
+
elif dname in ASSOC_DECORATORS:
|
|
259
|
+
a = {"kind": ASSOC_DECORATORS[dname], "target": _target(dargs[0] if dargs else None),
|
|
260
|
+
"fk": "", "through": "", "other": "", "as": prop}
|
|
261
|
+
rest = dargs[1:]
|
|
262
|
+
if dname == "BelongsToMany" and rest:
|
|
263
|
+
a["through"] = _target(rest[0])
|
|
264
|
+
rest = rest[1:]
|
|
265
|
+
if len(rest) >= 2:
|
|
266
|
+
a["other"] = o.string_value(rest[1]) or ""
|
|
267
|
+
if rest:
|
|
268
|
+
s = o.string_value(rest[0])
|
|
269
|
+
if s:
|
|
270
|
+
a["fk"] = s
|
|
271
|
+
elif unwrap(rest[0]) is not None and unwrap(rest[0]).type == "object":
|
|
272
|
+
_n, _a, okw = _dec_parts_obj(rest[0])
|
|
273
|
+
fk = okw.get("foreignKey")
|
|
274
|
+
a["fk"] = o.string_value(fk) or (txt(_obj_get(fk, "name")).strip("'\"") if unwrap(fk) is not None and unwrap(fk).type == "object" else "")
|
|
275
|
+
a["other"] = o.string_value(okw.get("otherKey")) or a["other"]
|
|
276
|
+
a["as"] = o.string_value(okw.get("as")) or prop
|
|
277
|
+
m.assocs[prop] = a
|
|
278
|
+
if is_col:
|
|
279
|
+
if field_name:
|
|
280
|
+
m.columns[prop] = field_name
|
|
281
|
+
else:
|
|
282
|
+
m.columns.setdefault(prop, "")
|
|
283
|
+
if m.is_model or m.columns or m.assocs or m.base:
|
|
284
|
+
out.append(m)
|
|
285
|
+
by_var[m.cls] = m
|
|
286
|
+
continue
|
|
287
|
+
if t == "call_expression":
|
|
288
|
+
fn = unwrap(node.child_by_field_name("function"))
|
|
289
|
+
a = node.child_by_field_name("arguments")
|
|
290
|
+
args = [x for x in (a.named_children if a is not None else []) if x.type != "comment"]
|
|
291
|
+
if fn is not None and fn.type == "member_expression":
|
|
292
|
+
prop = txt(fn.child_by_field_name("property"))
|
|
293
|
+
obj = txt(fn.child_by_field_name("object"))
|
|
294
|
+
if prop == "init" and len(args) >= 2 and unwrap(args[0]) is not None and unwrap(args[0]).type == "object":
|
|
295
|
+
m = by_var.get(obj) or Model(obj, rel, node.start_point[0] + 1)
|
|
296
|
+
m.is_model = True
|
|
297
|
+
_attributes(m, args[0])
|
|
298
|
+
_n, _a, kw = _dec_parts_obj(args[1])
|
|
299
|
+
_options(m, kw)
|
|
300
|
+
if obj not in by_var:
|
|
301
|
+
out.append(m)
|
|
302
|
+
by_var[obj] = m
|
|
303
|
+
elif prop == "define" and len(args) >= 2 and o.string_value(args[0]):
|
|
304
|
+
holder = node.parent
|
|
305
|
+
while holder is not None and holder.type in o.UNWRAP:
|
|
306
|
+
holder = holder.parent
|
|
307
|
+
var = txt(holder.child_by_field_name("name")) if holder is not None and holder.type == "variable_declarator" else ""
|
|
308
|
+
mname = o.string_value(args[0])
|
|
309
|
+
m = Model(var or mname, rel, node.start_point[0] + 1)
|
|
310
|
+
m.is_model, m.model_name = True, mname
|
|
311
|
+
_attributes(m, args[1])
|
|
312
|
+
if len(args) > 2:
|
|
313
|
+
_n, _a, kw = _dec_parts_obj(args[2])
|
|
314
|
+
_options(m, kw)
|
|
315
|
+
out.append(m)
|
|
316
|
+
if var:
|
|
317
|
+
by_var[var] = m
|
|
318
|
+
stack.extend(node.children)
|
|
319
|
+
return out
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _dec_parts_obj(node: Node | None) -> tuple[str, list, dict[str, Node]]:
|
|
323
|
+
kw: dict[str, Node] = {}
|
|
324
|
+
node = unwrap(node)
|
|
325
|
+
if node is not None and node.type == "object":
|
|
326
|
+
for c in node.named_children:
|
|
327
|
+
if c.type == "pair":
|
|
328
|
+
k = c.child_by_field_name("key")
|
|
329
|
+
key = o.string_value(k)
|
|
330
|
+
kw[key if key is not None else txt(k)] = c.child_by_field_name("value")
|
|
331
|
+
return "", [], kw
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _obj_get(node: Node | None, key: str) -> Node | None:
|
|
335
|
+
return _dec_parts_obj(node)[2].get(key)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
# ---- the library ----------------------------------------------------------------------------------------------
|
|
339
|
+
|
|
340
|
+
class Library:
|
|
341
|
+
name = NAME
|
|
342
|
+
|
|
343
|
+
def __init__(self, ctx, root, files, stats):
|
|
344
|
+
self.ctx, self.stats = ctx, stats
|
|
345
|
+
self.active = True
|
|
346
|
+
self.by_class: dict[str, list[Model]] = {}
|
|
347
|
+
self.underscored = False # `new Sequelize({ define: { underscored: true } })`
|
|
348
|
+
|
|
349
|
+
def wants(self, rel: str, src: bytes, deps) -> bool:
|
|
350
|
+
uses = "sequelize" in deps or "sequelize-typescript" in deps or b"sequelize" in src
|
|
351
|
+
if not uses:
|
|
352
|
+
return False
|
|
353
|
+
if MODEL_HINT.search(src):
|
|
354
|
+
try:
|
|
355
|
+
for m in read_models(rel, src):
|
|
356
|
+
self.by_class.setdefault(m.cls, []).append(m)
|
|
357
|
+
except Exception:
|
|
358
|
+
if os.environ.get("CODECOP_ORM_DEBUG"):
|
|
359
|
+
raise
|
|
360
|
+
if b"underscored" in src and re.search(rb"define\s*:\s*\{[^}]*underscored\s*:\s*true", src):
|
|
361
|
+
self.underscored = True
|
|
362
|
+
return bool(PRE.search(src))
|
|
363
|
+
|
|
364
|
+
def prepare(self, wanted) -> None:
|
|
365
|
+
def fill(m: Model, seen: set) -> None:
|
|
366
|
+
if not m.base or m.cls in seen:
|
|
367
|
+
return
|
|
368
|
+
seen.add(m.cls)
|
|
369
|
+
for base in self.by_class.get(m.base, [])[:1]:
|
|
370
|
+
fill(base, seen)
|
|
371
|
+
m.columns = {**base.columns, **m.columns}
|
|
372
|
+
m.types = {**base.types, **m.types}
|
|
373
|
+
m.assocs = {**base.assocs, **m.assocs}
|
|
374
|
+
m.pk = m.pk or list(base.pk)
|
|
375
|
+
m.deleted_at = m.deleted_at or base.deleted_at
|
|
376
|
+
m.default_scope = m.default_scope or base.default_scope
|
|
377
|
+
for attr in ("paranoid", "timestamps", "underscored"):
|
|
378
|
+
if getattr(m, attr) is None:
|
|
379
|
+
setattr(m, attr, getattr(base, attr))
|
|
380
|
+
if base.created_at != "createdAt":
|
|
381
|
+
m.created_at = base.created_at
|
|
382
|
+
if base.updated_at != "updatedAt":
|
|
383
|
+
m.updated_at = base.updated_at
|
|
384
|
+
for ms in self.by_class.values():
|
|
385
|
+
for m in ms:
|
|
386
|
+
fill(m, set())
|
|
387
|
+
for ms in self.by_class.values():
|
|
388
|
+
for m in ms:
|
|
389
|
+
if m.underscored is None:
|
|
390
|
+
m.underscored = self.underscored
|
|
391
|
+
if m.timestamps is None:
|
|
392
|
+
m.timestamps = True
|
|
393
|
+
if m.timestamps:
|
|
394
|
+
for attr in (m.created_at, m.updated_at):
|
|
395
|
+
m.columns.setdefault(attr, "")
|
|
396
|
+
if m.paranoid and not m.deleted_at:
|
|
397
|
+
m.deleted_at = "deletedAt"
|
|
398
|
+
if m.deleted_at:
|
|
399
|
+
m.columns.setdefault(m.deleted_at, "")
|
|
400
|
+
m.paranoid = True if m.paranoid is None else m.paranoid
|
|
401
|
+
if not m.pk and "id" not in m.columns and m.is_model:
|
|
402
|
+
m.columns = {"id": "", **m.columns}
|
|
403
|
+
for k, v in list(m.columns.items()):
|
|
404
|
+
if not v:
|
|
405
|
+
m.columns[k] = _snake(k) if m.underscored else k
|
|
406
|
+
if m.is_model and not m.table:
|
|
407
|
+
m.table, m.table_basis = pluralize(m.model_name or m.cls), "plural"
|
|
408
|
+
for a in m.assocs.values():
|
|
409
|
+
if not a["fk"]:
|
|
410
|
+
if a["kind"] == "belongsTo":
|
|
411
|
+
a["fk"] = a["as"] + "Id"
|
|
412
|
+
elif a["kind"] in ("hasMany", "hasOne", "belongsToMany"):
|
|
413
|
+
a["fk"] = _lower_first(m.model_name or m.cls) + "Id"
|
|
414
|
+
|
|
415
|
+
def model(self, name: str, rel: str) -> Model | None:
|
|
416
|
+
cands = [m for m in self.by_class.get(name, []) if m.is_model]
|
|
417
|
+
if len(cands) == 1:
|
|
418
|
+
return cands[0]
|
|
419
|
+
if cands:
|
|
420
|
+
d = os.path.dirname(rel)
|
|
421
|
+
near = [m for m in cands if os.path.dirname(m.rel) == d]
|
|
422
|
+
return near[0] if len(near) == 1 else None
|
|
423
|
+
return None
|
|
424
|
+
|
|
425
|
+
def tables(self) -> list:
|
|
426
|
+
from .schema_ts import TsTable
|
|
427
|
+
out = []
|
|
428
|
+
for ms in self.by_class.values():
|
|
429
|
+
for m in ms:
|
|
430
|
+
if not m.is_model or not m.table:
|
|
431
|
+
continue
|
|
432
|
+
cols = [{"name": c, "type": m.types.get(a, "")} for a, c in m.columns.items()]
|
|
433
|
+
out.append(TsTable(name=m.table, defined_at=[f"{m.rel}:{m.line}"], columns=cols,
|
|
434
|
+
primary_key=", ".join(m.column(p) for p in m.pk) or ("id" if "id" in m.columns else ""),
|
|
435
|
+
name_basis="sql" if m.table_basis == "sql" else "constant"))
|
|
436
|
+
return out
|
|
437
|
+
|
|
438
|
+
# -- receivers -----------------------------------------------------------------------------------------------
|
|
439
|
+
def receiver_model(self, f, recv: Node | None, call: Node) -> tuple[Model | None, list[str], str]:
|
|
440
|
+
"""(model, notes, why not) for the receiver of a static call: `User`, `this` in a static method of a model,
|
|
441
|
+
`User.unscoped()`, `User.scope("x")`."""
|
|
442
|
+
notes: list[str] = []
|
|
443
|
+
recv = unwrap(recv)
|
|
444
|
+
while recv is not None and recv.type == "call_expression":
|
|
445
|
+
fn = unwrap(recv.child_by_field_name("function"))
|
|
446
|
+
if fn is None or fn.type != "member_expression" or txt(fn.child_by_field_name("property")) not in SCOPE_CALLS:
|
|
447
|
+
return None, notes, ""
|
|
448
|
+
p = txt(fn.child_by_field_name("property"))
|
|
449
|
+
if p == "unscoped":
|
|
450
|
+
notes.append("unscoped")
|
|
451
|
+
elif p in ("scope", "withScope"):
|
|
452
|
+
notes.append(f"scope {o.norm_expr(txt(recv.child_by_field_name('arguments')))[:60]} not applied")
|
|
453
|
+
elif p == "schema":
|
|
454
|
+
notes.append("schema chosen at run time")
|
|
455
|
+
recv = unwrap(fn.child_by_field_name("object"))
|
|
456
|
+
if recv is None:
|
|
457
|
+
return None, notes, ""
|
|
458
|
+
if recv.type == "this":
|
|
459
|
+
cls = f._enclosing(call, ("class_declaration", "class", "abstract_class_declaration"))
|
|
460
|
+
meth = f._enclosing(call, ("method_definition",))
|
|
461
|
+
if cls is None or meth is None or not any(c.type == "static" for c in meth.children):
|
|
462
|
+
return None, notes, ""
|
|
463
|
+
name = txt(cls.child_by_field_name("name"))
|
|
464
|
+
m = self.model(name, f.rel)
|
|
465
|
+
return m, notes, "" if m else "model class is not a static @Table model"
|
|
466
|
+
if recv.type == "identifier":
|
|
467
|
+
name = txt(recv)
|
|
468
|
+
if name in self.by_class:
|
|
469
|
+
m = self.model(name, f.rel)
|
|
470
|
+
if m is None:
|
|
471
|
+
return None, notes, "model name is defined more than once"
|
|
472
|
+
if m.default_scope and "unscoped" not in notes:
|
|
473
|
+
notes.append("default scope not applied")
|
|
474
|
+
return m, notes, ""
|
|
475
|
+
return None, notes, ""
|
|
476
|
+
|
|
477
|
+
def instance_model(self, f, recv: Node | None, call: Node) -> Model | None:
|
|
478
|
+
recv = unwrap(recv)
|
|
479
|
+
if recv is None:
|
|
480
|
+
return None
|
|
481
|
+
if recv.type == "this":
|
|
482
|
+
cls = f._enclosing(call, ("class_declaration", "class", "abstract_class_declaration"))
|
|
483
|
+
meth = f._enclosing(call, ("method_definition",))
|
|
484
|
+
if cls is None or meth is None or any(c.type == "static" for c in meth.children):
|
|
485
|
+
return None
|
|
486
|
+
return self.model(txt(cls.child_by_field_name("name")), f.rel)
|
|
487
|
+
if recv.type != "identifier":
|
|
488
|
+
return None
|
|
489
|
+
name = txt(recv)
|
|
490
|
+
for func in f._scopes(call):
|
|
491
|
+
params = func.child_by_field_name("parameters")
|
|
492
|
+
for p in (params.named_children if params is not None else ()):
|
|
493
|
+
pat = p.child_by_field_name("pattern")
|
|
494
|
+
if pat is not None and txt(pat) == name:
|
|
495
|
+
return self._typed(f, txt(p.child_by_field_name("type")))
|
|
496
|
+
try:
|
|
497
|
+
decl = f._decl(name, call)
|
|
498
|
+
except Exception:
|
|
499
|
+
decl = None
|
|
500
|
+
if decl is None or decl[0].type != "variable_declarator":
|
|
501
|
+
return None
|
|
502
|
+
got = self._typed(f, txt(decl[0].child_by_field_name("type")))
|
|
503
|
+
if got is not None:
|
|
504
|
+
return got
|
|
505
|
+
val = unwrap(decl[0].child_by_field_name("value"))
|
|
506
|
+
if val is not None and val.type == "new_expression":
|
|
507
|
+
return self.model(txt(val.child_by_field_name("constructor")), f.rel)
|
|
508
|
+
if val is not None and val.type == "call_expression":
|
|
509
|
+
fn = unwrap(val.child_by_field_name("function"))
|
|
510
|
+
if fn is not None and fn.type == "member_expression" and txt(fn.child_by_field_name("property")) in (
|
|
511
|
+
"findByPk", "findOne", "create", "build", "findOrBuild"):
|
|
512
|
+
m, _n, _w = self.receiver_model(f, fn.child_by_field_name("object"), val)
|
|
513
|
+
return m
|
|
514
|
+
return None
|
|
515
|
+
|
|
516
|
+
def _typed(self, f, type_text: str) -> Model | None:
|
|
517
|
+
t = type_text.lstrip(": ").strip()
|
|
518
|
+
t = re.sub(r"\s*\|\s*(?:null|undefined)\b", "", t).strip()
|
|
519
|
+
return self.model(t, f.rel) if re.fullmatch(r"[A-Za-z_][\w$]*", t or "-") else None
|
|
520
|
+
|
|
521
|
+
def sites(self, f) -> list:
|
|
522
|
+
out = []
|
|
523
|
+
for call in f.calls:
|
|
524
|
+
fn = unwrap(call.child_by_field_name("function"))
|
|
525
|
+
if fn is None or fn.type != "member_expression":
|
|
526
|
+
continue
|
|
527
|
+
method = txt(fn.child_by_field_name("property"))
|
|
528
|
+
if method not in STATIC and method not in INSTANCE:
|
|
529
|
+
continue
|
|
530
|
+
args_node = call.child_by_field_name("arguments")
|
|
531
|
+
if args_node is None or args_node.type != "arguments":
|
|
532
|
+
continue
|
|
533
|
+
args = [a for a in args_node.named_children if a.type != "comment"]
|
|
534
|
+
recv = fn.child_by_field_name("object")
|
|
535
|
+
line = call.start_point[0] + 1
|
|
536
|
+
model, notes, why = (None, [], "")
|
|
537
|
+
instance = False
|
|
538
|
+
if method in STATIC:
|
|
539
|
+
model, notes, why = self.receiver_model(f, recv, call)
|
|
540
|
+
if model is None and method in INSTANCE and not why:
|
|
541
|
+
model = self.instance_model(f, recv, call)
|
|
542
|
+
instance = model is not None
|
|
543
|
+
if model is None:
|
|
544
|
+
if why or method in OWN:
|
|
545
|
+
self.stats.see(NAME, f.test)
|
|
546
|
+
self.stats.miss(NAME, f.test, why or "the receiver's model is not visible here", f.rel, line)
|
|
547
|
+
continue
|
|
548
|
+
self.stats.see(NAME, f.test)
|
|
549
|
+
try:
|
|
550
|
+
made = Call(self, f, call, model, method, args, txt(fn), instance, notes).run()
|
|
551
|
+
except Exception as e:
|
|
552
|
+
if os.environ.get("CODECOP_ORM_DEBUG"):
|
|
553
|
+
raise
|
|
554
|
+
self.stats.miss(NAME, f.test, f"internal error ({type(e).__name__})", f.rel, line)
|
|
555
|
+
continue
|
|
556
|
+
if not made:
|
|
557
|
+
self.stats.miss(NAME, f.test, "arguments could not be read", f.rel, line)
|
|
558
|
+
continue
|
|
559
|
+
self.stats.ok(NAME, f.test, len(made))
|
|
560
|
+
out.extend(made)
|
|
561
|
+
return out
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
# ---- one call ---------------------------------------------------------------------------------------------------
|
|
565
|
+
|
|
566
|
+
class Call:
|
|
567
|
+
def __init__(self, lib: Library, f, call: Node, model: Model, method: str, args: list[Node], sink: str,
|
|
568
|
+
instance: bool, notes: list[str]):
|
|
569
|
+
self.lib, self.f, self.call, self.m, self.method, self.args, self.sink = lib, f, call, model, method, args, sink
|
|
570
|
+
self.instance = instance
|
|
571
|
+
self.engine = o.engine_of(f)
|
|
572
|
+
self.notes = list(notes)
|
|
573
|
+
self.level = 2
|
|
574
|
+
self.joins: list[str] = []
|
|
575
|
+
self.join_cols: list[str] = []
|
|
576
|
+
self.separate: list[str] = []
|
|
577
|
+
self.aliases: dict[str, Model] = {}
|
|
578
|
+
if model.table_basis == "plural":
|
|
579
|
+
self.lower(1, f"table name {model.table} derived from the model name")
|
|
580
|
+
|
|
581
|
+
# -- names -----------------------------------------------------------------------------------------------------
|
|
582
|
+
def q(self, name: str) -> str:
|
|
583
|
+
return o.quote(self.engine, name)
|
|
584
|
+
|
|
585
|
+
def lower(self, level: int, note: str) -> None:
|
|
586
|
+
self.level = min(self.level, level)
|
|
587
|
+
if note not in self.notes:
|
|
588
|
+
self.notes.append(note)
|
|
589
|
+
|
|
590
|
+
def col(self, m: Model, attr: str, ref: str | None) -> str:
|
|
591
|
+
if attr not in m.columns and attr not in m.assocs:
|
|
592
|
+
if "." in attr or "->" in attr:
|
|
593
|
+
return mark(attr)
|
|
594
|
+
c = self.q(m.column(attr))
|
|
595
|
+
return f"{ref}.{c}" if ref else c
|
|
596
|
+
|
|
597
|
+
def ref(self) -> str | None:
|
|
598
|
+
return self.q(self.m.table) if self.joins else None
|
|
599
|
+
|
|
600
|
+
# -- objects ---------------------------------------------------------------------------------------------------
|
|
601
|
+
def read(self, node: Node | None, depth: int = 0):
|
|
602
|
+
"""An object argument as (entries [(key, node)], run-time parts [text]). `[Op.or]: ...` is the key `$or`.
|
|
603
|
+
None when it is not an object that can be read here."""
|
|
604
|
+
node = unwrap(node)
|
|
605
|
+
if node is None or depth > o.SETTINGS["orm_max_object_depth"]:
|
|
606
|
+
return None
|
|
607
|
+
if node.type == "object":
|
|
608
|
+
entries, extra = [], []
|
|
609
|
+
for c in node.named_children:
|
|
610
|
+
if c.type == "pair":
|
|
611
|
+
k, v = c.child_by_field_name("key"), c.child_by_field_name("value")
|
|
612
|
+
if k is None or v is None:
|
|
613
|
+
continue
|
|
614
|
+
if k.type == "computed_property_name":
|
|
615
|
+
inner = txt(k.named_children[0]) if k.named_children else ""
|
|
616
|
+
m = re.fullmatch(r"(?:Sequelize\.|sequelize\.)?Op\.(\w+)", inner)
|
|
617
|
+
if m:
|
|
618
|
+
entries.append(("$" + m.group(1), v))
|
|
619
|
+
else:
|
|
620
|
+
extra.append(txt(c))
|
|
621
|
+
else:
|
|
622
|
+
key = o.string_value(k)
|
|
623
|
+
entries.append((key if key is not None else txt(k), v))
|
|
624
|
+
elif c.type == "shorthand_property_identifier":
|
|
625
|
+
entries.append((txt(c), c))
|
|
626
|
+
elif c.type == "spread_element":
|
|
627
|
+
inner = unwrap(c.named_children[0]) if c.named_children else None
|
|
628
|
+
sub = self.read(inner, depth + 1) if inner is not None and inner.type in ("object", "identifier") else None
|
|
629
|
+
if sub is not None:
|
|
630
|
+
entries += sub[0]
|
|
631
|
+
extra += sub[1]
|
|
632
|
+
else:
|
|
633
|
+
extra.append("..." + txt(inner))
|
|
634
|
+
elif c.type == "method_definition":
|
|
635
|
+
extra.append(txt(c.child_by_field_name("name")) + "()")
|
|
636
|
+
return entries, extra
|
|
637
|
+
if node.type == "identifier":
|
|
638
|
+
base = as_object(self.f, node, self.call)
|
|
639
|
+
if base is None:
|
|
640
|
+
return None
|
|
641
|
+
try:
|
|
642
|
+
decl = self.f._decl(txt(node), self.call)
|
|
643
|
+
except Exception:
|
|
644
|
+
return None
|
|
645
|
+
if decl is None:
|
|
646
|
+
return None
|
|
647
|
+
val = unwrap(decl[0].child_by_field_name("value"))
|
|
648
|
+
got = self.read(val, depth + 1)
|
|
649
|
+
if got is None or val is None:
|
|
650
|
+
return None
|
|
651
|
+
entries, extra = list(got[0]), list(got[1])
|
|
652
|
+
for k, v in base.entries:
|
|
653
|
+
if not (val.start_byte <= v.start_byte < val.end_byte):
|
|
654
|
+
entries.append((k, v))
|
|
655
|
+
extra += ["optional: " + t for _k, _v, t in base.maybe]
|
|
656
|
+
name = txt(node)
|
|
657
|
+
extra += [x for x in base.extra if x.startswith(name)]
|
|
658
|
+
return entries, extra
|
|
659
|
+
return None
|
|
660
|
+
|
|
661
|
+
def get(self, obj, key: str) -> Node | None:
|
|
662
|
+
hit = None
|
|
663
|
+
for k, v in (obj[0] if obj else ()):
|
|
664
|
+
if k == key:
|
|
665
|
+
hit = v
|
|
666
|
+
return hit
|
|
667
|
+
|
|
668
|
+
# -- SQL expressions -----------------------------------------------------------------------------------------
|
|
669
|
+
def expr(self, node: Node | None) -> str:
|
|
670
|
+
"""sequelize.fn / col / literal / where as SQL; a «run-time part» otherwise."""
|
|
671
|
+
node = unwrap(node)
|
|
672
|
+
if node is None:
|
|
673
|
+
return "NULL"
|
|
674
|
+
lit = o.literal(node)
|
|
675
|
+
if node.type == "call_expression":
|
|
676
|
+
fn = unwrap(node.child_by_field_name("function"))
|
|
677
|
+
name = txt(fn.child_by_field_name("property")) if fn is not None and fn.type == "member_expression" else txt(fn)
|
|
678
|
+
a = node.child_by_field_name("arguments")
|
|
679
|
+
args = [x for x in (a.named_children if a is not None else []) if x.type != "comment"]
|
|
680
|
+
if name == "literal" and args and o.string_value(args[0]) is not None:
|
|
681
|
+
return o.string_value(args[0])
|
|
682
|
+
if name == "col" and args and o.string_value(args[0]) is not None:
|
|
683
|
+
return ".".join(self.q(p) for p in o.string_value(args[0]).split("."))
|
|
684
|
+
if name == "fn" and args and o.string_value(args[0]) is not None:
|
|
685
|
+
return o.string_value(args[0]).upper() + "(" + ", ".join(self.expr(x) for x in args[1:]) + ")"
|
|
686
|
+
if name == "cast" and len(args) == 2 and o.string_value(args[1]):
|
|
687
|
+
return f"CAST({self.expr(args[0])} AS {o.string_value(args[1])})"
|
|
688
|
+
if lit is not None:
|
|
689
|
+
return lit
|
|
690
|
+
return mark_node(node)
|
|
691
|
+
|
|
692
|
+
def value(self, node: Node | None) -> str:
|
|
693
|
+
node = unwrap(node)
|
|
694
|
+
if node is not None and node.type == "call_expression" and re.match(r"^(?:S|s)equelize\.(?:fn|col|literal|cast)\(", txt(node)):
|
|
695
|
+
return self.expr(node)
|
|
696
|
+
return o.value(node)
|
|
697
|
+
|
|
698
|
+
def is_list(self, node: Node | None) -> bool:
|
|
699
|
+
"""An array value: written as one, or a name declared as one (`ids: string[]`, `= [...]`, `= x.map(...)`)."""
|
|
700
|
+
node = unwrap(node)
|
|
701
|
+
if node is None:
|
|
702
|
+
return False
|
|
703
|
+
if node.type == "array":
|
|
704
|
+
return True
|
|
705
|
+
if node.type == "call_expression":
|
|
706
|
+
fn = unwrap(node.child_by_field_name("function"))
|
|
707
|
+
return fn is not None and fn.type == "member_expression" and txt(fn.child_by_field_name("property")) in (
|
|
708
|
+
"map", "filter", "flatMap", "concat", "slice", "uniq", "compact", "flat")
|
|
709
|
+
if node.type == "member_expression":
|
|
710
|
+
return bool(re.search(r"(?:Ids|ids|IDs|List|list)$", txt(node.child_by_field_name("property"))))
|
|
711
|
+
if node.type in ("identifier", "shorthand_property_identifier"):
|
|
712
|
+
name = txt(node)
|
|
713
|
+
for func in self.f._scopes(self.call):
|
|
714
|
+
params = func.child_by_field_name("parameters")
|
|
715
|
+
for p in (params.named_children if params is not None else ()):
|
|
716
|
+
pat = p.child_by_field_name("pattern")
|
|
717
|
+
if pat is not None and txt(pat) == name:
|
|
718
|
+
ty = txt(p.child_by_field_name("type"))
|
|
719
|
+
return "[]" in ty or "Array<" in ty
|
|
720
|
+
try:
|
|
721
|
+
decl = self.f._decl(name, self.call)
|
|
722
|
+
except Exception:
|
|
723
|
+
decl = None
|
|
724
|
+
if decl is not None and decl[0].type == "variable_declarator":
|
|
725
|
+
ty = txt(decl[0].child_by_field_name("type"))
|
|
726
|
+
if "[]" in ty or "Array<" in ty:
|
|
727
|
+
return True
|
|
728
|
+
if self.is_list(decl[0].child_by_field_name("value")):
|
|
729
|
+
return True
|
|
730
|
+
return bool(re.search(r"(?:Ids|IDs)$", name))
|
|
731
|
+
return False
|
|
732
|
+
|
|
733
|
+
# -- where -----------------------------------------------------------------------------------------------------
|
|
734
|
+
def where(self, node: Node | None, m: Model, ref: str | None) -> list[str]:
|
|
735
|
+
node = unwrap(node)
|
|
736
|
+
if node is None or o.is_undefined(node):
|
|
737
|
+
return []
|
|
738
|
+
if node.type == "call_expression" and re.match(r"^(?:S|s)equelize\.(?:where|literal|and|or)\(", txt(node)):
|
|
739
|
+
if re.match(r"^(?:S|s)equelize\.literal\(", txt(node)):
|
|
740
|
+
return [self.expr(node)]
|
|
741
|
+
return [mark_node(node)]
|
|
742
|
+
obj = self.read(node)
|
|
743
|
+
if obj is None:
|
|
744
|
+
self.lower(1, "where object built at run time")
|
|
745
|
+
return [mark_node(node)]
|
|
746
|
+
preds = []
|
|
747
|
+
for k, v in obj[0]:
|
|
748
|
+
p = self.pred(k, v, m, ref)
|
|
749
|
+
if p:
|
|
750
|
+
preds.append(p)
|
|
751
|
+
for x in obj[1]:
|
|
752
|
+
preds.append(mark(x))
|
|
753
|
+
return preds
|
|
754
|
+
|
|
755
|
+
def pred(self, key: str, v: Node, m: Model, ref: str | None) -> str:
|
|
756
|
+
uv = unwrap(v)
|
|
757
|
+
if uv is None or o.is_undefined(uv):
|
|
758
|
+
return ""
|
|
759
|
+
if key in ("$or", "$and"):
|
|
760
|
+
items = o.array_items(uv)
|
|
761
|
+
if items is None:
|
|
762
|
+
obj = self.read(uv)
|
|
763
|
+
if obj is None:
|
|
764
|
+
return mark_node(uv)
|
|
765
|
+
parts = [p for p in (self.pred(k2, v2, m, ref) for k2, v2 in obj[0]) if p] + [mark(x) for x in obj[1]]
|
|
766
|
+
else:
|
|
767
|
+
parts = []
|
|
768
|
+
for it in items:
|
|
769
|
+
sub = self.where(it, m, ref)
|
|
770
|
+
if sub:
|
|
771
|
+
parts.append(" AND ".join(sub) if len(sub) == 1 else "(" + " AND ".join(sub) + ")")
|
|
772
|
+
if not parts:
|
|
773
|
+
return ""
|
|
774
|
+
return "(" + f" {key[1:].upper()} ".join(parts) + ")"
|
|
775
|
+
if key == "$not":
|
|
776
|
+
sub = self.where(uv, m, ref)
|
|
777
|
+
return "NOT (" + " AND ".join(sub) + ")" if sub else ""
|
|
778
|
+
if key.startswith("$") and key.endswith("$") and len(key) > 2:
|
|
779
|
+
path = key[1:-1].split(".")
|
|
780
|
+
colref = ".".join(self.q(p) for p in path[:-1]) + "." + self.q(self.aliased_column(path))
|
|
781
|
+
else:
|
|
782
|
+
if key.startswith("$"):
|
|
783
|
+
return mark(f"{key}: {txt(uv)}")
|
|
784
|
+
colref = self.col(m, key, ref)
|
|
785
|
+
# an operator object: { [Op.gt]: 3, [Op.lt]: 9 }
|
|
786
|
+
if uv.type in ("object", "identifier"):
|
|
787
|
+
obj = self.read(uv) if uv.type == "object" or not self.is_list(uv) else None
|
|
788
|
+
if obj is not None and obj[0] and all(k2.startswith("$") for k2, _ in obj[0]):
|
|
789
|
+
parts = [self.op(colref, k2[1:], v2, m, ref) for k2, v2 in obj[0]] + [mark(x) for x in obj[1]]
|
|
790
|
+
return " AND ".join(p for p in parts if p)
|
|
791
|
+
if obj is not None and uv.type == "object" and obj[0]:
|
|
792
|
+
return mark(f"{key}: {txt(uv)}") # a JSON attribute's nested keys
|
|
793
|
+
if uv.type == "array" or self.is_list(uv):
|
|
794
|
+
return f"{colref} IN ({o.in_list(uv)})"
|
|
795
|
+
lit = o.literal(uv)
|
|
796
|
+
if lit == "NULL":
|
|
797
|
+
return f"{colref} IS NULL"
|
|
798
|
+
return f"{colref} = {self.value(uv)}"
|
|
799
|
+
|
|
800
|
+
def aliased_column(self, path: list[str]) -> str:
|
|
801
|
+
alias = path[-2] if len(path) > 1 else ""
|
|
802
|
+
target = self.aliases.get(alias)
|
|
803
|
+
return target.column(path[-1]) if target is not None else path[-1]
|
|
804
|
+
|
|
805
|
+
def op(self, colref: str, op: str, v: Node, m: Model, ref: str | None) -> str:
|
|
806
|
+
uv = unwrap(v)
|
|
807
|
+
lit = o.literal(uv)
|
|
808
|
+
if op in ("in", "notIn"):
|
|
809
|
+
return f"{colref} {'NOT IN' if op == 'notIn' else 'IN'} ({o.in_list(uv)})"
|
|
810
|
+
if op in ("is", "not"):
|
|
811
|
+
if lit in ("NULL", "TRUE", "FALSE"):
|
|
812
|
+
return f"{colref} IS {'NOT ' if op == 'not' else ''}{lit}"
|
|
813
|
+
return f"{colref} {'<>' if op == 'not' else 'IS'} {self.value(uv)}"
|
|
814
|
+
if op == "ne" and lit == "NULL":
|
|
815
|
+
return f"{colref} IS NOT NULL"
|
|
816
|
+
if op == "eq" and lit == "NULL":
|
|
817
|
+
return f"{colref} IS NULL"
|
|
818
|
+
if op in ("between", "notBetween"):
|
|
819
|
+
items = o.array_items(uv)
|
|
820
|
+
if items and len(items) == 2:
|
|
821
|
+
return f"{colref} {'NOT ' if op == 'notBetween' else ''}BETWEEN {self.value(items[0])} AND {self.value(items[1])}"
|
|
822
|
+
return f"{colref} {'NOT ' if op == 'notBetween' else ''}BETWEEN {mark_node(uv)} AND {mark_node(uv)}"
|
|
823
|
+
if op in LIKE_WRAP:
|
|
824
|
+
s = o.string_value(uv)
|
|
825
|
+
pre, post = LIKE_WRAP[op]
|
|
826
|
+
return f"{colref} LIKE " + (o.sql_string(pre + s + post) if s is not None else self.value(uv))
|
|
827
|
+
if op in ("any", "all"):
|
|
828
|
+
return f"{colref} = {op.upper()} ({self.value(uv)})"
|
|
829
|
+
if op in ("or", "and"):
|
|
830
|
+
items = o.array_items(uv)
|
|
831
|
+
if items is not None:
|
|
832
|
+
parts = [f"{colref} = {self.value(i)}" if o.literal(i) != "NULL" else f"{colref} IS NULL" for i in items]
|
|
833
|
+
return "(" + f" {op.upper()} ".join(parts) + ")" if parts else ""
|
|
834
|
+
obj = self.read(uv)
|
|
835
|
+
if obj is not None:
|
|
836
|
+
parts = [self.op(colref, k[1:], vv, m, ref) for k, vv in obj[0] if k.startswith("$")]
|
|
837
|
+
return "(" + f" {op.upper()} ".join(parts) + ")" if parts else ""
|
|
838
|
+
return mark(f"{colref} {op} {txt(uv)}")
|
|
839
|
+
if op == "col":
|
|
840
|
+
s = o.string_value(uv)
|
|
841
|
+
return f"{colref} = " + (".".join(self.q(p) for p in s.split(".")) if s else mark_node(uv))
|
|
842
|
+
sym = OPS.get(op)
|
|
843
|
+
if sym is None:
|
|
844
|
+
return mark(f"{colref} {op} {txt(uv)}")
|
|
845
|
+
if sym in ("ILIKE", "NOT ILIKE") and self.engine == "mysql":
|
|
846
|
+
sym = sym.replace("ILIKE", "LIKE")
|
|
847
|
+
return f"{colref} {sym} {self.value(uv)}"
|
|
848
|
+
|
|
849
|
+
# -- options ---------------------------------------------------------------------------------------------------
|
|
850
|
+
def attributes(self, node: Node | None, m: Model, ref: str | None) -> list[str]:
|
|
851
|
+
node = unwrap(node)
|
|
852
|
+
every = [self.col(m, a, ref) for a in m.columns]
|
|
853
|
+
if node is None:
|
|
854
|
+
return every or ["*"]
|
|
855
|
+
items = o.array_items(node)
|
|
856
|
+
if items is not None:
|
|
857
|
+
return [self.attribute(i, m, ref) for i in items] or every
|
|
858
|
+
obj = self.read(node)
|
|
859
|
+
if obj is not None:
|
|
860
|
+
inc, exc = self.get(obj, "include"), self.get(obj, "exclude")
|
|
861
|
+
cols = list(every)
|
|
862
|
+
if exc is not None:
|
|
863
|
+
drop = [o.string_value(i) for i in (o.array_items(exc) or [])]
|
|
864
|
+
if o.array_items(exc) is None:
|
|
865
|
+
self.lower(1, "excluded attributes chosen at run time")
|
|
866
|
+
cols = [self.col(m, a, ref) for a in m.columns if a not in drop]
|
|
867
|
+
if inc is not None:
|
|
868
|
+
cols += [self.attribute(i, m, ref) for i in (o.array_items(inc) or [])]
|
|
869
|
+
return cols or ["*"]
|
|
870
|
+
self.lower(1, "attribute list chosen at run time")
|
|
871
|
+
return [mark_node(node)]
|
|
872
|
+
|
|
873
|
+
def attribute(self, node: Node, m: Model, ref: str | None) -> str:
|
|
874
|
+
s = o.string_value(node)
|
|
875
|
+
if s is not None:
|
|
876
|
+
return self.col(m, s, ref)
|
|
877
|
+
items = o.array_items(node)
|
|
878
|
+
if items and len(items) == 2 and o.string_value(items[1]):
|
|
879
|
+
inner = o.string_value(items[0])
|
|
880
|
+
e = self.col(m, inner, ref) if inner is not None else self.expr(items[0])
|
|
881
|
+
return f"{e} AS {self.q(o.string_value(items[1]))}"
|
|
882
|
+
return mark_node(node)
|
|
883
|
+
|
|
884
|
+
def order(self, node: Node | None, m: Model, ref: str | None) -> list[str]:
|
|
885
|
+
node = unwrap(node)
|
|
886
|
+
if node is None:
|
|
887
|
+
return []
|
|
888
|
+
items = o.array_items(node)
|
|
889
|
+
if items is None:
|
|
890
|
+
if node.type == "call_expression":
|
|
891
|
+
return [self.expr(node)]
|
|
892
|
+
self.lower(1, "order chosen at run time")
|
|
893
|
+
return [mark_node(node)]
|
|
894
|
+
out = []
|
|
895
|
+
for it in items:
|
|
896
|
+
s = o.string_value(it)
|
|
897
|
+
if s is not None:
|
|
898
|
+
out.append(self.col(m, s, ref))
|
|
899
|
+
continue
|
|
900
|
+
parts = o.array_items(it)
|
|
901
|
+
if parts is None:
|
|
902
|
+
out.append(self.expr(it))
|
|
903
|
+
continue
|
|
904
|
+
direction = ""
|
|
905
|
+
if parts and o.string_value(parts[-1]) and o.string_value(parts[-1]).upper().replace(" NULLS", "").split()[0] in ("ASC", "DESC"):
|
|
906
|
+
direction = " " + o.string_value(parts[-1]).upper()
|
|
907
|
+
parts = parts[:-1]
|
|
908
|
+
if len(parts) == 1:
|
|
909
|
+
s = o.string_value(parts[0])
|
|
910
|
+
out.append((self.col(m, s, ref) if s is not None else self.expr(parts[0])) + direction)
|
|
911
|
+
elif len(parts) >= 2 and o.string_value(parts[-1]) is not None:
|
|
912
|
+
# [Assoc, "column"] / [{ model, as }, "column"] / ["assoc", "column"]
|
|
913
|
+
alias = o.string_value(parts[-2])
|
|
914
|
+
if alias is None:
|
|
915
|
+
t = unwrap(parts[-2])
|
|
916
|
+
alias = txt(t) if t is not None and t.type == "identifier" else ""
|
|
917
|
+
a = next((k for k, v in self.aliases.items() if v.cls == alias), "")
|
|
918
|
+
alias = a or alias
|
|
919
|
+
target = self.aliases.get(alias)
|
|
920
|
+
c = target.column(o.string_value(parts[-1])) if target else o.string_value(parts[-1])
|
|
921
|
+
out.append(f"{self.q(alias)}.{self.q(c)}{direction}" if alias else mark_node(it))
|
|
922
|
+
else:
|
|
923
|
+
out.append(mark_node(it) + direction)
|
|
924
|
+
return out
|
|
925
|
+
|
|
926
|
+
def num(self, node: Node | None) -> str | None:
|
|
927
|
+
node = unwrap(node)
|
|
928
|
+
if node is None or o.is_undefined(node):
|
|
929
|
+
return None
|
|
930
|
+
return o.value(node)
|
|
931
|
+
|
|
932
|
+
# -- include ---------------------------------------------------------------------------------------------------
|
|
933
|
+
def includes(self, node: Node | None, m: Model, ref: str, depth: int = 0) -> None:
|
|
934
|
+
node = unwrap(node)
|
|
935
|
+
if node is None or depth > o.SETTINGS["orm_max_relation_depth"]:
|
|
936
|
+
return
|
|
937
|
+
items = o.array_items(node)
|
|
938
|
+
if items is None:
|
|
939
|
+
items = [node]
|
|
940
|
+
for it in items:
|
|
941
|
+
self.include(it, m, ref, depth)
|
|
942
|
+
|
|
943
|
+
def include(self, it: Node, m: Model, ref: str, depth: int) -> None:
|
|
944
|
+
it = unwrap(it)
|
|
945
|
+
target, alias, opts = None, "", None
|
|
946
|
+
if it is None:
|
|
947
|
+
return
|
|
948
|
+
if it.type == "identifier" and it.text.decode() in self.lib.by_class:
|
|
949
|
+
target = self.lib.model(txt(it), self.f.rel)
|
|
950
|
+
elif o.string_value(it) is not None:
|
|
951
|
+
alias = o.string_value(it)
|
|
952
|
+
else:
|
|
953
|
+
opts = self.read(it)
|
|
954
|
+
if opts is None:
|
|
955
|
+
self.lower(1, f"include {o.norm_expr(txt(it))[:50]} not translated")
|
|
956
|
+
return
|
|
957
|
+
mnode = unwrap(self.get(opts, "model"))
|
|
958
|
+
if mnode is not None and mnode.type == "call_expression":
|
|
959
|
+
mt = txt(mnode)
|
|
960
|
+
if ".scope(" in mt:
|
|
961
|
+
self.lower(1, f"include scope {o.norm_expr(mt)[:50]} not applied")
|
|
962
|
+
mfn = unwrap(mnode.child_by_field_name("function"))
|
|
963
|
+
mnode = unwrap(mfn.child_by_field_name("object")) if mfn is not None and mfn.type == "member_expression" else None
|
|
964
|
+
if mnode is not None:
|
|
965
|
+
target = self.lib.model(txt(mnode).split(".")[-1], self.f.rel)
|
|
966
|
+
alias = o.string_value(self.get(opts, "as")) or o.string_value(self.get(opts, "association")) or ""
|
|
967
|
+
assoc = m.assocs.get(alias) if alias else None
|
|
968
|
+
if assoc is None and target is not None:
|
|
969
|
+
cands = [a for a in m.assocs.values() if a["target"] == target.cls]
|
|
970
|
+
assoc = cands[0] if len(cands) == 1 else None
|
|
971
|
+
if assoc is not None and target is None:
|
|
972
|
+
target = self.lib.model(assoc["target"], m.rel)
|
|
973
|
+
if assoc is None or target is None:
|
|
974
|
+
self.lower(1, f"include {o.norm_expr(txt(it))[:50]} not translated (association not visible)")
|
|
975
|
+
return
|
|
976
|
+
alias = alias or assoc["as"]
|
|
977
|
+
self.aliases[alias] = target
|
|
978
|
+
a = self.q(alias)
|
|
979
|
+
where = self.where(self.get(opts, "where"), target, a) if opts else []
|
|
980
|
+
required = _bool(self.get(opts, "required")) if opts else None
|
|
981
|
+
if required is None:
|
|
982
|
+
required = bool(where)
|
|
983
|
+
paranoid = target.paranoid and (_bool(self.get(opts, "paranoid")) is not False if opts else True)
|
|
984
|
+
if paranoid:
|
|
985
|
+
where.append(f"{a}.{self.q(target.column(target.deleted_at))} IS NULL")
|
|
986
|
+
separate = opts is not None and _bool(self.get(opts, "separate")) is True and assoc["kind"] == "hasMany"
|
|
987
|
+
kind = "INNER JOIN" if required else "LEFT OUTER JOIN"
|
|
988
|
+
fk = assoc["fk"]
|
|
989
|
+
if assoc["kind"] == "belongsTo":
|
|
990
|
+
on = f"{a}.{self.q(target.pk_column())} = {ref}.{self.q(m.column(fk))}"
|
|
991
|
+
elif assoc["kind"] in ("hasMany", "hasOne"):
|
|
992
|
+
if separate:
|
|
993
|
+
cols = self.attributes(self.get(opts, "attributes"), target, None)
|
|
994
|
+
w = [f"{self.q(target.column(fk))} IN ({mark(m.cls + '.' + m.pk_column() + ' list')})"] + \
|
|
995
|
+
[p.replace(a + ".", "") for p in where]
|
|
996
|
+
order = self.order(self.get(opts, "order"), target, None)
|
|
997
|
+
sql = f"SELECT {', '.join(cols)} FROM {self.q(target.table)} WHERE " + " AND ".join(w)
|
|
998
|
+
if order:
|
|
999
|
+
sql += " ORDER BY " + ", ".join(order)
|
|
1000
|
+
self.separate.append(sql)
|
|
1001
|
+
return
|
|
1002
|
+
on = f"{a}.{self.q(target.column(fk))} = {ref}.{self.q(m.pk_column())}"
|
|
1003
|
+
else:
|
|
1004
|
+
through = self.lib.model(assoc["through"], m.rel)
|
|
1005
|
+
other = assoc["other"] or _lower_first(target.model_name or target.cls) + "Id"
|
|
1006
|
+
if through is None:
|
|
1007
|
+
self.lower(1, f"include {alias}: join model {assoc['through']} not visible")
|
|
1008
|
+
return
|
|
1009
|
+
j = self.q(alias + "->" + through.cls)
|
|
1010
|
+
self.joins.append(f"{kind} {self.q(through.table)} AS {j} ON {j}.{self.q(through.column(fk))} = {ref}.{self.q(m.pk_column())}")
|
|
1011
|
+
on = f"{a}.{self.q(target.pk_column())} = {j}.{self.q(through.column(other))}"
|
|
1012
|
+
self.joins.append(f"{kind} {self.q(target.table)} AS {a} ON " + " AND ".join([on] + where))
|
|
1013
|
+
attrs = self.attributes(self.get(opts, "attributes") if opts else None, target, a)
|
|
1014
|
+
self.join_cols += [f"{c} AS {self.q(alias + '.' + c.split('.')[-1].strip(chr(34)))}" if c.startswith(a + ".") else c
|
|
1015
|
+
for c in attrs]
|
|
1016
|
+
if opts is not None and self.get(opts, "include") is not None:
|
|
1017
|
+
self.includes(self.get(opts, "include"), target, a, depth + 1)
|
|
1018
|
+
|
|
1019
|
+
# -- statements -------------------------------------------------------------------------------------------------
|
|
1020
|
+
def soft(self, preds: list[str], opts, ref: str | None) -> list[str]:
|
|
1021
|
+
if self.m.paranoid and self.m.deleted_at and not (opts is not None and _bool(self.get(opts, "paranoid")) is False):
|
|
1022
|
+
return preds + [f"{self.col(self.m, self.m.deleted_at, ref)} IS NULL"]
|
|
1023
|
+
return preds
|
|
1024
|
+
|
|
1025
|
+
def select(self, opts, *, limit1: bool = False, pk: Node | None = None, count: str | None = None) -> str:
|
|
1026
|
+
m = self.m
|
|
1027
|
+
table = self.q(m.table)
|
|
1028
|
+
if opts is not None:
|
|
1029
|
+
self.includes(self.get(opts, "include"), m, table)
|
|
1030
|
+
ref = table if self.joins else None
|
|
1031
|
+
preds = []
|
|
1032
|
+
if pk is not None:
|
|
1033
|
+
preds.append(f"{self.col(m, m.pk[0] if m.pk else 'id', ref)} = {self.value(pk)}")
|
|
1034
|
+
if opts is not None:
|
|
1035
|
+
preds += self.where(self.get(opts, "where"), m, ref)
|
|
1036
|
+
if opts[1]:
|
|
1037
|
+
self.lower(1, "options built at run time: " + ", ".join(opts[1])[:80])
|
|
1038
|
+
preds = self.soft(preds, opts, ref)
|
|
1039
|
+
if count is not None:
|
|
1040
|
+
cols = [count]
|
|
1041
|
+
else:
|
|
1042
|
+
cols = self.attributes(self.get(opts, "attributes") if opts else None, m, ref) + self.join_cols
|
|
1043
|
+
sql = f"SELECT {', '.join(cols)} FROM {table}"
|
|
1044
|
+
if self.joins:
|
|
1045
|
+
sql += " " + " ".join(self.joins)
|
|
1046
|
+
if preds:
|
|
1047
|
+
sql += " WHERE " + " AND ".join(preds)
|
|
1048
|
+
if opts is not None:
|
|
1049
|
+
group = unwrap(self.get(opts, "group"))
|
|
1050
|
+
if group is not None:
|
|
1051
|
+
items = o.array_items(group)
|
|
1052
|
+
g = [self.col(m, o.string_value(i), ref) if o.string_value(i) else self.expr(i) for i in items] if items is not None \
|
|
1053
|
+
else ([self.col(m, o.string_value(group), ref)] if o.string_value(group) else [mark_node(group)])
|
|
1054
|
+
sql += " GROUP BY " + ", ".join(g)
|
|
1055
|
+
having = self.get(opts, "having")
|
|
1056
|
+
if having is not None:
|
|
1057
|
+
h = self.where(having, m, ref)
|
|
1058
|
+
if h:
|
|
1059
|
+
sql += " HAVING " + " AND ".join(h)
|
|
1060
|
+
if count is None:
|
|
1061
|
+
order = self.order(self.get(opts, "order"), m, ref)
|
|
1062
|
+
if order:
|
|
1063
|
+
sql += " ORDER BY " + ", ".join(order)
|
|
1064
|
+
lim = self.num(self.get(opts, "limit"))
|
|
1065
|
+
if lim is None and limit1:
|
|
1066
|
+
lim = "1"
|
|
1067
|
+
if lim is not None:
|
|
1068
|
+
sql += f" LIMIT {lim}"
|
|
1069
|
+
off = self.num(self.get(opts, "offset"))
|
|
1070
|
+
if off is not None:
|
|
1071
|
+
sql += f" OFFSET {off}"
|
|
1072
|
+
lock = self.get(opts, "lock")
|
|
1073
|
+
if lock is not None and txt(unwrap(lock)) not in ("false", "undefined"):
|
|
1074
|
+
sql += " FOR UPDATE"
|
|
1075
|
+
elif limit1:
|
|
1076
|
+
sql += " LIMIT 1"
|
|
1077
|
+
return sql
|
|
1078
|
+
|
|
1079
|
+
def values(self, node: Node | None) -> tuple[list[str], list[str]]:
|
|
1080
|
+
obj = self.read(node)
|
|
1081
|
+
m = self.m
|
|
1082
|
+
if obj is None:
|
|
1083
|
+
self.lower(0, "values object built at run time: columns are every attribute of the model")
|
|
1084
|
+
cols = [a for a in m.columns if a not in (m.deleted_at,)]
|
|
1085
|
+
return [self.q(m.column(a)) for a in cols], [mark(f"{txt(node)}.{a}") for a in cols]
|
|
1086
|
+
cols, vals = [], []
|
|
1087
|
+
for k, v in obj[0]:
|
|
1088
|
+
if k.startswith("$") or o.is_undefined(v):
|
|
1089
|
+
continue
|
|
1090
|
+
if k in m.assocs and k not in m.columns:
|
|
1091
|
+
continue
|
|
1092
|
+
if k not in m.columns:
|
|
1093
|
+
self.lower(1, f"`{k}` is not a known attribute of {m.cls}")
|
|
1094
|
+
cols.append(self.q(m.column(k)))
|
|
1095
|
+
vals.append(self.value(v))
|
|
1096
|
+
for x in obj[1]:
|
|
1097
|
+
self.lower(1, "values set at run time: " + x[:60])
|
|
1098
|
+
return cols, vals
|
|
1099
|
+
|
|
1100
|
+
def stamp(self, cols: list[str], vals: list[str], *, created: bool) -> None:
|
|
1101
|
+
m = self.m
|
|
1102
|
+
if not m.timestamps:
|
|
1103
|
+
return
|
|
1104
|
+
names = ([m.created_at] if created else []) + [m.updated_at]
|
|
1105
|
+
for n in names:
|
|
1106
|
+
c = self.q(m.column(n))
|
|
1107
|
+
if c not in cols:
|
|
1108
|
+
cols.append(c)
|
|
1109
|
+
vals.append(mark("now"))
|
|
1110
|
+
|
|
1111
|
+
def insert(self, node: Node | None, *, many: bool = False, opts=None) -> str:
|
|
1112
|
+
m = self.m
|
|
1113
|
+
source = node
|
|
1114
|
+
if many:
|
|
1115
|
+
items = o.array_items(node)
|
|
1116
|
+
if items:
|
|
1117
|
+
source = items[0]
|
|
1118
|
+
if len(items) > 1:
|
|
1119
|
+
self.notes.append(f"{len(items)} rows")
|
|
1120
|
+
else:
|
|
1121
|
+
self.notes.append("one row shown of a list built at run time")
|
|
1122
|
+
self.lower(1, "rows built at run time")
|
|
1123
|
+
source = None
|
|
1124
|
+
cols, vals = self.values(source) if source is not None else self.values_unknown(node)
|
|
1125
|
+
self.stamp(cols, vals, created=True)
|
|
1126
|
+
if m.pk and self.q(m.pk_column()) not in cols and m.pk_column() == "id":
|
|
1127
|
+
cols.insert(0, self.q("id"))
|
|
1128
|
+
vals.insert(0, mark("default id"))
|
|
1129
|
+
sql = f"INSERT INTO {self.q(m.table)} ({', '.join(cols)}) VALUES ({', '.join(vals)})"
|
|
1130
|
+
if opts is not None and _bool(self.get(opts, "ignoreDuplicates")):
|
|
1131
|
+
sql += " ON CONFLICT DO NOTHING"
|
|
1132
|
+
upd = unwrap(self.get(opts, "updateOnDuplicate")) if opts is not None else None
|
|
1133
|
+
if upd is not None:
|
|
1134
|
+
names = [o.string_value(i) for i in (o.array_items(upd) or [])]
|
|
1135
|
+
if names and all(names):
|
|
1136
|
+
sets = ", ".join(f"{self.q(m.column(n))} = EXCLUDED.{self.q(m.column(n))}" for n in names)
|
|
1137
|
+
sql += f" ON CONFLICT ({self.q(m.pk_column())}) DO UPDATE SET {sets}"
|
|
1138
|
+
if self.engine in ("postgres", ""):
|
|
1139
|
+
sql += " RETURNING *"
|
|
1140
|
+
return sql
|
|
1141
|
+
|
|
1142
|
+
def values_unknown(self, node: Node | None) -> tuple[list[str], list[str]]:
|
|
1143
|
+
m = self.m
|
|
1144
|
+
cols = [a for a in m.columns if a not in (m.deleted_at,)]
|
|
1145
|
+
return [self.q(m.column(a)) for a in cols], [mark(f"{txt(node)}.{a}") for a in cols]
|
|
1146
|
+
|
|
1147
|
+
def update(self, values: Node | None, opts) -> str:
|
|
1148
|
+
m = self.m
|
|
1149
|
+
cols, vals = self.values(values)
|
|
1150
|
+
self.stamp(cols, vals, created=False)
|
|
1151
|
+
sets = ", ".join(f"{c} = {v}" for c, v in zip(cols, vals))
|
|
1152
|
+
preds = self.where(self.get(opts, "where"), m, None) if opts is not None else []
|
|
1153
|
+
preds = self.soft(preds, opts, None)
|
|
1154
|
+
sql = f"UPDATE {self.q(m.table)} SET {sets}"
|
|
1155
|
+
if preds:
|
|
1156
|
+
sql += " WHERE " + " AND ".join(preds)
|
|
1157
|
+
return sql
|
|
1158
|
+
|
|
1159
|
+
def destroy(self, opts, preds: list[str] | None = None) -> str:
|
|
1160
|
+
m = self.m
|
|
1161
|
+
if preds is None:
|
|
1162
|
+
preds = self.where(self.get(opts, "where"), m, None) if opts is not None else []
|
|
1163
|
+
if opts is None or self.get(opts, "where") is None:
|
|
1164
|
+
if not _bool(self.get(opts, "truncate") if opts else None):
|
|
1165
|
+
self.lower(1, "destroy without a where")
|
|
1166
|
+
force = opts is not None and _bool(self.get(opts, "force"))
|
|
1167
|
+
if m.paranoid and m.deleted_at and not force:
|
|
1168
|
+
preds = preds + [f"{self.q(m.column(m.deleted_at))} IS NULL"]
|
|
1169
|
+
return f"UPDATE {self.q(m.table)} SET {self.q(m.column(m.deleted_at))} = {mark('now')}" + \
|
|
1170
|
+
(" WHERE " + " AND ".join(preds) if preds else "")
|
|
1171
|
+
return f"DELETE FROM {self.q(m.table)}" + (" WHERE " + " AND ".join(preds) if preds else "")
|
|
1172
|
+
|
|
1173
|
+
def by_pk(self) -> str:
|
|
1174
|
+
m = self.m
|
|
1175
|
+
recv = unwrap(unwrap(self.call.child_by_field_name("function")).child_by_field_name("object"))
|
|
1176
|
+
who = "this" if recv is not None and recv.type == "this" else txt(recv)
|
|
1177
|
+
return f"{self.q(m.pk_column())} = {mark(who + '.' + (m.pk[0] if m.pk else 'id'))}"
|
|
1178
|
+
|
|
1179
|
+
def run(self) -> list:
|
|
1180
|
+
args, m = self.args, self.m
|
|
1181
|
+
method = self.method
|
|
1182
|
+
out: list[str] = []
|
|
1183
|
+
if self.instance:
|
|
1184
|
+
opts = None
|
|
1185
|
+
if method == "save":
|
|
1186
|
+
opts = self.read(args[0]) if args else None
|
|
1187
|
+
fields = o.array_items(self.get(opts, "fields")) if opts is not None and self.get(opts, "fields") is not None else None
|
|
1188
|
+
assigned = self.assigned()
|
|
1189
|
+
names = [o.string_value(x) for x in fields] if fields else assigned
|
|
1190
|
+
names = [n for n in (names or []) if n]
|
|
1191
|
+
if names:
|
|
1192
|
+
sets = [f"{self.q(m.column(n))} = {mark('value of ' + n)}" for n in dict.fromkeys(names)]
|
|
1193
|
+
if not fields:
|
|
1194
|
+
self.notes.append("columns assigned before the call")
|
|
1195
|
+
else:
|
|
1196
|
+
sets = [f"{mark('changed attributes')} = {mark('values')}"]
|
|
1197
|
+
self.lower(1, "changed attributes known only at run time (an INSERT when the instance is new)")
|
|
1198
|
+
if m.timestamps:
|
|
1199
|
+
sets.append(f"{self.q(m.column(m.updated_at))} = {mark('now')}")
|
|
1200
|
+
out.append(f"UPDATE {self.q(m.table)} SET {', '.join(sets)} WHERE {self.by_pk()}")
|
|
1201
|
+
elif method == "update":
|
|
1202
|
+
cols, vals = self.values(args[0] if args else None)
|
|
1203
|
+
self.stamp(cols, vals, created=False)
|
|
1204
|
+
out.append(f"UPDATE {self.q(m.table)} SET {', '.join(f'{c} = {v}' for c, v in zip(cols, vals))} WHERE {self.by_pk()}")
|
|
1205
|
+
elif method == "destroy":
|
|
1206
|
+
opts = self.read(args[0]) if args else None
|
|
1207
|
+
out.append(self.destroy(opts, [self.by_pk()]))
|
|
1208
|
+
elif method == "reload":
|
|
1209
|
+
cols = [self.col(m, a, None) for a in m.columns] or ["*"]
|
|
1210
|
+
out.append(f"SELECT {', '.join(cols)} FROM {self.q(m.table)} WHERE {self.by_pk()} LIMIT 1")
|
|
1211
|
+
elif method in ("increment", "decrement"):
|
|
1212
|
+
out.append(self.incr(args[0] if args else None, args[1] if len(args) > 1 else None, [self.by_pk()]))
|
|
1213
|
+
elif method == "restore":
|
|
1214
|
+
if not m.paranoid:
|
|
1215
|
+
return []
|
|
1216
|
+
out.append(f"UPDATE {self.q(m.table)} SET {self.q(m.column(m.deleted_at))} = NULL WHERE {self.by_pk()}")
|
|
1217
|
+
return self.sites(out)
|
|
1218
|
+
if method in ("findAll", "findOne", "findAndCountAll", "aggregate"):
|
|
1219
|
+
if method == "aggregate":
|
|
1220
|
+
return []
|
|
1221
|
+
opts = self.opts(args[0] if args else None)
|
|
1222
|
+
if opts is False:
|
|
1223
|
+
return []
|
|
1224
|
+
if method == "findAndCountAll":
|
|
1225
|
+
count_sql = Call(self.lib, self.f, self.call, m, "count", args, self.sink, False, self.notes).select(
|
|
1226
|
+
opts, count="count(*) AS " + self.q("count"))
|
|
1227
|
+
out.append(count_sql)
|
|
1228
|
+
out.append(self.select(opts, limit1=method == "findOne"))
|
|
1229
|
+
out += self.separate
|
|
1230
|
+
elif method == "findByPk":
|
|
1231
|
+
if not args:
|
|
1232
|
+
return []
|
|
1233
|
+
opts = self.opts(args[1] if len(args) > 1 else None)
|
|
1234
|
+
if opts is False:
|
|
1235
|
+
return []
|
|
1236
|
+
out.append(self.select(opts, pk=args[0]))
|
|
1237
|
+
out += self.separate
|
|
1238
|
+
elif method in ("findOrCreate", "findOrBuild", "findCreateFind"):
|
|
1239
|
+
opts = self.opts(args[0] if args else None)
|
|
1240
|
+
if opts in (None, False):
|
|
1241
|
+
return []
|
|
1242
|
+
out.append(self.select(opts, limit1=True))
|
|
1243
|
+
if method != "findOrBuild":
|
|
1244
|
+
where = self.read(self.get(opts, "where"))
|
|
1245
|
+
defaults = self.read(self.get(opts, "defaults"))
|
|
1246
|
+
entries = (where[0] if where else []) + (defaults[0] if defaults else [])
|
|
1247
|
+
cols, vals = [], []
|
|
1248
|
+
for k, v in entries:
|
|
1249
|
+
if k.startswith("$") or o.is_undefined(v):
|
|
1250
|
+
continue
|
|
1251
|
+
c = self.q(m.column(k))
|
|
1252
|
+
if c not in cols:
|
|
1253
|
+
cols.append(c)
|
|
1254
|
+
vals.append(self.value(v))
|
|
1255
|
+
self.stamp(cols, vals, created=True)
|
|
1256
|
+
if cols:
|
|
1257
|
+
out.append(f"INSERT INTO {self.q(m.table)} ({', '.join(cols)}) VALUES ({', '.join(vals)})" +
|
|
1258
|
+
(" RETURNING *" if self.engine in ("postgres", "") else ""))
|
|
1259
|
+
elif method in ("count", "sum", "max", "min"):
|
|
1260
|
+
if method == "count":
|
|
1261
|
+
opts = self.opts(args[0] if args else None)
|
|
1262
|
+
if opts is False:
|
|
1263
|
+
return []
|
|
1264
|
+
distinct = opts is not None and _bool(self.get(opts, "distinct"))
|
|
1265
|
+
colnode = self.get(opts, "col") if opts is not None else None
|
|
1266
|
+
target = self.col(m, o.string_value(colnode), None) if colnode is not None and o.string_value(colnode) else "*"
|
|
1267
|
+
if distinct and target == "*":
|
|
1268
|
+
target = self.col(m, m.pk[0] if m.pk else "id", self.q(m.table))
|
|
1269
|
+
agg = f"count({'DISTINCT ' if distinct else ''}{target}) AS {self.q('count')}"
|
|
1270
|
+
else:
|
|
1271
|
+
if not args:
|
|
1272
|
+
return []
|
|
1273
|
+
field = o.string_value(args[0])
|
|
1274
|
+
opts = self.opts(args[1] if len(args) > 1 else None)
|
|
1275
|
+
if opts is False:
|
|
1276
|
+
return []
|
|
1277
|
+
agg = f"{method.upper()}({self.col(m, field, None) if field else mark_node(args[0])}) AS {self.q(method)}"
|
|
1278
|
+
out.append(self.select(opts, count=agg))
|
|
1279
|
+
elif method == "create":
|
|
1280
|
+
opts = self.opts(args[1] if len(args) > 1 else None)
|
|
1281
|
+
out.append(self.insert(args[0] if args else None, opts=opts or None))
|
|
1282
|
+
elif method == "bulkCreate":
|
|
1283
|
+
opts = self.opts(args[1] if len(args) > 1 else None)
|
|
1284
|
+
out.append(self.insert(args[0] if args else None, many=True, opts=opts or None))
|
|
1285
|
+
elif method == "upsert":
|
|
1286
|
+
if not args:
|
|
1287
|
+
return []
|
|
1288
|
+
cols, vals = self.values(args[0])
|
|
1289
|
+
self.stamp(cols, vals, created=True)
|
|
1290
|
+
sets = ", ".join(f"{c} = EXCLUDED.{c}" for c in cols if c != self.q(m.pk_column()))
|
|
1291
|
+
sql = f"INSERT INTO {self.q(m.table)} ({', '.join(cols)}) VALUES ({', '.join(vals)}) ON CONFLICT ({self.q(m.pk_column())}) "
|
|
1292
|
+
sql += f"DO UPDATE SET {sets}" if sets else "DO NOTHING"
|
|
1293
|
+
if self.engine in ("postgres", ""):
|
|
1294
|
+
sql += " RETURNING *"
|
|
1295
|
+
out.append(sql)
|
|
1296
|
+
elif method == "update":
|
|
1297
|
+
if len(args) < 2:
|
|
1298
|
+
return []
|
|
1299
|
+
opts = self.opts(args[1])
|
|
1300
|
+
if opts in (None, False):
|
|
1301
|
+
return []
|
|
1302
|
+
out.append(self.update(args[0], opts))
|
|
1303
|
+
elif method == "destroy":
|
|
1304
|
+
opts = self.opts(args[0] if args else None)
|
|
1305
|
+
if opts is False:
|
|
1306
|
+
return []
|
|
1307
|
+
out.append(self.destroy(opts))
|
|
1308
|
+
elif method in ("increment", "decrement"):
|
|
1309
|
+
opts = self.opts(args[1] if len(args) > 1 else None)
|
|
1310
|
+
if opts in (None, False):
|
|
1311
|
+
return []
|
|
1312
|
+
preds = self.where(self.get(opts, "where"), m, None)
|
|
1313
|
+
out.append(self.incr(args[0] if args else None, args[1], preds))
|
|
1314
|
+
elif method == "restore":
|
|
1315
|
+
if not m.paranoid:
|
|
1316
|
+
return []
|
|
1317
|
+
opts = self.opts(args[0] if args else None)
|
|
1318
|
+
if opts is False:
|
|
1319
|
+
return []
|
|
1320
|
+
preds = self.where(self.get(opts, "where"), m, None) if opts is not None else []
|
|
1321
|
+
out.append(f"UPDATE {self.q(m.table)} SET {self.q(m.column(m.deleted_at))} = NULL" + (" WHERE " + " AND ".join(preds) if preds else ""))
|
|
1322
|
+
elif method == "truncate":
|
|
1323
|
+
out.append(f"TRUNCATE {self.q(m.table)}")
|
|
1324
|
+
return self.sites(out)
|
|
1325
|
+
|
|
1326
|
+
def opts(self, node: Node | None):
|
|
1327
|
+
"""The options object; None when there is none, False when one is given but cannot be read."""
|
|
1328
|
+
node = unwrap(node)
|
|
1329
|
+
if node is None or o.is_undefined(node):
|
|
1330
|
+
return None
|
|
1331
|
+
got = self.read(node)
|
|
1332
|
+
if got is None:
|
|
1333
|
+
self.lower(0, "options object built at run time")
|
|
1334
|
+
return ([], [txt(node)])
|
|
1335
|
+
return got
|
|
1336
|
+
|
|
1337
|
+
def incr(self, fields: Node | None, by_opts: Node | None, preds: list[str]) -> str:
|
|
1338
|
+
m = self.m
|
|
1339
|
+
sign = "+" if self.method == "increment" else "-"
|
|
1340
|
+
by = "1"
|
|
1341
|
+
opts = self.read(by_opts) if by_opts is not None else None
|
|
1342
|
+
if opts is not None and self.get(opts, "by") is not None:
|
|
1343
|
+
by = self.value(self.get(opts, "by"))
|
|
1344
|
+
sets = []
|
|
1345
|
+
s = o.string_value(fields)
|
|
1346
|
+
items = o.array_items(fields)
|
|
1347
|
+
obj = self.read(fields) if s is None and items is None else None
|
|
1348
|
+
if s is not None:
|
|
1349
|
+
sets = [f"{self.q(m.column(s))} = {self.q(m.column(s))} {sign} {by}"]
|
|
1350
|
+
elif items is not None:
|
|
1351
|
+
sets = [f"{self.q(m.column(o.string_value(i)))} = {self.q(m.column(o.string_value(i)))} {sign} {by}" for i in items if o.string_value(i)]
|
|
1352
|
+
elif obj is not None:
|
|
1353
|
+
sets = [f"{self.q(m.column(k))} = {self.q(m.column(k))} {sign} {self.value(v)}" for k, v in obj[0]]
|
|
1354
|
+
if not sets:
|
|
1355
|
+
sets = [f"{mark(txt(fields))} = {mark(txt(fields))} {sign} {by}"]
|
|
1356
|
+
if m.timestamps:
|
|
1357
|
+
sets.append(f"{self.q(m.column(m.updated_at))} = {mark('now')}")
|
|
1358
|
+
sql = f"UPDATE {self.q(m.table)} SET {', '.join(sets)}"
|
|
1359
|
+
if preds:
|
|
1360
|
+
sql += " WHERE " + " AND ".join(preds)
|
|
1361
|
+
return sql
|
|
1362
|
+
|
|
1363
|
+
def assigned(self) -> list[str]:
|
|
1364
|
+
"""`doc.title = x` before `doc.save()` in the same function: the attributes the save writes."""
|
|
1365
|
+
recv = unwrap(unwrap(self.call.child_by_field_name("function")).child_by_field_name("object"))
|
|
1366
|
+
name = "this" if recv is not None and recv.type == "this" else txt(recv)
|
|
1367
|
+
func = next(iter(self.f._scopes(self.call)), None)
|
|
1368
|
+
if func is None:
|
|
1369
|
+
return []
|
|
1370
|
+
out = []
|
|
1371
|
+
stack = [func]
|
|
1372
|
+
budget = o.SETTINGS["orm_max_chain_statements"] * 50
|
|
1373
|
+
while stack and budget > 0:
|
|
1374
|
+
n = stack.pop()
|
|
1375
|
+
budget -= 1
|
|
1376
|
+
if n.start_byte > self.call.start_byte:
|
|
1377
|
+
continue
|
|
1378
|
+
if n.type == "assignment_expression":
|
|
1379
|
+
left = n.child_by_field_name("left")
|
|
1380
|
+
if left is not None and left.type == "member_expression" and txt(left.child_by_field_name("object")) == name:
|
|
1381
|
+
prop = txt(left.child_by_field_name("property"))
|
|
1382
|
+
if prop in self.m.columns:
|
|
1383
|
+
out.append((n.start_byte, prop))
|
|
1384
|
+
if n is not func and n.type in o.FUNC_TYPES:
|
|
1385
|
+
continue
|
|
1386
|
+
stack.extend(n.children)
|
|
1387
|
+
return [p for _b, p in sorted(out)]
|
|
1388
|
+
|
|
1389
|
+
def sites(self, statements: list[str]) -> list:
|
|
1390
|
+
if self.method in ("findOne", "findAll") and any("hasMany" == a["kind"] for a in self.m.assocs.values()) and self.joins and \
|
|
1391
|
+
re.search(r" LIMIT ", statements[-1] if statements else ""):
|
|
1392
|
+
self.lower(1, "LIMIT with an included association: Sequelize moves the base table into a subquery")
|
|
1393
|
+
confidence = o.CONFIDENCE[self.level]
|
|
1394
|
+
out = []
|
|
1395
|
+
expr = self.args[0] if self.args else None
|
|
1396
|
+
for sql in statements:
|
|
1397
|
+
site = o.make_site(self.f, self.call, self.sink, self.engine, sql, expr, library=NAME, table=self.m.table,
|
|
1398
|
+
operation=self.method, confidence=confidence, notes=self.notes)
|
|
1399
|
+
site.orm["mechanism"] = "orm_api_in_loop" if site.in_loop else MECHANISM
|
|
1400
|
+
out.append(site)
|
|
1401
|
+
return out
|