Skip to content

Commit

Permalink
Fixes [302](#302)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheinbergon committed Jan 9, 2025
1 parent 9925f10 commit d119953
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
7 changes: 5 additions & 2 deletions src/sqlacodegen/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -1362,15 +1362,18 @@ def generate_base(self) -> None:
self.base = Base(
literal_imports=[],
declarations=[],
metadata_ref="",
metadata_ref="metadata",
table_metadata_declaration="metadata = MetaData()",
)

def collect_imports(self, models: Iterable[Model]) -> None:
super(DeclarativeGenerator, self).collect_imports(models)
if any(isinstance(model, Model) for model in models):
self.add_literal_import("sqlalchemy", "MetaData")
if any(isinstance(model, ModelClass) for model in models):
self.remove_literal_import("sqlalchemy", "MetaData")
self.add_literal_import("sqlmodel", "SQLModel")
self.add_literal_import("sqlmodel", "Field")
self.add_literal_import("sqlalchemy.orm", "mapped_column")

def collect_imports_for_model(self, model: Model) -> None:
super(DeclarativeGenerator, self).collect_imports_for_model(model)
Expand Down
7 changes: 4 additions & 3 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,14 @@ def test_cli_sqlmodels(db_path: Path, tmp_path: Path) -> None:
== """\
from typing import Optional
from sqlalchemy import Column, Integer, Text
from sqlalchemy import Integer, MetaData, Text
from sqlalchemy.orm import mapped_column
from sqlmodel import Field, SQLModel
class Foo(SQLModel, table=True):
id: Optional[int] = Field(default=None, sa_column=Column('id', Integer, \
id: Optional[int] = Field(default=None, sa_column=mapped_column('id', Integer, \
primary_key=True))
name: str = Field(sa_column=Column('name', Text, nullable=False))
name: str = Field(sa_column=mapped_column('name', Text))
"""
)

Expand Down

0 comments on commit d119953

Please sign in to comment.