1

I have an alembic migration script and I want to add some exception handling but not sure what is the best practice.

Basically, I have several issues to handle:

  1. A change was already made and not needed (e.g. if I try to add_column, and this column already exists, I want it to continue)
  2. A table is locked (if I try to perform some operation on a table and it is locked, I want to raise an exception)
  3. other exceptions?

    def upgrade():
        engine = op.get_bind().engine
        op.add_column('t_break_employee', sa.Column('auto', sa.Boolean()))
        op.add_column('t_employee', sa.Column('settings', sa.Text()))
    

I thought about adding a class to be used with the 'with' statement on every change. Does it sound reasonable?

for example:

    def upgrade():
        engine = op.get_bind().engine
        with my_test():
            op.add_column('t_break_employee', sa.Column('auto', sa.Boolean()))
        with my_test():
            op.add_column('t_employee', sa.Column('settings', sa.Text()))

In that case, what are the exceptions I need to handle and how do I know if a table is locked?

Ofir
  • 1,565
  • 3
  • 23
  • 41
  • 1
    The easiest way to find out is either to read the documentation, or set up some test cases and see what happens. – jonrsharpe Jun 06 '14 at 07:11

1 Answers1

1

I'm not refering to specific issues of the API you use, but I discourage you from this approach.

Really migration is something that has two two outcomes:

  • Migration did apply succesfully
  • Database is in state before migration (and hence there was some kind of error).

Proper way to deal with errors is to fix the migration. Your approach is allows third migration outcome:

  • Migration did fail but some changes were applied

This would result in schema corruption which is a bad thing!

jb.
  • 23,300
  • 18
  • 98
  • 136
  • Why would it result in a schema corruption? Suppose I need to do 3 changes, and 2 were already applied in the past. Making the third change would only bring my schema to the correct state ... – Ofir Jun 07 '14 at 07:04
  • First: if some changes are applied before migration run it means that your shema is already corrupded --- in the sense that it is not in a well-defined state. Secondly, exception might be raised for many other reasons other than change being alread applied... in this case you wouldn't know because errors would be suppressed. – jb. Jun 07 '14 at 07:55
  • 1
    My schema can get to that state from several irrelevant reasons. I'm trying to "fix" that state by applying only changes that were not yet made. Regarding other exceptions, I didn't say I want to handle all exceptions ... – Ofir Jun 08 '14 at 11:37