# -*- coding: utf-8 -*-
from ppms import ppms
from ppms.constants import *
from ppms.migration.packet import *


DBMS = ppms.db_get_dbms_name()

class UpdateRelationType(SQLPacket):
    '''Update faulty relation types.

    Several relations had a customizing that lead to
    wrong relation types and keys (1:1 instead of N:1).
    '''

    wi_number = 10354
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY

    UPDATE_DT877_VARIABLE_NAME = """UPDATE DT416 SET DI000951 = 'ID877' WHERE DI000389 = DI000277 AND DI000951 = 'DT877'"""
    UPDATE_ALL_RELATIONS = {DBMS_ORACLE: """UPDATE DT416 SET DI000374 = '2', DI000279 = 'N:1' WHERE DI001891 IN {0} AND DI000389 = DI000277 AND NOT DI000951 = 'ID' || DI000277""".format(PLANTA_LICENSES),
                            DBMS_MSSQL: """UPDATE DT416 SET DI000374 = '2', DI000279 = 'N:1' WHERE DI001891 IN {0} AND DI000389 = DI000277 AND NOT DI000951 = 'ID' + DI000277""".format(PLANTA_LICENSES)}

    def fix(self, runner):
        failures = 0
        if not self.modify_and_log(self.UPDATE_DT877_VARIABLE_NAME):
            failures += 1

        if self.modify_and_log(self.UPDATE_ALL_RELATIONS[DBMS]):
            return self.success()

        if failures:
            return self.fail()

        return self.fail()
