#!/usr/bin/env python3
#-*- coding:utf-8 -*-
try:
    import sys
    import importlib
    importlib.reload(sys)
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))


class CheckDropColumn(BaseItem):
    def __init__(self):
        super(CheckDropColumn, self).__init__(self.__class__.__name__)

    def doCheck(self):
        sql1 = """select a.relname, b.attname ,n.nspname||'.'||a.relname
         from pg_catalog.pg_class a, pg_catalog.pg_attribute b, pg_catalog.pg_namespace n
          where a.oid = b.attrelid and b.attisdropped and n.oid = a.relnamespace;"""
        sqldb = "select datname from pg_catalog.pg_database;"
        output = SharedFuncs.runSqlCmd(sqldb, self.user, "", self.port, self.tmpPath, "postgres", self.mpprcFile)
        dbList = output.split("\n")
        dbList.remove("template0")
        result = ""
        for db in dbList:
            output1 = SharedFuncs.runSqlSimplely(sql1, self.user, "", self.port, self.tmpPath, "postgres",
                                                 self.mpprcFile)
            if (output1.find("(0 rows)") < 0):
                result += "%s:\n%s\n" % (db, output1)
        if(result):
            self.result.val = "Alter table drop column operation is did in :\n%s" % result
            self.result.rst = ResultStatus.NG
            self.result.raw = sql1
        else:
            self.result.val = "No alter table drop column operation"
            self.result.rst = ResultStatus.OK
