from ppms.migration import PacketCategory, SQLPacket, MaxVersionDependency
from ppms.constants import *
from ppms import ppms


class EnableDT280PrimaryKey(SQLPacket):
    """Enables the primary constraint in dt280 which is required for the following migration packets, so they are able
     to create foreign keys onto this table.
    """
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 19923

    SQL_PROCEDURE = {DBMS_MSSQL: ['''ALTER TABLE "DT280" CHECK CONSTRAINT ALL''',
                                  '''ALTER TABLE "DT280" WITH CHECK CHECK CONSTRAINT ALL'''],
                     DBMS_ORACLE: ['''alter table "DT280" enable constraint "PID280DT280"''',
                                   '''alter table "DT280" enable validate constraint "PID280DT280"''']}

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

    def fix(self, runner):
        for statement in self.SQL_PROCEDURE[self.DBMS]:
            try:
                self.modify_and_log(statement)
            except ppms.DatabaseError:
                # most likly this is an update from a higher db version in which the constraints are named differently,
                # the packet is not necessary here so just ignore the error
                pass
        return self.success()
