# -*- coding: utf-8 -*-
from ppms.migration import SQLPacket, PacketCategory, MinVersionDependency, MaxVersionDependency
from ppms import ppms
import os


class RemoveVersionColumn(SQLPacket):
    """Remove the version column from the migration rule table"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 15618

    def get_dependencies(self):
        return (MinVersionDependency(version='39.5.6'),
                MaxVersionDependency(version='39.5.6'))

    def fix(self, packet_runner):
        #this packet should run twice: as reload_server will restart the server,
        # we'll execute this packet again; it will then not reload and just succeed
        if self.column_exists('MIGRATIONRULE', 'VERSION'):
            self.drop_column(table_name='MIGRATIONRULE', column_name='VERSION')
            self.drop_column(table_name='MIGRATIONRULE_HIS', column_name='VERSION')

            # Explicitly tell hibernate to close the transaction
            ppms.db_commit()

            self.log('Reloading data dictionary because of column changes')

            # in windows, we get an assertion when the connection to the server is lost
            #  -> kill the session in this case, too! (using finally)
            try:
                ppms.reload_server()
            finally:
                # the session has to end immediately so it does not try to complete
                # this and following packets without being attached to a server
                os._exit(0)

        return self.success()
