@gate-forge/pack-sqlalchemy 0.7.1 → 0.9.0
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.
- package/README.md +98 -5
- package/dist/detector.d.ts +19 -2
- package/dist/detector.d.ts.map +1 -1
- package/dist/detector.js +42 -9
- package/dist/detector.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/singleton.d.ts +103 -0
- package/dist/singleton.d.ts.map +1 -0
- package/dist/singleton.js +146 -0
- package/dist/singleton.js.map +1 -0
- package/dist/tenancy.d.ts +18 -0
- package/dist/tenancy.d.ts.map +1 -0
- package/dist/tenancy.js +93 -0
- package/dist/tenancy.js.map +1 -0
- package/dist/test-paths.d.ts +40 -0
- package/dist/test-paths.d.ts.map +1 -0
- package/dist/test-paths.js +49 -0
- package/dist/test-paths.js.map +1 -0
- package/package.json +7 -4
- package/python/gateforge_sqlalchemy_detector/__init__.py +12 -2
- package/python/gateforge_sqlalchemy_detector/scan.py +343 -30
- package/python/gateforge_sqlalchemy_detector/__pycache__/__init__.cpython-314.pyc +0 -0
- package/python/gateforge_sqlalchemy_detector/__pycache__/__main__.cpython-314.pyc +0 -0
- package/python/gateforge_sqlalchemy_detector/__pycache__/scan.cpython-314.pyc +0 -0
|
@@ -102,6 +102,21 @@ UPDATEABLE_FIELDS_ATTR = "__gateforge_updateable_fields__"
|
|
|
102
102
|
# Column-call constructors carrying column facts.
|
|
103
103
|
COLUMN_CALL_NAMES = ("Column", "mapped_column")
|
|
104
104
|
|
|
105
|
+
# SQLModel declares tables with the class keyword ``table=True`` on a
|
|
106
|
+
# class deriving from ``SQLModel`` — no declarative base, no
|
|
107
|
+
# ``__tablename__``. SQLModel derives the table name at runtime by
|
|
108
|
+
# lowercasing the class name, which the AST CAN see, so the name is a
|
|
109
|
+
# fact (``sqlmodel-class-name`` provenance), not a guess. The root is
|
|
110
|
+
# recognized by import provenance (``from sqlmodel import SQLModel``,
|
|
111
|
+
# including aliases) or the exact conventional name ``SQLModel``; a
|
|
112
|
+
# denylisted provenance (Pydantic's ``BaseModel`` family) never matches.
|
|
113
|
+
SQLMODEL_MODULES = ("sqlmodel",)
|
|
114
|
+
SQLMODEL_ROOT_NAME = "SQLModel"
|
|
115
|
+
|
|
116
|
+
# Tablename provenance label for a name SQLModel derives at runtime from
|
|
117
|
+
# the class name.
|
|
118
|
+
SQLMODEL_CLASS_NAME_PROVENANCE = "sqlmodel-class-name"
|
|
119
|
+
|
|
105
120
|
# Import provenance that can NEVER make a base name a declarative root
|
|
106
121
|
# (phase 2 denylist). The conventional-name rule ("Base") is a flat-file
|
|
107
122
|
# heuristic: most projects do ``from app.db import Base`` (cross-file,
|
|
@@ -132,6 +147,34 @@ SOFT_DELETE_CANDIDATE_FIELDS = (
|
|
|
132
147
|
"is_deleted",
|
|
133
148
|
)
|
|
134
149
|
|
|
150
|
+
# Directory segments that mark test fixture surface (exact segment match,
|
|
151
|
+
# case-insensitive). Files under such a directory are parsed and reported
|
|
152
|
+
# in ``scannedPaths`` — the coverage evidence stays honest — but they never
|
|
153
|
+
# reach the resource graph: a fixture table is not business surface, and a
|
|
154
|
+
# fixture that re-declares a real table's name used to collide with it and
|
|
155
|
+
# leave the REAL resource plane-unresolved. This mirrors
|
|
156
|
+
# ``packages/pack-sqlalchemy/src/test-paths.ts`` exactly (the TypeScript
|
|
157
|
+
# side applies the same rule to plane proposals and route folders); both
|
|
158
|
+
# must stay in step, which ``test/test-directory-models.test.ts`` pins.
|
|
159
|
+
TEST_PATH_SEGMENTS = ("tests", "test")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _is_test_path(relpath: str) -> bool:
|
|
163
|
+
"""Whether a repo-relative path is test fixture surface.
|
|
164
|
+
|
|
165
|
+
Only DIRECTORY segments decide, so ``models/test_accounts.py`` is not
|
|
166
|
+
test surface while ``tests/models.py`` is, and ``contest/`` is not
|
|
167
|
+
``test``.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
relpath: Repo-root-relative posix path.
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
bool: True when any directory segment is ``test``/``tests``.
|
|
174
|
+
"""
|
|
175
|
+
segments = relpath.replace("\\", "/").split("/")[:-1]
|
|
176
|
+
return any(segment.lower() in TEST_PATH_SEGMENTS for segment in segments)
|
|
177
|
+
|
|
135
178
|
|
|
136
179
|
def expr_label(node: ast.expr) -> str:
|
|
137
180
|
"""Classify a non-literal expression deterministically for UNRESOLVED reasons.
|
|
@@ -244,6 +287,28 @@ class ColumnFacts:
|
|
|
244
287
|
self.foreign_keys: dict[str, str] = {}
|
|
245
288
|
#: Sorted column names resembling soft-delete bookkeeping.
|
|
246
289
|
self.soft_delete_candidates: list[str] = []
|
|
290
|
+
#: Every literal column name, in written order (deduplicated).
|
|
291
|
+
self.column_names: list[str] = []
|
|
292
|
+
#: Declared UNIQUE constraints/indexes in written order, as
|
|
293
|
+
#: ``{"name": str | None, "kind": "constraint"|"index"|"column",
|
|
294
|
+
#: "columns": [...]}``. Literal evidence only — a computed column
|
|
295
|
+
#: expression is never guessed.
|
|
296
|
+
self.unique_constraints: list[dict] = []
|
|
297
|
+
|
|
298
|
+
def add_unique(self, name: str | None, kind: str, columns: list[str]) -> None:
|
|
299
|
+
"""Records one declared UNIQUE constraint/index, deduplicated.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
name: The declared constraint/index name, or None when unnamed.
|
|
303
|
+
kind: ``constraint`` (UniqueConstraint), ``index`` (a unique
|
|
304
|
+
Index), or ``column`` (a column declared ``unique=True``).
|
|
305
|
+
columns: The unique columns, written order.
|
|
306
|
+
"""
|
|
307
|
+
if not columns:
|
|
308
|
+
return
|
|
309
|
+
fact = {"name": name, "kind": kind, "columns": list(columns)}
|
|
310
|
+
if fact not in self.unique_constraints:
|
|
311
|
+
self.unique_constraints.append(fact)
|
|
247
312
|
|
|
248
313
|
@property
|
|
249
314
|
def has_pk_evidence(self) -> bool:
|
|
@@ -270,8 +335,16 @@ def _literal_kwarg_true(call: ast.Call, name: str) -> bool | None:
|
|
|
270
335
|
return None
|
|
271
336
|
|
|
272
337
|
|
|
338
|
+
|
|
339
|
+
|
|
273
340
|
def _column_call_name(call: ast.expr) -> str | None:
|
|
274
|
-
"""Simple name of a call, when it is a column constructor.
|
|
341
|
+
"""Simple name of a call, when it is a plain column constructor.
|
|
342
|
+
|
|
343
|
+
The unqualified SQLAlchemy constructors only. SQLModel's ``Field`` is
|
|
344
|
+
recognized per class in `ClassRecord._column_call_name`, which can see
|
|
345
|
+
the import provenance; it never appears in ``__table_args__`` or in a
|
|
346
|
+
``Table(...)`` argument list.
|
|
347
|
+
"""
|
|
275
348
|
name = call_name(call.func) if isinstance(call, ast.Call) else None
|
|
276
349
|
return name if name in COLUMN_CALL_NAMES else None
|
|
277
350
|
|
|
@@ -292,7 +365,13 @@ def _column_name(call: ast.Call, target: str | None) -> str | None:
|
|
|
292
365
|
|
|
293
366
|
|
|
294
367
|
def _foreign_key_reference(call: ast.Call) -> str | None:
|
|
295
|
-
"""Finds a literal ``ForeignKey("
|
|
368
|
+
"""Finds a literal foreign-key target, by ``ForeignKey("t.c")`` or by string.
|
|
369
|
+
|
|
370
|
+
SQLModel spells the target as a literal string instead of a call:
|
|
371
|
+
``hero_id: int | None = Field(foreign_key="hero.id")``. A declarative
|
|
372
|
+
``Column`` never takes that keyword, so reading it changes nothing for
|
|
373
|
+
the existing styles.
|
|
374
|
+
"""
|
|
296
375
|
for arg in call.args:
|
|
297
376
|
if (
|
|
298
377
|
isinstance(arg, ast.Call)
|
|
@@ -311,6 +390,13 @@ def _foreign_key_reference(call: ast.Call) -> str | None:
|
|
|
311
390
|
and isinstance(kw.value.args[0].value, str)
|
|
312
391
|
):
|
|
313
392
|
return kw.value.args[0].value
|
|
393
|
+
for kw in call.keywords:
|
|
394
|
+
if (
|
|
395
|
+
kw.arg == "foreign_key"
|
|
396
|
+
and isinstance(kw.value, ast.Constant)
|
|
397
|
+
and isinstance(kw.value.value, str)
|
|
398
|
+
):
|
|
399
|
+
return kw.value.value
|
|
314
400
|
return None
|
|
315
401
|
|
|
316
402
|
|
|
@@ -336,6 +422,10 @@ def _record_column(facts: ColumnFacts, call: ast.Call, target: str | None) -> No
|
|
|
336
422
|
facts.foreign_keys[column_name] = reference
|
|
337
423
|
if column_name in SOFT_DELETE_CANDIDATE_FIELDS:
|
|
338
424
|
facts.soft_delete_candidates.append(column_name)
|
|
425
|
+
if column_name not in facts.column_names:
|
|
426
|
+
facts.column_names.append(column_name)
|
|
427
|
+
if _literal_kwarg_true(call, "unique") is True:
|
|
428
|
+
facts.add_unique(None, "column", [column_name])
|
|
339
429
|
|
|
340
430
|
|
|
341
431
|
def _facts_from_column_calls(calls: list[tuple[ast.Call, str | None]]) -> ColumnFacts:
|
|
@@ -368,13 +458,75 @@ def _pk_constraint_columns(node: ast.expr) -> list[str] | None:
|
|
|
368
458
|
return None
|
|
369
459
|
|
|
370
460
|
|
|
461
|
+
def _literal_string_args(args: list[ast.expr]) -> list[str] | None:
|
|
462
|
+
"""Every argument as a non-empty literal string, or None."""
|
|
463
|
+
if not args or not all(
|
|
464
|
+
isinstance(a, ast.Constant) and isinstance(a.value, str) and a.value for a in args
|
|
465
|
+
):
|
|
466
|
+
return None
|
|
467
|
+
return [a.value for a in args if isinstance(a, ast.Constant)]
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def _unique_constraint(node: ast.expr) -> dict | None:
|
|
471
|
+
"""One declared UNIQUE constraint or UNIQUE index of a table.
|
|
472
|
+
|
|
473
|
+
``UniqueConstraint("a", "b")`` (name via the ``name=`` keyword) and
|
|
474
|
+
``Index("ix", "a", "b", unique=True)`` (name = the first argument)
|
|
475
|
+
say the same thing about uniqueness. Literal columns only: a computed
|
|
476
|
+
expression or a non-literal ``unique`` flag yields None (the hole is
|
|
477
|
+
never filled with a guess).
|
|
478
|
+
|
|
479
|
+
Args:
|
|
480
|
+
node: An ``__table_args__`` tuple element.
|
|
481
|
+
|
|
482
|
+
Returns:
|
|
483
|
+
dict | None: ``{"name", "kind", "columns"}``, or None.
|
|
484
|
+
"""
|
|
485
|
+
if not isinstance(node, ast.Call):
|
|
486
|
+
return None
|
|
487
|
+
called = call_name(node.func)
|
|
488
|
+
if called == "UniqueConstraint":
|
|
489
|
+
columns = _literal_string_args(node.args)
|
|
490
|
+
if columns is None:
|
|
491
|
+
return None
|
|
492
|
+
name = _literal_string_keyword(node, "name")
|
|
493
|
+
return {"name": name, "kind": "constraint", "columns": columns}
|
|
494
|
+
if called == "Index" and _literal_kwarg_true(node, "unique") is True:
|
|
495
|
+
columns = _literal_string_args(node.args)
|
|
496
|
+
if columns is None:
|
|
497
|
+
return None
|
|
498
|
+
# An Index's first argument is its name, not a column.
|
|
499
|
+
name = node.args[0].value
|
|
500
|
+
return {"name": name, "kind": "index", "columns": columns[1:]}
|
|
501
|
+
return None
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _literal_string_keyword(call: ast.Call, name: str) -> str | None:
|
|
505
|
+
"""A literal string keyword value, or None (absent or computed)."""
|
|
506
|
+
for kw in call.keywords:
|
|
507
|
+
if kw.arg == name and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
|
|
508
|
+
return kw.value.value
|
|
509
|
+
return None
|
|
510
|
+
|
|
511
|
+
|
|
371
512
|
class ClassRecord:
|
|
372
513
|
"""AST facts about one class definition, at any lexical scope."""
|
|
373
514
|
|
|
374
|
-
def __init__(
|
|
515
|
+
def __init__(
|
|
516
|
+
self,
|
|
517
|
+
qname: str,
|
|
518
|
+
node: ast.ClassDef,
|
|
519
|
+
scope: str,
|
|
520
|
+
imports: "dict[str, ImportRef] | None" = None,
|
|
521
|
+
):
|
|
375
522
|
self.qname = qname
|
|
376
523
|
self.node = node
|
|
377
524
|
self.scope = scope # "" at module level, enclosing dotted scope otherwise
|
|
525
|
+
# Import bindings of the OWNING file (complete before any class is
|
|
526
|
+
# recorded): the only provenance evidence for a SQLModel ``Field``
|
|
527
|
+
# column, whose spelling alone proves nothing (dataclasses and
|
|
528
|
+
# SQLAlchemy itself export one).
|
|
529
|
+
self.imports: dict[str, ImportRef] = imports if imports is not None else {}
|
|
378
530
|
self.bases: list[str] = [b for b in (base_name(b) for b in node.bases) if b is not None]
|
|
379
531
|
self.keywords = {kw.arg: kw.value for kw in node.keywords if kw.arg}
|
|
380
532
|
self.tablename_literal: str | None = None
|
|
@@ -404,7 +556,11 @@ class ClassRecord:
|
|
|
404
556
|
)
|
|
405
557
|
names = [t.id for t in targets if isinstance(t, ast.Name)]
|
|
406
558
|
value = stmt.value
|
|
407
|
-
if
|
|
559
|
+
if (
|
|
560
|
+
value is not None
|
|
561
|
+
and isinstance(value, ast.Call)
|
|
562
|
+
and self._column_call_name(value) is not None
|
|
563
|
+
):
|
|
408
564
|
for name in names:
|
|
409
565
|
column_calls.append((value, name))
|
|
410
566
|
if TABULAR_ATTR in names and self.tablename_expr is None:
|
|
@@ -453,6 +609,64 @@ class ClassRecord:
|
|
|
453
609
|
if constraint is not None:
|
|
454
610
|
self.column_facts.primary_key_columns = constraint
|
|
455
611
|
self.column_facts.has_pk_constraint = True
|
|
612
|
+
unique = _unique_constraint(element)
|
|
613
|
+
if unique is not None:
|
|
614
|
+
self.column_facts.add_unique(unique["name"], unique["kind"], unique["columns"])
|
|
615
|
+
|
|
616
|
+
def _column_call_name(self, call: ast.expr) -> str | None:
|
|
617
|
+
"""Whether a call is a column constructor, honoring SQLModel Field().
|
|
618
|
+
|
|
619
|
+
``Column``/``mapped_column`` are unqualified column constructors.
|
|
620
|
+
``Field`` is not: ``dataclasses`` and SQLAlchemy export one too, so
|
|
621
|
+
it counts only when this file imports it from ``sqlmodel`` (the
|
|
622
|
+
SQLModel table style). Facts attach only to emitted tables, so the
|
|
623
|
+
gate never sees a column from a non-model class.
|
|
624
|
+
|
|
625
|
+
Args:
|
|
626
|
+
call: The candidate call expression.
|
|
627
|
+
|
|
628
|
+
Returns:
|
|
629
|
+
str | None: The simple constructor name, or None.
|
|
630
|
+
"""
|
|
631
|
+
if not isinstance(call, ast.Call):
|
|
632
|
+
return None
|
|
633
|
+
name = call_name(call.func)
|
|
634
|
+
if name is None:
|
|
635
|
+
return None
|
|
636
|
+
if name in COLUMN_CALL_NAMES:
|
|
637
|
+
return name
|
|
638
|
+
if name == "Field":
|
|
639
|
+
ref = self.imports.get(name)
|
|
640
|
+
provenance = ref.module.split(".")[0] if ref is not None else None
|
|
641
|
+
return name if provenance in SQLMODEL_MODULES else None
|
|
642
|
+
return None
|
|
643
|
+
|
|
644
|
+
@property
|
|
645
|
+
def table_keyword_true(self) -> bool:
|
|
646
|
+
"""Whether the class keyword ``table=True`` is literally present.
|
|
647
|
+
|
|
648
|
+
Only the literal True marks a SQLModel table; ``table=False`` (and
|
|
649
|
+
a computed value) marks a class that is NOT one, and guessing True
|
|
650
|
+
there would invent tables.
|
|
651
|
+
"""
|
|
652
|
+
value = self.keywords.get("table")
|
|
653
|
+
return isinstance(value, ast.Constant) and value.value is True
|
|
654
|
+
|
|
655
|
+
def is_sqlmodel_table(self, idx: "FileIndex", sqlmodel_names: frozenset[str]) -> bool:
|
|
656
|
+
"""Whether this class is a SQLModel table (``table=True`` on a SQLModel base).
|
|
657
|
+
|
|
658
|
+
Args:
|
|
659
|
+
idx: The owning file index (import provenance).
|
|
660
|
+
sqlmodel_names: Simple names of classes derived from SQLModel
|
|
661
|
+
across ALL scanned files (the SQLModel closure `scan`
|
|
662
|
+
computes before emission, e.g. a shared ``UserBase``).
|
|
663
|
+
|
|
664
|
+
Returns:
|
|
665
|
+
bool: True only for ``class X(<SQLModel base>, table=True)``.
|
|
666
|
+
"""
|
|
667
|
+
if not self.table_keyword_true:
|
|
668
|
+
return False
|
|
669
|
+
return any(idx.base_is_sqlmodel(base, sqlmodel_names) for base in self.bases)
|
|
456
670
|
|
|
457
671
|
# -- Classification ----------------------------------------------------
|
|
458
672
|
|
|
@@ -492,7 +706,7 @@ class ClassRecord:
|
|
|
492
706
|
self.tablename_literal is not None
|
|
493
707
|
or self.tablename_expr is not None
|
|
494
708
|
or self.tablename_func is not None
|
|
495
|
-
or
|
|
709
|
+
or self.table_keyword_true
|
|
496
710
|
)
|
|
497
711
|
if has_facts:
|
|
498
712
|
return True
|
|
@@ -523,16 +737,18 @@ def _literal_record(node: ast.expr) -> dict[str, str | int | float | bool] | Non
|
|
|
523
737
|
|
|
524
738
|
|
|
525
739
|
def _string_sequence_literal(node: ast.expr) -> list[str] | None:
|
|
526
|
-
"""Reads
|
|
740
|
+
"""Reads list/tuple literals of distinct non-empty strings.
|
|
741
|
+
|
|
742
|
+
Empty list/tuple literals are valid.
|
|
527
743
|
|
|
528
744
|
Args:
|
|
529
745
|
node: The AST expression (e.g. the value of
|
|
530
746
|
``__gateforge_updateable_fields__``).
|
|
531
747
|
|
|
532
748
|
Returns:
|
|
533
|
-
list[str] | None:
|
|
534
|
-
|
|
535
|
-
|
|
749
|
+
list[str] | None: string values in written order, including an
|
|
750
|
+
empty list for an empty literal, or None when the node is not
|
|
751
|
+
a list/tuple of string literals.
|
|
536
752
|
"""
|
|
537
753
|
if not isinstance(node, (ast.List, ast.Tuple)):
|
|
538
754
|
return None
|
|
@@ -541,7 +757,7 @@ def _string_sequence_literal(node: ast.expr) -> list[str] | None:
|
|
|
541
757
|
if not (isinstance(elt, ast.Constant) and isinstance(elt.value, str) and elt.value):
|
|
542
758
|
return None
|
|
543
759
|
values.append(elt.value)
|
|
544
|
-
return values
|
|
760
|
+
return values
|
|
545
761
|
|
|
546
762
|
|
|
547
763
|
def _table_args_elements(node: ast.expr | None) -> list[ast.expr]:
|
|
@@ -763,6 +979,32 @@ class FileIndex:
|
|
|
763
979
|
return True
|
|
764
980
|
return name in model_names
|
|
765
981
|
|
|
982
|
+
def base_is_sqlmodel(self, name: str, sqlmodel_names: frozenset[str]) -> bool:
|
|
983
|
+
"""Whether one base simple name makes its class a SQLModel class.
|
|
984
|
+
|
|
985
|
+
The same fail-closed shape as `base_is_declarative`: a denylisted
|
|
986
|
+
provenance or a locally defined namesake vetoes the SQLModel
|
|
987
|
+
reading; otherwise the name is a SQLModel root when it is imported
|
|
988
|
+
from ``sqlmodel`` (alias-aware — ``from sqlmodel import SQLModel as
|
|
989
|
+
Model``), is the exact conventional name ``SQLModel``, or belongs
|
|
990
|
+
to the cross-file SQLModel closure.
|
|
991
|
+
|
|
992
|
+
Args:
|
|
993
|
+
name: The base's simple name.
|
|
994
|
+
sqlmodel_names: Simple names of SQLModel-derived classes so far.
|
|
995
|
+
|
|
996
|
+
Returns:
|
|
997
|
+
bool: True only when the base derives from ``SQLModel``.
|
|
998
|
+
"""
|
|
999
|
+
if self._import_denied(name) or name in self.locally_denied_base_names:
|
|
1000
|
+
return False
|
|
1001
|
+
ref = self.imports.get(name)
|
|
1002
|
+
if ref is not None and ref.name == SQLMODEL_ROOT_NAME:
|
|
1003
|
+
return ref.module.split(".")[0] in SQLMODEL_MODULES
|
|
1004
|
+
if name == SQLMODEL_ROOT_NAME:
|
|
1005
|
+
return True
|
|
1006
|
+
return name in sqlmodel_names
|
|
1007
|
+
|
|
766
1008
|
@staticmethod
|
|
767
1009
|
def _literal_name_arg(call: ast.Call) -> bool:
|
|
768
1010
|
return bool(call.args) and isinstance(call.args[0], ast.Constant) and isinstance(
|
|
@@ -776,7 +1018,9 @@ class FileIndex:
|
|
|
776
1018
|
visit(child, stack + [child.name])
|
|
777
1019
|
elif isinstance(child, ast.ClassDef):
|
|
778
1020
|
qname = ".".join(stack + [child.name])
|
|
779
|
-
self.classes.append(
|
|
1021
|
+
self.classes.append(
|
|
1022
|
+
ClassRecord(qname, child, ".".join(stack), self.imports)
|
|
1023
|
+
)
|
|
780
1024
|
visit(child, stack + [child.name])
|
|
781
1025
|
else:
|
|
782
1026
|
visit(child, stack)
|
|
@@ -817,7 +1061,9 @@ def loc(relpath: str, node: ast.AST) -> dict:
|
|
|
817
1061
|
return {"file": relpath, "line": node.lineno, "col": node.col_offset}
|
|
818
1062
|
|
|
819
1063
|
|
|
820
|
-
def _symbol_resource(
|
|
1064
|
+
def _symbol_resource(
|
|
1065
|
+
relpath: str, rec: ClassRecord, name_unresolved: bool, table_name: str | None = None
|
|
1066
|
+
) -> dict:
|
|
821
1067
|
"""The graph class-symbol resource for one declarative class.
|
|
822
1068
|
|
|
823
1069
|
Args:
|
|
@@ -826,6 +1072,8 @@ def _symbol_resource(relpath: str, rec: ClassRecord, name_unresolved: bool) -> d
|
|
|
826
1072
|
name_unresolved: Detector assertion that this class's tablename is
|
|
827
1073
|
unresolved (true for table candidates the detector cannot name;
|
|
828
1074
|
false for pure bases and literal-named classes).
|
|
1075
|
+
table_name: The resolved table name when the detector has one
|
|
1076
|
+
(a declared literal, or the name SQLModel derives at runtime).
|
|
829
1077
|
|
|
830
1078
|
Returns:
|
|
831
1079
|
dict: A ``gateforge.class`` resource consumed by the symbol table.
|
|
@@ -838,8 +1086,10 @@ def _symbol_resource(relpath: str, rec: ClassRecord, name_unresolved: bool) -> d
|
|
|
838
1086
|
}
|
|
839
1087
|
if rec.bases:
|
|
840
1088
|
attrs["baseNames"] = list(rec.bases)
|
|
841
|
-
if
|
|
842
|
-
|
|
1089
|
+
if table_name is None:
|
|
1090
|
+
table_name = rec.tablename_literal
|
|
1091
|
+
if table_name is not None:
|
|
1092
|
+
attrs["tableName"] = table_name
|
|
843
1093
|
return {
|
|
844
1094
|
"schemaVersion": 1,
|
|
845
1095
|
"id": f"sqlalchemy.class:{relpath}:{rec.qname}",
|
|
@@ -851,17 +1101,24 @@ def _symbol_resource(relpath: str, rec: ClassRecord, name_unresolved: bool) -> d
|
|
|
851
1101
|
}
|
|
852
1102
|
|
|
853
1103
|
|
|
854
|
-
def _table_resource(
|
|
855
|
-
|
|
1104
|
+
def _table_resource(
|
|
1105
|
+
relpath: str, rec: ClassRecord, provenance: str, table_name: str | None = None
|
|
1106
|
+
) -> dict:
|
|
1107
|
+
"""The business table resource for a class with a resolved tablename.
|
|
856
1108
|
|
|
857
1109
|
Args:
|
|
858
1110
|
relpath: Repo-root-relative source path.
|
|
859
1111
|
rec: The class record.
|
|
860
|
-
provenance: Tablename provenance label
|
|
1112
|
+
provenance: Tablename provenance label: ``literal`` for a declared
|
|
1113
|
+
``__tablename__``, ``sqlmodel-class-name`` for the name
|
|
1114
|
+
SQLModel derives from the class name.
|
|
1115
|
+
table_name: The resolved name (defaults to the declared literal).
|
|
861
1116
|
|
|
862
1117
|
Returns:
|
|
863
1118
|
dict: A ``sqlalchemy.table`` resource.
|
|
864
1119
|
"""
|
|
1120
|
+
if table_name is None:
|
|
1121
|
+
table_name = rec.tablename_literal
|
|
865
1122
|
return {
|
|
866
1123
|
"schemaVersion": 1,
|
|
867
1124
|
"id": f"sqlalchemy.table:{relpath}:{rec.qname}",
|
|
@@ -870,14 +1127,14 @@ def _table_resource(relpath: str, rec: ClassRecord, provenance: str) -> dict:
|
|
|
870
1127
|
"location": loc(relpath, rec.node),
|
|
871
1128
|
"detectorVersion": VERSION,
|
|
872
1129
|
"attributes": {
|
|
873
|
-
"resourceName":
|
|
1130
|
+
"resourceName": table_name,
|
|
874
1131
|
"classQname": rec.qname,
|
|
875
1132
|
"scope": rec.scope or "module",
|
|
876
|
-
"tableName":
|
|
1133
|
+
"tableName": table_name,
|
|
877
1134
|
"tablenameProvenance": provenance,
|
|
878
1135
|
"hasTableArgs": rec.has_table_args,
|
|
879
1136
|
"tableArgsSchema": rec.table_args_schema,
|
|
880
|
-
"tableKeywordTrue":
|
|
1137
|
+
"tableKeywordTrue": rec.table_keyword_true,
|
|
881
1138
|
"abstract": False,
|
|
882
1139
|
"baseNames": list(rec.bases),
|
|
883
1140
|
**_attribute_facts(rec.column_facts, rec),
|
|
@@ -1048,11 +1305,14 @@ def _attribute_facts(facts: ColumnFacts, rec: ClassRecord | None) -> dict:
|
|
|
1048
1305
|
rec: The class record (None for Table() calls).
|
|
1049
1306
|
|
|
1050
1307
|
Returns:
|
|
1051
|
-
dict: Attribute entries (only when non-empty):
|
|
1308
|
+
dict: Attribute entries (only when non-empty): `columnNames`
|
|
1309
|
+
(every literal column, written order), ordered
|
|
1052
1310
|
`primaryKeyColumns`, `foreignKeyReferences` (sorted by
|
|
1053
1311
|
column), `softDeleteCandidateFields`, and `readOnly`.
|
|
1054
1312
|
"""
|
|
1055
1313
|
entries: dict = {}
|
|
1314
|
+
if facts.column_names:
|
|
1315
|
+
entries["columnNames"] = list(facts.column_names)
|
|
1056
1316
|
if facts.has_pk_evidence:
|
|
1057
1317
|
entries["primaryKeyColumns"] = list(facts.primary_key_columns)
|
|
1058
1318
|
if facts.foreign_keys:
|
|
@@ -1062,9 +1322,14 @@ def _attribute_facts(facts: ColumnFacts, rec: ClassRecord | None) -> dict:
|
|
|
1062
1322
|
]
|
|
1063
1323
|
if facts.soft_delete_candidates:
|
|
1064
1324
|
entries["softDeleteCandidateFields"] = sorted(set(facts.soft_delete_candidates))
|
|
1325
|
+
if facts.unique_constraints:
|
|
1326
|
+
entries["uniqueConstraints"] = [
|
|
1327
|
+
{"name": u["name"], "kind": u["kind"], "columns": list(u["columns"])}
|
|
1328
|
+
for u in facts.unique_constraints
|
|
1329
|
+
]
|
|
1065
1330
|
if rec is not None and rec.read_only:
|
|
1066
1331
|
entries["readOnly"] = True
|
|
1067
|
-
if rec is not None and rec.updateable_fields_literal:
|
|
1332
|
+
if rec is not None and rec.updateable_fields_literal is not None:
|
|
1068
1333
|
entries["updateableFields"] = list(rec.updateable_fields_literal)
|
|
1069
1334
|
return entries
|
|
1070
1335
|
|
|
@@ -1577,7 +1842,13 @@ def scan(paths: list[str], root: Path | None = None) -> dict:
|
|
|
1577
1842
|
if finding is not None:
|
|
1578
1843
|
findings.append(finding)
|
|
1579
1844
|
continue
|
|
1845
|
+
# Coverage evidence records EVERY successfully parsed file, test
|
|
1846
|
+
# fixtures included — a hole in the scan must stay visible. The
|
|
1847
|
+
# index is what feeds the resource graph, and a fixture table is
|
|
1848
|
+
# not business surface (see ``_is_test_path``).
|
|
1580
1849
|
scanned.append(relpath)
|
|
1850
|
+
if _is_test_path(relpath):
|
|
1851
|
+
continue
|
|
1581
1852
|
indexes[relpath] = index
|
|
1582
1853
|
resources: list[dict] = []
|
|
1583
1854
|
unresolved: list[dict] = []
|
|
@@ -1605,26 +1876,68 @@ def scan(paths: list[str], root: Path | None = None) -> dict:
|
|
|
1605
1876
|
model_names.add(simple)
|
|
1606
1877
|
changed = True
|
|
1607
1878
|
|
|
1879
|
+
# Pass 0b: the SQLModel closure, to a fixpoint over ALL scanned
|
|
1880
|
+
# files. A class deriving from ``SQLModel`` (or from another
|
|
1881
|
+
# SQLModel-derived class in any file) enters it; the same
|
|
1882
|
+
# fail-closed provenance rules apply, so a Pydantic namesake never
|
|
1883
|
+
# does. Needed for the split-base style the FastAPI template ships:
|
|
1884
|
+
# ``class UserBase(SQLModel)`` + ``class User(UserBase, table=True)``.
|
|
1885
|
+
sqlmodel_names: set[str] = set()
|
|
1886
|
+
changed = True
|
|
1887
|
+
while changed:
|
|
1888
|
+
changed = False
|
|
1889
|
+
for idx in indexes.values():
|
|
1890
|
+
for rec in idx.classes:
|
|
1891
|
+
simple = rec.qname.rsplit(".", 1)[-1]
|
|
1892
|
+
if simple in sqlmodel_names:
|
|
1893
|
+
continue
|
|
1894
|
+
if any(idx.base_is_sqlmodel(base, sqlmodel_names) for base in rec.bases):
|
|
1895
|
+
sqlmodel_names.add(simple)
|
|
1896
|
+
changed = True
|
|
1897
|
+
|
|
1898
|
+
sqlmodel_closure = frozenset(sqlmodel_names)
|
|
1899
|
+
|
|
1608
1900
|
# Pass 1: class symbols + business tables + typed unresolved + signals.
|
|
1609
1901
|
for relpath in sorted(indexes):
|
|
1610
1902
|
idx = indexes[relpath]
|
|
1611
1903
|
for rec in idx.classes:
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1904
|
+
candidate = rec.is_table_candidate(idx, model_names)
|
|
1905
|
+
# SQLModel derives an undeclared table name at runtime by
|
|
1906
|
+
# lowercasing the class name — a name the AST can see, so it
|
|
1907
|
+
# is a fact, not a guess (any OTHER declared name source —
|
|
1908
|
+
# a literal, an expression, a method — stays unresolved).
|
|
1909
|
+
derived_name = (
|
|
1910
|
+
rec.qname.rsplit(".", 1)[-1].lower()
|
|
1911
|
+
if rec.is_sqlmodel_table(idx, sqlmodel_closure)
|
|
1912
|
+
and rec.tablename_literal is None
|
|
1913
|
+
and rec.tablename_expr is None
|
|
1914
|
+
and rec.tablename_func is None
|
|
1915
|
+
else None
|
|
1916
|
+
)
|
|
1917
|
+
table_name = rec.tablename_literal or derived_name
|
|
1918
|
+
if candidate or rec.is_pure_base(idx):
|
|
1919
|
+
resources.append(
|
|
1920
|
+
_symbol_resource(
|
|
1921
|
+
relpath,
|
|
1922
|
+
rec,
|
|
1923
|
+
table_name is None and not rec.is_pure_base(idx),
|
|
1924
|
+
table_name,
|
|
1925
|
+
)
|
|
1615
1926
|
)
|
|
1616
|
-
resources.append(_symbol_resource(relpath, rec, last_segment_unresolved))
|
|
1617
1927
|
if rec.is_pure_base(idx):
|
|
1618
1928
|
continue # bases never materialize; the symbol table owns them
|
|
1619
|
-
if
|
|
1620
|
-
|
|
1621
|
-
|
|
1929
|
+
if table_name is not None:
|
|
1930
|
+
provenance = (
|
|
1931
|
+
"literal" if rec.tablename_literal is not None
|
|
1932
|
+
else SQLMODEL_CLASS_NAME_PROVENANCE
|
|
1933
|
+
)
|
|
1934
|
+
resources.append(_table_resource(relpath, rec, provenance, table_name))
|
|
1622
1935
|
identity = _identity_signal(rec, relpath, table_name, rec.node)
|
|
1623
1936
|
if identity is not None:
|
|
1624
1937
|
signals.append(identity)
|
|
1625
1938
|
signals.extend(_declaration_signals(rec, relpath, table_name))
|
|
1626
1939
|
unresolved.extend(_signal_unresolved_entries(rec, relpath, identity is not None))
|
|
1627
|
-
elif
|
|
1940
|
+
elif candidate:
|
|
1628
1941
|
unresolved.append(_unresolved_entry(relpath, rec))
|
|
1629
1942
|
|
|
1630
1943
|
# Pass 2: direct Table("name", ...) declarations.
|
|
Binary file
|
|
Binary file
|
|
Binary file
|