Skip to content

Commit

Permalink
Add force_class option
Browse files Browse the repository at this point in the history
  • Loading branch information
multimeric committed Sep 14, 2024
1 parent eb7b95f commit 5c6b1ef
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/sqlacodegen/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,7 @@ class DeclarativeGenerator(TablesGenerator):
"use_inflect",
"nojoined",
"nobidi",
"force_class"
}

def __init__(
Expand Down Expand Up @@ -774,16 +775,16 @@ def generate_models(self) -> list[Model]:

# Only form model classes for tables that have a primary key and are not
# association tables
if not table.primary_key:
models_by_table_name[qualified_name] = Model(table)
else:
if table.primary_key or "force_class" in self.options:
model = ModelClass(table)
models_by_table_name[qualified_name] = model

# Fill in the columns
for column in table.c:
column_attr = ColumnAttribute(model, column)
model.columns.append(column_attr)
else:
models_by_table_name[qualified_name] = Model(table)

# Add relationships
for model in models_by_table_name.values():
Expand Down
30 changes: 30 additions & 0 deletions tests/test_generator_declarative.py
Original file line number Diff line number Diff line change
Expand Up @@ -1509,3 +1509,33 @@ class Simple(Base):
server_default=text("'test'"))
""",
)


def test_force_class(
metadata: MetaData, engine: Engine
) -> None:
generator = DeclarativeGenerator(metadata, engine, options = ["force_class"])
Table(
"simple",
generator.metadata,
Column("a", INTEGER),
Column("b", VARCHAR),
)


assert generator.generate() == """\
from typing import Optional
from sqlalchemy import Integer, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class Simple(Base):
__tablename__ = 'simple'
a: Mapped[Optional[int]] = mapped_column(Integer)
b: Mapped[Optional[str]] = mapped_column(String)
"""

0 comments on commit 5c6b1ef

Please sign in to comment.