使用Python编写一个程序,动态监测数据库表的DDL(数据定义语言)变更,并实时记录到日志文件中。
import pymysql
import logging
from threading import Timer
# 配置日志
logging.basicConfig(filename='ddl_changes.log', level=logging.INFO, format='%(asctime)s - %(message)s')
# 数据库连接配置
db_config = {
'host': 'localhost',
'user': 'root',
'password': 'password',
'database': 'test_db'
}
# 上一次检查时的表结构
last_table_structure = {}
def get_table_structure():
"""
获取当前数据库的表结构
:return: 表结构的字典,键为表名,值为表的列信息
"""
table_structure = {}
try:
conn = pymysql.connect(**db_config)
cursor = conn.cursor()
# 获取所有表名
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
for table in tables:
table_name = table[0]
# 获取表的列信息
cursor.execute(f"SHOW COLUMNS FROM {table_name}")
columns = cursor.fetchall()
table_structure[table_name] = [col[0] for col in columns] # 保存列名
cursor.close()
conn.close()
except Exception as e:
logging.error(f"获取表结构失败: {e}")
return table_structure
def monitor_ddl_changes():
"""
检查表结构是否发生变化,并记录变更到日志
"""
global last_table_structure
current_structure = get_table_structure()
# 如果是第一次运行,直接更新记录
if not last_table_structure:
last_table_structure = current_structure
Timer(60, monitor_ddl_changes).start() # 60秒后再次检查
return
# 检查新增的表
new_tables = set(current_structure.keys()) - set(last_table_structure.keys())
for table in new_tables:
logging.info(f"新增表: {table}, 列结构: {current_structure[table]}")
# 检查删除的表
deleted_tables = set(last_table_structure.keys()) - set(current_structure.keys())
for table in deleted_tables:
logging.info(f"删除表: {table}")
# 检查表的列变更
common_tables = set(current_structure.keys()) & set(last_table_structure.keys())
for table in common_tables:
current_columns = current_structure[table]
last_columns = last_table_structure[table]
# 检查新增的列
new_columns = set(current_columns) - set(last_columns)
if new_columns:
logging.info(f"表 {table} 新增列: {list(new_columns)}")
# 检查删除的列
deleted_columns = set(last_columns) - set(current_columns)
if deleted_columns:
logging.info(f"表 {table} 删除列: {list(deleted_columns)}")
# 更新记录
last_table_structure = current_structure
Timer(60, monitor_ddl_changes).start() # 60秒后再次检查
if __name__ == "__main__":
monitor_ddl_changes()
代码解析
-
日志配置
- 使用
logging模块配置日志文件ddl_changes.log,记录所有 DDL 变更。
- 使用
-
数据库连接
- 使用
pymysql连接数据库,通过SHOW TABLES和SHOW COLUMNS命令获取表结构信息。
- 使用
-
动态监测
- 通过
Timer实现每隔 60 秒检查一次表结构的变化。 - 比较当前表结构和上一次的表结构,检测新增表、删除表、新增列和删除列等变更。
- 通过
-
变更记录
- 将检测到的变更实时记录到日志文件中,包括新增表、删除表、新增列和删除列的详细信息。
示例输出
日志文件中可能记录的内容如下:
2023-10-01 12:00:00 - 新增表: users, 列结构: ['id', 'name', 'email']
2023-10-01 12:01:00 - 表 users 新增列: ['age']
2023-10-01 12:02:00 - 删除表: temp_data
注意事项
- 程序需要持续运行,可以通过
nohup或容器化部署实现后台运行。 - 数据库配置(如用户名、密码)需根据实际情况修改。
- 检查间隔(60秒)可以根据需求调整。
- 如果数据库表结构变化频繁,建议缩短检查间隔以提高实时性。