When using PostgreSQL, creating a foreign key on a column in a table does not automatically index that column, unlike Oracle or MySQL.
I would like to get SQLAlchemy to automatically create an index on the same columns that are specified in a ForeingKeyConstraint.
For example, if I have a table like this:
foo = table(
'foos', metadata,
Column('id', BigInteger),
Column('parent_id', BigInteger),
ForeignKeyConstraint(('parent_id',), refcolumns=('
bar.id',), name='foo_parent_id_fk')
)
I would like it to automatically add an Index like:
Index('foo_parent_id_idx', 'parent_id')
I've made the following, which appears to work:
from sqlalchemy import event, Table
@event.listens_for(Table, 'before_create')
def add_index_on_foreign_key_columns(table, connection, **kwargs):
for foreign_key in table.foreign_key_constraints:
index_name = foreign_key.name.replace('_fk', '_idx')
columns = (c.name for c in foreign_key.columns)
Index(index_name, *columns, _table=table)
Is there a better way to accomplish this?
Thanks and best regards,
Matthew Moisen