#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File     : database
# @Author   : LiuYan
# @Time     : 2021/9/14 17:51

import pymysql


class DatabaseMySQL(object):
    def __init__(self, database_config: dict):
        super(DatabaseMySQL, self).__init__()
        self._conn = None
        self._cursor = None
        self._database_config = database_config
        self._connect()

    def _connect(self) -> None:
        self._database_config['port'] = int(self._database_config['port'])
        self._database_config['charset'] = 'utf8'
        self._database_config['cursorclass'] = pymysql.cursors.DictCursor
        self._conn = pymysql.connect(**self._database_config)
        self._cursor = self._conn.cursor()

    def query(self, sql: str) -> list:
        # 获取表单信息
        print('SQL: {}'.format(sql))
        self._cursor.execute(sql)
        list_result = self._cursor.fetchall()
        return list_result

    def close(self) -> None:
        self._cursor.close()
        self._conn.close()

    def is_connected(self):
        """Check if the server is alive"""
        try:
            self.conn.ping(reconnect=True)
            print("db is connecting")
        except Exception:
            self.conn = self._connect()
            print("db reconnect")


if __name__ == '__main__':
    database_config = {
        'host': '114.115.159.144',
        'port': 3306,
        'user': 'root',
        'password': 'zzsn9988',
        'database': 'clb_project'
    }
    dbm = DatabaseMySQL(database_config=database_config)
 #    sql = """select ds.data_source_name,ds.url,ds.params,ds.type,ds.data_name from clb_report_data_source ds inner join clb_report_data_set_source_map m on ds.id = m.data_source_id
 # where m.data_set_id = '1641045122365317122'
 #    """
    task_id = '1641261934625521666'
#
    sql = '''SELECT ds.id,ds.param_value,te.file_path FROM clb_report_task t inner join clb_report_template te on t.template_id = te.id
inner join clb_report_data_set ds on te.data_set_id = ds.id
 where t.id  = {};'''.format(task_id)
    list_result = dbm.query(sql=sql)
    print(list_result)
    dbm.close()
