#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2023/4/4 18:33 # @Author : old tom # @File : connector_factory.py # @Project : futool-db # @Desc : 连接器工厂 import hashlib from common.fudb.connectors.dialect.dialect_connector import OracleConnector, PostgresqlConnector from datahub.datasource.constant import ds_conf_param from urllib.parse import quote_plus as urlquote from common.fudb.connectors.connector_cache import connector_cache class ConnFactory(object): """ 数据库连接器工厂 """ CONNECTION_CONTAINER = { 'oracle': OracleConnector, 'postgresql': PostgresqlConnector } def __init__(self, conf: ds_conf_param): self.db_type = conf.db_type # 生成连接ID self.connector_id = self._gen_connector_id(conf.db_type, conf.user, conf.password, conf.host, conf.port, conf.database) # 尝试从缓存获取 if connector_cache.exist(self.connector_id) and connector_cache.get(self.connector_id): self.connector = connector_cache.get(self.connector_id) else: # urlquote 用于处理密码中的特殊字符例如@ self.connector = self.CONNECTION_CONTAINER[self.db_type](conf.user, urlquote(conf.password), conf.host, conf.port, conf.database) connector_cache.set(self.connector_id, self.connector) def get_conn(self): """ 获取连接 :return: """ return self.connector.get_conn() @staticmethod def _gen_connector_id(db_type, user, password, host, port, database): # 保证相同输入下MD5计算结果一致 md5 = hashlib.md5() md5.update( (db_type + user + password + host + str(port) + password + database).encode(encoding='utf-8')) return md5.hexdigest()