Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ Version history
- Fixed a column named ``registry`` being rendered as-is, which made SQLAlchemy warn
that the attribute should be left reserved for the declarative class registry; it is
now renamed to ``registry_`` the same way a ``metadata`` column already was
- Fixed a column named like a module used in the type annotations (``uuid``,
``datetime``, ``decimal``) shadowing that module, which made the generated declarative
and dataclass models fail at import with ``AttributeError``; the attribute is now renamed
(`#331 <https://github.com/agronholm/sqlacodegen/issues/331>`_; PR by @jayhemnani9910)

**4.0.4**

Expand Down
7 changes: 6 additions & 1 deletion src/sqlacodegen/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -1148,6 +1148,11 @@ def collect_imports_for_model(self, model: Model) -> None:
if model.relationships:
self.add_literal_import("sqlalchemy.orm", "relationship")

# Collect the modules the Mapped[] annotations use (uuid, datetime,
# decimal) now, so attribute names can avoid them
for column in model.table.columns:
self.render_column_python_type(column)

def generate_models(self) -> list[Model]:
models_by_table_name: dict[str, Model] = {}

Expand Down Expand Up @@ -1223,7 +1228,7 @@ def generate_models(self) -> list[Model]:
# attributes
global_names = {
name for namespace in self.imports.values() for name in namespace
}
} | self.module_imports
for model in models_by_table_name.values():
self.generate_model_name(model, global_names)
global_names.add(model.name)
Expand Down
29 changes: 29 additions & 0 deletions tests/test_generator_declarative.py
Original file line number Diff line number Diff line change
Expand Up @@ -2187,6 +2187,35 @@ class Simple(Base):
)


def test_column_named_like_annotation_module(generator: CodeGenerator) -> None:
Table(
"accounts",
generator.metadata,
Column("id", INTEGER, primary_key=True),
Column("uuid", postgresql.UUID, nullable=False),
)

validate_code(
generator.generate(),
"""\
import uuid

from sqlalchemy import Integer, UUID
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

class Base(DeclarativeBase):
pass


class Accounts(Base):
__tablename__ = 'accounts'

id: Mapped[int] = mapped_column(Integer, primary_key=True)
uuid_: Mapped[uuid.UUID] = mapped_column('uuid', UUID, nullable=False)
""",
)


def test_invalid_variable_name_from_column(generator: CodeGenerator) -> None:
Table(
"simple",
Expand Down