Skip to content

Alembic generates unneeded migrations for expression-based indexes #1321

Closed
@vasa-chi

Description

@vasa-chi

Describe the bug
I have a table that has an index like this:

Index(
    "event_requisition_action_idx2", arguments["requisition_id"].as_integer()
),

In database it is represented as follows:

"event_requisition_create_idx2" btree (((response ->> 'id'::text)::integer)) 

After migrating to SQLAlchemy 2.0 Alembic started to generate migrations that drop the index, and create another, that is the same, but uses another syntax:

    op.drop_index('event_requisition_create_idx2', table_name='event')
    op.create_index('event_requisition_create_idx2', 'event', [sa.text("CAST(response ->> 'id' AS INTEGER)")], unique=False)

After upgrade, the index is the same as before:

"event_requisition_create_idx2" btree (((response ->> 'id'::text)::integer)) 

Expected behavior
No migrations are created for the index.

To Reproduce
Please try to provide a Minimal, Complete, and Verifiable example, with the migration script and/or the SQLAlchemy tables or models involved.
See also Reporting Bugs on the website.

from sqlalchemy import Column, Index
from sqlalchemy.orm import declarative_base
from sqlalchemy.dialects.postgresql JSONB

Base = declarative_base()

class Event(Base):
    __tablename__ = 'event'

    id = Column(Integer, primary_key=True)
    arguments = Column(JSONB)

    __table__args__ = (
        Index("event_arguments_idx", arguments["numeric"].as_integer()),
    )

Versions.

  • OS: macOS 14.0
  • Python: 3.7.13
  • Alembic: 1.12.0
  • SQLAlchemy: 2.0.21
  • Database: PostgreSQL 15.3 on aarch64-apple-darwin21.6.0, compiled by Apple clang version 14.0.0 (clang-1400.0.29.102), 64-bit
  • DBAPI: psycopg2==2.9.9

Additional context

Currently, I solved this by using a text() notation for the index expression:

        Index(
            "event_requisition_action_idx2",
            # arguments["requisition_id"].as_integer(),
            text("((arguments ->> 'requisition_id'::text)::integer)"),
        ),

This doesn't cause any new migrations.

Have a nice day!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions