Search code examples
mysqlsqlalchemyalembic

How do I set an initial value for a primary key set to automatically increment using SQLAlchemy/Alembic?


In MySQL, we can use AUTO_INCREMENT = ? to automatically insert a primary key value. How do we do it in SQLAlchemy/Alembic? Thanks very much!


Solution

  • auto_increment is emitted within a CREATE TABLE if the type is "Integer, primary_key=True". Within Alembic using alter_column, you need to specify it to alter_column.

    See "autoincrement" and "existing_autoincrement" for alter_column() at:

    https://alembic.readthedocs.org/en/latest/ops.html#alembic.operations.Operations.alter_column

    See autoincrement for Column, note this defaults to True and you normally don't need to change it, at:

    http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#sqlalchemy.schema.Column.__init__