SQLAlchemy and Alembic Troubleshooting
May 12, 2022
Workflow:
- Create table with revision
- ID and one string column (no nulls)
- Add new string column (no nulls)
op.add_column("tbl_hello_world", Column("ISIN_B", String(length=255), nullable=False))
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'ISIN_B' cannot be added to non-empty table 'tbl_hello_world' because it does not satisfy these conditions. (4901) (SQLExecDirectW)")
This resolves the problem (using server_default
):
op.add_column("tbl_hello_world", Column("ISIN_B", String(length=255), nullable=False, server_default="QWERTY"))
Specify schema:
def add_column(
table_name: str, column: "Column", schema: Optional[str] = None
) -> Optional["Table"]:
Scripts:
# revision 1
def upgrade():
op.create_table(
"tbl_hello_world",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("ISIN_A", String(length=255), nullable=False),
)
def downgrade():
op.drop_table('tbl_hello_world')
# revision 2
def upgrade():
op.add_column("tbl_hello_world", Column("ISIN_B", String(length=255), nullable=False, server_default="QWERTY"))
def downgrade():
op.drop_column('tbl_hello_world', 'ISIN_B')
# revision 3
def upgrade():
op.create_table(
"tbl_foo_bar",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("ISIN_A", String(length=255), nullable=False),
schema="dbo"
)
def downgrade():
op.drop_table('tbl_foo_bar', schema="dbo")
Alembic commands:
- View the latest revision that has been run -
alembic current --verbose
- View all revisions and where HEAD is pointing to -
alembic history