I am trying to get a composite index working between a polymorphic subclass and it’s parent.
Alembic autogenerate does not seem to detect Indexes outside of __table_args__
.
I can’t use __table_args__
because, being in the subclass, it does not count my class as having a __table__
.
How do I create a composite Index between these?
JavaScript
x
24
24
1
class Main(Base, SomeMixin):
2
__tablename__ = "main"
3
__table_args__ = (
4
# Some constraints and Indexes specific to main
5
)
6
7
id = Column(String, primary_key=True, default=func.generate_object_id())
8
9
mtype = Column(String, nullable=False)
10
11
__mapper_args__ = {"polymorphic_on": mtype}
12
13
class SubClass(Main):
14
__mapper_args__ = {"polymorphic_identity": "subclass"}
15
16
bid = Column(String, ForeignKey("other.id", ondelete="CASCADE"))
17
18
# My index specific to Subclass
19
Index(
20
"ix_main_bid_mtype",
21
"bid",
22
"mtype",
23
)
24
The goal is to have something like this pop with alembic autogenerate:
JavaScript
1
16
16
1
def upgrade():
2
# ### commands auto generated by Alembic - please adjust! ###
3
op.create_index(
4
"ix_main_bid_mtype",
5
"main",
6
["bid", "mtype"],
7
unique=False,
8
)
9
# ### end Alembic commands ###
10
11
12
def downgrade():
13
# ### commands auto generated by Alembic - please adjust! ###
14
op.drop_index(op.f("ix_main_bid_mtype"), table_name="main")
15
# ### end Alembic commands ###
16
Thank you for your time and potential future help.
EDIT: Note: The other fields are detected by autogenerate, only the index done this way does not seem to work.
Advertisement
Answer
Create the index externally after both classes:
JavaScript
1
21
21
1
class Main(Base, SomeMixin):
2
__tablename__ = "main"
3
__table_args__ = (
4
# Some constraints and Indexes specific to main
5
)
6
7
id = Column(String, primary_key=True, default=func.generate_object_id())
8
9
mtype = Column(String, nullable=False)
10
11
__mapper_args__ = {"polymorphic_on": mtype}
12
13
14
class SubClass(Main):
15
__mapper_args__ = {"polymorphic_identity": "subclass"}
16
17
bid = Column(String, ForeignKey("other.id", ondelete="CASCADE"))
18
19
20
Index("ix_main_bid_mtype", SubClass.bid, SubClass.mtype)
21