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


class FixTablesWithoutPK(SQLPacket):
    '''Add PK to tables we know, point out further tables without PK on DB.

    Only modifies tables DT343, DT421, DT876, DT887.
    Other tables without PK will be reported in the log, please check them and
    manually set this packet to 'done' once they have been dealt with.
    '''
    wi_number = 14673
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY

    sql = {DBMS_MSSQL: ("""DROP INDEX PID343DT343
                             ON DT343""",
                        """ALTER TABLE DT343
                             ADD CONSTRAINT "PID343DT343" PRIMARY KEY ("DI024372", "DI024373")""",
                        """ALTER TABLE DT421
                             ALTER COLUMN DI040961 VARCHAR(16) NOT NULL""",
                        """ALTER TABLE DT421
                             ADD CONSTRAINT "PID421DT421" PRIMARY KEY ("DI040961")""",
                        """ALTER TABLE DT876
                             ADD CONSTRAINT "PID876DT876" PRIMARY KEY ("DI057880")""",
                        """ALTER TABLE DT887
                             ADD CONSTRAINT "PID887DT887" PRIMARY KEY ("DI056935")"""),
           DBMS_ORACLE: ("""ALTER TABLE DT343
                              ADD CONSTRAINT "PID343DT343" PRIMARY KEY ("DI024372", "DI024373")""",
                         """ALTER TABLE DT421
                              ADD CONSTRAINT "PID421DT421" PRIMARY KEY ("DI040961")""",
                         """ALTER TABLE DT876
                              ADD CONSTRAINT "PID876DT876" PRIMARY KEY ("DI057880")""",
                         """ALTER TABLE DT887
                              ADD CONSTRAINT "PID887DT887" PRIMARY KEY ("DI056935")""")}


    def get_dependencies(self):
        return (MaxVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING), )
    
    def fix(self, runner):
        for statement in self.sql[self.DBMS]:
            try:
                self.modify_and_log(statement)
            except ppms.DatabaseError as e:
                if ('ORA-02260' in str(e)) or ('sqlserver' in str(e)):
                    self.log("Skipped statement cause DT has already a primary key")
                else:
                    raise e
        
        return self.success()