Adding indexes to SQLAlchemy models after table creation

前端 未结 6 1183
野性不改
野性不改 2021-01-31 16:20

I have a flask-sqlalchemy model:

class MyModel(db.Model):
__tablename__ = \'targets\'
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.String(2048         


        
6条回答
  •  暖寄归人
    2021-01-31 16:53

    I am not sure if this conforms to best practices but I found Alembic would notify me of Indexes in the __table_args__ but not actually make them for me during migrations. I made this small script that can generate new indexes found in the __table_args__ property. It makes use of Index.create() as mentioned above, but will generate new indexes if they do not exist.

    def create_indexes(db, drop_index=False):
        """
        Creates all indexes on models in project if they do not exists already. Assumes all models
        inherit from RequiredFields class, otherwise will need to adjust search for subclasses. If the index
        exists SQLAlchemy throws an error and we assume everything is ok. 
        :param db: The app db object, acts as the engine param for the Index.create()
        :param drop_index: specifies whether the indexes should be dropped or created
        :return:
        """
        from application.base_models import RequiredFields
        from sqlalchemy import Index
        from sqlalchemy.exc import ProgrammingError
        for klass in RequiredFields.__subclasses__():
            if hasattr(klass, '__table_args__'):
                for item in getattr(klass, '__table_args__'):
                    if isinstance(item, Index):
                        try:
                            if not drop_index:
                                item.create(db.engine)
                            else:
                                item.drop(db.engine)
                        except ProgrammingError:  # If index exists, creation fails on error
                            pass
        return
    

    Here is a sample class showing the indexes.

    class MyModel(RequiredFields):
    
        __table_args__ = (
             db.Index( ... ),
             db.Index( ... ),
        )
    

提交回复
热议问题