# -*- coding: utf-8 -*-

from ppms import ppms
from ppms.migration import SQLPacket, PacketCategory
from ppms.constants import DBMS_ORACLE

class FixUuidFieldWidth(SQLPacket):
    """Reduce all UUID columns to their required width in Oracle
    """

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

    ora_statement_template = """begin
                                p_update_column_if_existing('{table}',
                                         '{column}',
                                         'alter table "{table}" modify ("{column}" raw(16))');
                                end;"""

    def fix(self, runner):
        if DBMS_ORACLE == ppms.db_get_dbms_name():
            return self.fix_uuid_fields()
        else:
            return self.success()


    def fix_uuid_fields(self):
        try:
            for di in ppms.get_data_dictionary().data_items.values():
                if di.db_type == 'ID':
                    alter_statement = self.ora_statement_template.format(table=di.table.sql_name, column=di.sql_name)
                    ppms.db_modify(alter_statement)
            return self.success()
        except ppms.DatabaseError as error:
            self.log("Error with statement:")
            self.log(alter_statement)
            return self.fail(error)