@gate-forge/pack-sqlalchemy 0.25.0 → 0.25.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gate-forge/pack-sqlalchemy",
3
- "version": "0.25.0",
3
+ "version": "0.25.1",
4
4
  "license": "Apache-2.0",
5
5
  "description": "SQLAlchemy CRUD discovery pack: AST-only python detector (GPP/3), in-process TS discover entry, configurable plane mapping, entity-adapter schema.",
6
6
  "type": "module",
@@ -29,8 +29,8 @@
29
29
  "test": "vitest run"
30
30
  },
31
31
  "dependencies": {
32
- "@gate-forge/core": "^0.25.0",
33
- "@gate-forge/plugin-protocol": "^0.25.0",
32
+ "@gate-forge/core": "^0.25.1",
33
+ "@gate-forge/plugin-protocol": "^0.25.1",
34
34
  "yaml": "^2.8.1",
35
35
  "zod": "^4.1.5"
36
36
  },
@@ -15,12 +15,21 @@ from __future__ import annotations
15
15
 
16
16
  import ast
17
17
  import re
18
- from collections import Counter
18
+ from collections import Counter, defaultdict
19
19
 
20
20
  from . import PLUGIN_ID
21
21
  from .scan import _module_to_relpath, _signal, loc
22
22
 
23
23
  SA_MODULES = frozenset({"sqlalchemy", "sqlalchemy.orm"})
24
+ TABLE_NAMES = frozenset({"Table", "table"})
25
+
26
+
27
+ def _in_sa_family(module):
28
+ """D2: the root is ``sqlmodel`` or contains ``alchemy`` (sqlalchemy, flask_sqlalchemy, geoalchemy2, ...)."""
29
+ root = module.split(".")[0]
30
+ return root == "sqlmodel" or "alchemy" in root
31
+
32
+
24
33
  # A `__main__` block that reaches one of these starts a server: no entry point.
25
34
  SERVER_NAMES = frozenset({"run", "serve", "serve_forever"})
26
35
  WRITE_CALLS = frozenset({"insert", "update", "delete"})
@@ -70,7 +79,8 @@ def reachability_signals(indexes, trees, tables, categories, others, root):
70
79
  writer of the table. ``unreferenced`` gives a signal at the
71
80
  definition of each table that no serving module names; granting
72
81
  it trusts only alembic-shaped revision modules as operator code,
73
- and scripts are serving code (see ``_References``).
82
+ and scripts are serving code (see ``_References``). A run void for it
83
+ gives non-certifying signals naming each construct instead.
74
84
  others: Relpaths of the non-test inputs that are not in ``indexes``.
75
85
  Read as bytes, and only for ``unreferenced``.
76
86
  root: The scan root ``others`` resolve under.
@@ -252,9 +262,9 @@ def _table_key(table):
252
262
  return (table[0], table[1] or "", table[2])
253
263
 
254
264
 
255
- def _table_signal(table, category, location):
265
+ def _table_signal(table, assertion, location, basis="code-positive"):
256
266
  relpath, symbol, name = table
257
- signal = _signal("internality", category, "code-positive", PLUGIN_ID, location, name, symbol)
267
+ signal = _signal("internality", assertion, basis, PLUGIN_ID, location, name, symbol)
258
268
  if symbol is not None:
259
269
  # A declarative class target carries its symbol only: the bare table
260
270
  # name would bind the signal to every same-named table in the scan.
@@ -731,13 +741,16 @@ class _References:
731
741
  scanned module imports or names in a string. Every other module is
732
742
  serving code, scripts included: nothing in the scan shows what launches one.
733
743
 
734
- The guard: one construct that can reach a table without naming it (see
735
- ``_visit``) voids every signal of the run.
744
+ The guard: a construct that can reach a table without naming it (see
745
+ ``_visit``) voids the run. A void run emits no ``unreferenced`` signal; it
746
+ gives each target nothing names one non-certifying signal per construct
747
+ (``signals``), so the core can name the construct but never certify.
736
748
  """
737
749
 
738
750
  def __init__(self, walker, others, root):
739
751
  self.walker = walker
740
- self.void = False
752
+ self.void = [] # (relpath, node, construct kind) per construct that can reach a table unnamed
753
+ self._bindings_by_rel = {} # file -> (import bindings, other binding counts, star import)
741
754
  self.classes = {} # a target's ClassDef -> its symbol
742
755
  self.own = set() # ids of a Table() target's own binding name and name argument
743
756
  self.targets = self._targets()
@@ -829,45 +842,116 @@ class _References:
829
842
  stack.extend((child, region) for child in ast.iter_child_nodes(node))
830
843
 
831
844
  def _visit(self, rel, node, region):
832
- """Notes the reference one node makes; sets ``void`` when it can reach a table unnamed."""
845
+ """Notes the reference one node makes; records in ``void`` a construct that can reach a table unnamed."""
833
846
  text = _str_const(node)
834
847
  if isinstance(node, ast.Name):
835
848
  _note(self.idents, node.id, region)
836
849
  elif isinstance(node, ast.Attribute):
837
850
  _note(self.idents, node.attr, region)
838
851
  if node.attr in REGISTRY_ATTRS or (node.attr == "tables" and _final_name(node.value) == "metadata"):
839
- self.void = True
852
+ self.void.append((rel, node, "registry-walk"))
840
853
  elif isinstance(node, ast.alias) and node.asname is not None:
841
854
  # ``from models import Row as R``: the uses then say ``R``, never ``Row``.
842
855
  _note(self.idents, node.name, region)
843
- elif isinstance(node, ast.Call) and self._computed_lookup(rel, node):
844
- self.void = True
856
+ elif isinstance(node, ast.Call):
857
+ kind = self._computed_lookup(rel, node)
858
+ if kind is not None:
859
+ self.void.append((rel, node, kind))
845
860
  elif text is not None:
846
861
  for word in WORD.findall(text.lower()):
847
862
  _note(self.words, word, region)
848
863
  if isinstance(node, (ast.Constant, ast.JoinedStr, ast.BinOp)) and COMPUTED_WRITE.match(_template(node)):
849
- self.void = True
864
+ self.void.append((rel, node, "computed-write"))
865
+
866
+ def _bindings(self, rel, name):
867
+ """The import bindings of ``name`` in ``rel``, as ``(module, imported, level)``, and how many other bindings it has.
868
+
869
+ One walk per file. Parameters count as other bindings. A star import
870
+ binds names the walk cannot see, so it counts for every name.
871
+ """
872
+ if rel not in self._bindings_by_rel:
873
+ imports, others, star = defaultdict(list), Counter(), False
874
+ for node in ast.walk(self.walker.trees[rel]):
875
+ if isinstance(node, ast.Import):
876
+ for alias in node.names:
877
+ head = alias.name.split(".")[0]
878
+ imports[alias.asname or head].append((alias.name if alias.asname else head, None, 0))
879
+ elif isinstance(node, ast.ImportFrom):
880
+ star = star or any(alias.name == "*" for alias in node.names)
881
+ for alias in node.names:
882
+ if alias.name != "*":
883
+ imports[alias.asname or alias.name].append((node.module or "", alias.name, node.level))
884
+ elif isinstance(node, ast.arg):
885
+ others[node.arg] += 1
886
+ else:
887
+ others.update(_bound_names([node]))
888
+ self._bindings_by_rel[rel] = (imports, others, star)
889
+ imports, others, star = self._bindings_by_rel[rel]
890
+ return imports.get(name, []), others[name] + int(star)
891
+
892
+ def _may_be_scanned(self, dotted):
893
+ """True when a scanned module is ``dotted`` or one of its dotted prefixes: it could re-export SQLAlchemy's Table."""
894
+ parts = dotted.split(".")
895
+ return any(".".join(parts[:i]) in self.modules for i in range(1, len(parts) + 1))
896
+
897
+ def _table_callee(self, rel, func):
898
+ """``sqlalchemy``, ``foreign`` or ``unknown`` for a callee that may build a table; None for any other callee.
899
+
900
+ D1=a, D2=a. ``sqlalchemy``: an absolute import of the callee's root name
901
+ from the SQLAlchemy family names ``Table`` or ``table`` (a bare callee)
902
+ or the callee's final name is one of them (an attribute). ``foreign``:
903
+ the root is bound only by absolute imports outside the family that no
904
+ scanned module can re-export. ``unknown``: anything else.
905
+ """
906
+ final = _final_name(func)
907
+ root = func
908
+ while isinstance(root, ast.Attribute):
909
+ root = root.value
910
+ if not isinstance(root, ast.Name):
911
+ return "unknown" if final in TABLE_NAMES else None
912
+ imports, others = self._bindings(rel, root.id)
913
+ bare = isinstance(func, ast.Name)
914
+ if any(
915
+ level == 0 and _in_sa_family(module) and ((imported in TABLE_NAMES) if bare else (final in TABLE_NAMES))
916
+ for module, imported, level in imports
917
+ ):
918
+ return "sqlalchemy"
919
+ if final not in TABLE_NAMES:
920
+ return None
921
+ foreign = all(
922
+ level == 0
923
+ and not _in_sa_family(module)
924
+ and not self._may_be_scanned(f"{module}.{imported}" if imported else module)
925
+ for module, imported, level in imports
926
+ )
927
+ return "foreign" if imports and not others and foreign else "unknown"
850
928
 
851
929
  def _computed_lookup(self, rel, call):
852
- """True for ``table(<non-literal>)``, ``Table(<non-literal>, ...)`` and ``getattr(<scanned module>, <non-literal>)``."""
930
+ """The construct kind of a table constructor (``_table_callee``) with a non-literal first argument, ``computed-table``, or of ``getattr(<scanned module>, <non-literal>)``, ``module-getattr``; None otherwise."""
853
931
  func, args = call.func, call.args
854
- if _final_name(func) in ("table", "Table"):
855
- return bool(args) and _str_const(args[0]) is None
932
+ if self._table_callee(rel, func) in ("sqlalchemy", "unknown"):
933
+ return "computed-table" if args and _str_const(args[0]) is None else None
856
934
  if not (isinstance(func, ast.Name) and func.id == "getattr" and len(args) >= 2 and isinstance(args[0], ast.Name)):
857
- return False
935
+ return None
858
936
  ref = self.walker.indexes[rel].imports.get(args[0].id)
859
937
  if ref is None or _str_const(args[1]) is not None:
860
- return False
938
+ return None
861
939
  module = ref.module if ref.name is None else f"{ref.module}.{ref.name}".lstrip(".")
862
- return module in self.modules
940
+ return "module-getattr" if module in self.modules else None
863
941
 
864
942
  def signals(self):
865
- """One signal per target nothing names, at its definition; none when the run is void."""
866
- if self.void:
867
- return []
943
+ """One signal per target nothing names, at its definition. A void run gives each such target one non-certifying signal per construct instead."""
944
+ sites = {}
945
+ for rel, node, kind in self.void:
946
+ sites.setdefault((rel, node.lineno, kind), node)
868
947
  out = []
869
948
  for table, symbol, node in self.targets:
870
949
  named = self.idents[symbol] | self.words[symbol.lower()] | self.words[table[2].lower()]
871
- if not named - {node}:
950
+ if named - {node}:
951
+ continue
952
+ if not sites:
872
953
  out.append(_table_signal(table, "unreferenced", loc(table[0], node)))
954
+ for key in sorted(sites):
955
+ assertion = {"voidCategory": "unreferenced", "construct": key[2]}
956
+ out.append(_table_signal(table, assertion, loc(key[0], sites[key]), "code-negative-closed-world"))
873
957
  return out