Skip to content
Merged
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: 3 additions & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ Version history
connect to the same target table. Regenerating models will break existing code.
- Improved relationship naming: one-to-many uses FK column names (e.g.,
``simple_items_parent_container``), many-to-many uses junction table names (e.g.,
``students_enrollments``). Use ``--options nofknames`` to revert to old behavior.
``students_enrollments``). Use ``--options nofknames`` to revert to old behavior. (PR by @sheinbergon)
- Fixed ``Index`` kwargs (e.g. ``mysql_length``) being ignored during code generation
(PR by @luliangce)

**4.0.0rc2**

Expand Down
5 changes: 4 additions & 1 deletion src/sqlacodegen/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,10 @@ def render_table(self, table: Table) -> str:

def render_index(self, index: Index) -> str:
extra_args = [repr(col.name) for col in index.columns]
kwargs = {}
kwargs = {
key: repr(value) if isinstance(value, str) else value
for key, value in sorted(index.kwargs.items(), key=lambda item: item[0])
}
if index.unique:
kwargs["unique"] = True

Expand Down
39 changes: 37 additions & 2 deletions tests/test_generator_declarative.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,41 @@ class SimpleItems(Base):
)


def test_index_with_kwargs(generator: CodeGenerator) -> None:
simple_items = Table(
"simple_items",
generator.metadata,
Column("id", INTEGER, primary_key=True),
Column("name", VARCHAR),
)
simple_items.indexes.add(
Index("idx_name", simple_items.c.name, postgresql_using="gist", mysql_length=10)
)

validate_code(
generator.generate(),
"""\
from typing import Optional

from sqlalchemy import Index, Integer, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

class Base(DeclarativeBase):
pass


class SimpleItems(Base):
__tablename__ = 'simple_items'
__table_args__ = (
Index('idx_name', 'name', mysql_length=10, postgresql_using='gist'),
)

id: Mapped[int] = mapped_column(Integer, primary_key=True)
name: Mapped[Optional[str]] = mapped_column(String)
""",
)


def test_constraints(generator: CodeGenerator) -> None:
Table(
"simple_items",
Expand Down Expand Up @@ -2382,8 +2417,8 @@ class Base(DeclarativeBase):
class SpatialTable(Base):
__tablename__ = 'spatial_table'
__table_args__ = (
Index('idx_spatial_table_geog', 'geog'),
Index('idx_spatial_table_geom', 'geom')
Index('idx_spatial_table_geog', 'geog', postgresql_using='gist'),
Index('idx_spatial_table_geom', 'geom', postgresql_using='gist')
)

id: Mapped[int] = mapped_column(Integer, primary_key=True)
Expand Down