Buckets:
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| """ | |
| Split SQLAlchemy models into one file per table. | |
| Usage: | |
| python split_models.py /path/to/your/repo/src/OSSS/db/models /path/to/output/models_split | |
| """ | |
| import argparse | |
| import ast | |
| import re | |
| from pathlib import Path | |
| HEADER = """from __future__ import annotations | |
| from datetime import datetime, date, time | |
| from decimal import Decimal | |
| from typing import Any, Optional, List | |
| import sqlalchemy as sa | |
| from sqlalchemy import ForeignKey, UniqueConstraint, text | |
| from sqlalchemy.orm import Mapped, mapped_column, relationship | |
| from OSSS.db.base import Base, UUIDMixin, GUID, JSONB | |
| """ | |
| def snake(name: str) -> str: | |
| s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) | |
| return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() | |
| def find_model_classes(tree: ast.Module): | |
| classes = [] | |
| for node in tree.body: | |
| if isinstance(node, ast.ClassDef): | |
| # Has __tablename__ = "..." assignment? | |
| tablename = None | |
| for stmt in node.body: | |
| if isinstance(stmt, ast.Assign): | |
| for target in stmt.targets: | |
| if isinstance(target, ast.Name) and target.id == "__tablename__": | |
| if isinstance(stmt.value, ast.Constant) and isinstance(stmt.value.value, str): | |
| tablename = stmt.value.value | |
| break | |
| if tablename: | |
| break | |
| if not tablename: | |
| continue | |
| # Check inherits Base somewhere | |
| inherits_base = any( | |
| (isinstance(base, ast.Name) and base.id == "Base") | |
| or (isinstance(base, ast.Attribute) and base.attr == "Base") | |
| for base in node.bases | |
| ) | |
| if tablename and inherits_base: | |
| classes.append(node) | |
| return classes | |
| def referenced_names(node: ast.AST): | |
| names = set() | |
| class RefVisitor(ast.NodeVisitor): | |
| def visit_Name(self, n: ast.Name): | |
| names.add(n.id) | |
| RefVisitor().visit(node) | |
| return names | |
| def collect_helpers_for_class(module_tree: ast.Module, cls: ast.ClassDef): | |
| """ | |
| Copy helper constants/enums defined in the same file if referenced by the class. | |
| """ | |
| needed = referenced_names(cls) | |
| helpers = [] | |
| for node in module_tree.body: | |
| if isinstance(node, (ast.Assign, ast.AnnAssign)): | |
| # constants like SOME_CONST = ... | |
| targets = [] | |
| if isinstance(node, ast.Assign): | |
| targets = [t.id for t in node.targets if isinstance(t, ast.Name)] | |
| elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): | |
| targets = [node.target.id] | |
| if any(t in needed for t in targets): | |
| helpers.append(node) | |
| elif isinstance(node, ast.ClassDef): | |
| if node is not cls and node.name in needed: | |
| helpers.append(node) | |
| return helpers | |
| def get_source_segment(code: str, node: ast.AST) -> str: | |
| seg = ast.get_source_segment(code, node) | |
| return seg if seg is not None else "" | |
| def write_model_files(src_dir: Path, out_dir: Path): | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| created = [] | |
| for py in sorted(src_dir.glob("*.py")): | |
| if py.name in {"__init__.py", "base.py"}: | |
| continue | |
| code = py.read_text(encoding="utf-8") | |
| try: | |
| tree = ast.parse(code) | |
| except SyntaxError: | |
| continue | |
| classes = find_model_classes(tree) | |
| if not classes: | |
| continue | |
| for cls in classes: | |
| tablename = None | |
| for stmt in cls.body: | |
| if isinstance(stmt, ast.Assign): | |
| for t in stmt.targets: | |
| if isinstance(t, ast.Name) and t.id == "__tablename__": | |
| if isinstance(stmt.value, ast.Constant) and isinstance(stmt.value.value, str): | |
| tablename = stmt.value.value | |
| break | |
| if tablename: | |
| break | |
| if not tablename: | |
| tablename = snake(cls.name) | |
| helpers = collect_helpers_for_class(tree, cls) | |
| pieces = [HEADER, "\n"] | |
| for h in helpers: | |
| pieces.append(get_source_segment(code, h)) | |
| pieces.append("\n\n") | |
| pieces.append(get_source_segment(code, cls)) | |
| pieces.append("\n") | |
| out_file = out_dir / f"{tablename}.py" | |
| out_file.write_text("".join(pieces), encoding="utf-8") | |
| created.append(out_file.name) | |
| init_lines = ["# auto-generated by split_models.py\n"] | |
| for fn in sorted(created): | |
| mod = fn[:-3] | |
| init_lines.append(f"from .{mod} import *\n") | |
| (out_dir / "__init__.py").write_text("".join(init_lines), encoding="utf-8") | |
| return created | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("src_models_dir", type=Path) | |
| ap.add_argument("out_dir", type=Path) | |
| args = ap.parse_args() | |
| created = write_model_files(args.src_models_dir, args.out_dir) | |
| print(f"Created {len(created)} files in {args.out_dir}") | |
| for c in created: | |
| print(" -", c) | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 5.34 kB
- Xet hash:
- 91ab6b42967f18deef4a56b8532ee1fc8661c9a2fb34e56d98f3c7d5ea2d9570
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.