Last active
December 23, 2015 07:19
-
-
Save zzzeek/6600104 to your computer and use it in GitHub Desktop.
change how alembic runs an ADD COLUMN on postgresql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# in env.py.... | |
from alembic.ddl.postgresql import PostgresqlImpl | |
class MyPostgresqlImpl(PostgresqlImpl): | |
__dialect__ = 'postgresql' | |
def add_column(self, table_name, column, schema=None): | |
if column.server_default is not None: | |
server_default = column.server_default | |
column.server_default = None | |
nullable = column.nullable | |
column.nullable = True | |
super(MyPostgresqlImpl, self).add_column(table_name, column, schema=schema) | |
self.alter_column(table_name, column.name, | |
server_default=server_default, schema=schema) | |
if not nullable: | |
self.alter_column(table_name, column.name, nullable=False, schema=schema) | |
else: | |
super(MyPostgresqlImpl, self).add_column(table_name, column, schema=schema) | |
# profit! | |
# output of: | |
def upgrade(): | |
op.add_column("foo", sa.Column('data', sa.String(50), nullable=False, server_default='value')) | |
INFO [alembic.migration] Running upgrade 20cab39367e3 -> 500e690e37d0, add col w default | |
INFO [sqlalchemy.engine.base.Engine] ALTER TABLE foo ADD COLUMN data VARCHAR(50) | |
INFO [sqlalchemy.engine.base.Engine] {} | |
INFO [sqlalchemy.engine.base.Engine] ALTER TABLE foo ALTER COLUMN data SET DEFAULT 'value' | |
INFO [sqlalchemy.engine.base.Engine] {} | |
INFO [sqlalchemy.engine.base.Engine] ALTER TABLE foo ALTER COLUMN data SET NOT NULL | |
INFO [sqlalchemy.engine.base.Engine] {} | |
INFO [sqlalchemy.engine.base.Engine] UPDATE alembic_version SET version_num='500e690e37d0' | |
INFO [sqlalchemy.engine.base.Engine] {} | |
INFO [sqlalchemy.engine.base.Engine] COMMIT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is it just me, or that the alter_column of lines 14-15 will not actually affect current rows?
If you would like to set not nullable at line 17, you should actually set all the rows to the requested default value or the operation fails.