Adding indexes to SQLAlchemy models after table creation

前端 未结 6 1165
野性不改
野性不改 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:56

    Please note that this is incorrect and over-complicated answer

    The right way is to use index.create as it was said here.


    First of all make sure that you have latest snapshot of your database and is able to restore database from this snapshot.

    For medium and large size projects (the ones that you might need to support several versions at the same time and are installed on multiple environments) there is special procedure which is part of database management lifecycle called "database migration". DB migrations includes changes to existing schema. SQLAlchemy doesn't support migration out of the box.

    There are two SQLAlchemy compatible database migration tools available:

    • Alembic
    • SQLAlchemy-Migrate

    See more information and links to these tools in SQLAlchemy documentation page: Altering Schemas through Migrations.

    But if your are working on small project I would suggest to manually run ALTER TABLE DDL query from the database command line utility or through connection.execute() in python script.

    In the production application I'm working at right now, we support only one latest version of application. For every database schema change we do the following steps:

    • make a snapshot of the production database
    • load this snapshot on development environment
    • update sqlalchemy data model module
    • prepare and run alter table query and save this query for later
    • make other related changes to the code
    • run tests on dev environment
    • deploy latest version of the code to production
    • do alter table on production

    Also I'm using the following trick for generating create table/index queries: I point my application to brand new database, enable logging of sqlalchemy queries and run metadata.create_all() - so in logs (or STDOUT) I see create query generated by sqlalchemy

    Depending on the database system you are using index creation query will be little different. Generic query would look like this:

    create index targets_i on targets(url);
    

提交回复
热议问题