import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))
from utils.ssh_util import SSHUtil
from utils.common_util import CommonUtil
from utils.db_util import DBUtil,DbTypes

if __name__ == '__main__':
    site_name = CommonUtil.get_sys_arg(1, None)

    db_type = DbTypes.postgresql.name
    print("导出到PG库中")

    export_master_tb = f"{site_name}_st_year_week"
    export_tb = f"{export_master_tb}_tmp"

    engine = DBUtil.get_db_engine(db_type, site_name)
    with engine.connect() as connection:
        sql = f"""
        drop table if exists {export_master_tb}_old;
        CREATE TABLE {export_tb} (LIKE {export_master_tb} INCLUDING ALL);
                """
        print("================================执行sql================================")
        print(sql)
        connection.execute(sql)

    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dim_st_year_week",
        export_tb=export_tb,
        col=[
            "search_term",
            "st_key",
            "year_week"
        ],
        partition_dict={
            "site_name": site_name
        }
    )

    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    client.close()

    engine = DBUtil.get_db_engine(db_type, site_name)
    with engine.connect() as connection:
        sql = f"""
        ALTER TABLE {export_master_tb} RENAME TO {export_master_tb}_old;
        ALTER TABLE {export_tb} RENAME TO {export_master_tb};
        """
        print("================================执行sql================================")
        print(sql)
        connection.execute(sql)

    print("success")
