data_factory/service/env_ddl_service.py

54 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2025/3/24 19:56
# @Author : AngesZhu
# @File : env_ddl_service.py
# @Desc : 环境对比并生成对应的ddl
from utils.logger_utils import logger
from service.get_db_config import get_db_config
from utils.mysql_utils import MySQLHandler
from utils.postgresql_utils import PostgresHandler
def generate_sync_ddl(base_env, target_env, type_key):
# 对比两个库,记录数据库对比内容
base_config = get_db_config(base_env)
target_config = get_db_config(target_env)
# 判断
match type_key:
case "postgresql":
sql_config = base_config[type_key]
logger.debug(f"数据库配置: {sql_config}")
target_handler = PostgresHandler(**target_config[type_key])
base_tables = {}
target_tables = {}
case "mysql":
base_handler = MySQLHandler(**base_config[type_key])
target_handler = MySQLHandler(**target_config[type_key])
base_tables = base_handler.get_tables()
target_tables = target_handler.get_tables()
case _:
sql_config = {}
base_tables = {}
target_tables = {}
handler = None
ddl_script = []
# 找出目标库中多余的表(需要删除)
tables_to_drop = set(base_tables.keys()) - set(target_tables.keys())
for table in tables_to_drop:
ddl_script.append(f"DROP TABLE IF EXISTS `{table}`;")
# 比较共有表结构
common_tables = set(target_tables.keys()) & set(base_tables.keys())
for table in common_tables:
if target_tables[table] != base_tables[table]:
# 简单策略删除重建实际生产应使用ALTER语句
ddl_script.append(f"DROP TABLE IF EXISTS `{table}`;")
ddl_script.append(target_tables[table] + ";")
# 找出基础库中有但目标中没有的表(需要创建)
tables_to_create = set(target_tables.keys()) - set(base_tables.keys())
for table in tables_to_create:
ddl_script.append(target_tables[table] + ";")