MySQL 데이터베이스의 테이블과 컬럼을 분석하여 데이터 타입 최적화를 제안하는 Python 코드를 작성해드리겠습니다.
import mysql.connector
from mysql.connector import Error
import pandas as pd
from datetime import datetime
class DatabaseOptimizer:
def __init__(self, db_config):
self.db_config = db_config
self.connection = None
self.cursor = None
def connect(self):
"""데이터베이스 연결"""
try:
self.connection = mysql.connector.connect(**self.db_config)
self.cursor = self.connection.cursor(dictionary=True)
print(f"Successfully connected to database: {self.db_config['database']}")
return True
except Error as e:
print(f"Error connecting to database: {e}")
return False
def disconnect(self):
"""데이터베이스 연결 해제"""
if self.cursor:
self.cursor.close()
if self.connection and self.connection.is_connected():
self.connection.close()
print("Database connection closed")
def get_all_tables(self):
"""데이터베이스의 모든 테이블 목록 가져오기"""
query = "SHOW TABLES"
self.cursor.execute(query)
tables = [list(table.values())[0] for table in self.cursor.fetchall()]
return tables
def analyze_column(self, table_name, column_name, column_type, is_nullable):
"""개별 컬럼 분석 및 최적화 제안"""
recommendations = []
# 실제 데이터 분석을 위한 쿼리들
queries = {
'max_length': f"SELECT MAX(LENGTH(`{column_name}`)) as max_len FROM `{table_name}` WHERE `{column_name}` IS NOT NULL",
'min_value': f"SELECT MIN(`{column_name}`) as min_val FROM `{table_name}` WHERE `{column_name}` IS NOT NULL",
'max_value': f"SELECT MAX(`{column_name}`) as max_val FROM `{table_name}` WHERE `{column_name}` IS NOT NULL",
'distinct_count': f"SELECT COUNT(DISTINCT `{column_name}`) as distinct_cnt FROM `{table_name}`",
'null_count': f"SELECT COUNT(*) as null_cnt FROM `{table_name}` WHERE `{column_name}` IS NULL",
'total_count': f"SELECT COUNT(*) as total_cnt FROM `{table_name}`"
}
results = {}
for key, query in queries.items():
try:
self.cursor.execute(query)
result = self.cursor.fetchone()
results[key] = result[list(result.keys())[0]] if result else None
except:
results[key] = None
# VARCHAR 최적화
if 'varchar' in column_type.lower():
current_size = int(column_type.split('(')[1].split(')')[0])
max_length = results.get('max_length', 0) or 0
if max_length > 0 and max_length < current_size:
if max_length <= 255:
recommendations.append({
'current': column_type,
'suggested': f'VARCHAR({int(max_length * 1.2)})', # 20% 여유
'reason': f'Current max length is {max_length}, can reduce from VARCHAR({current_size})',
'space_saving': 'High'
})
# INT 타입 최적화
elif column_type.lower() in ['int', 'integer', 'bigint', 'mediumint', 'smallint', 'tinyint']:
min_val = results.get('min_value')
max_val = results.get('max_value')
if min_val is not None and max_val is not None:
# 양수만 있는 경우 UNSIGNED 제안
if min_val >= 0:
if max_val <= 255:
recommendations.append({
'current': column_type,
'suggested': 'TINYINT UNSIGNED',
'reason': f'Values range from {min_val} to {max_val}',
'space_saving': 'Very High'
})
elif max_val <= 65535:
recommendations.append({
'current': column_type,
'suggested': 'SMALLINT UNSIGNED',
'reason': f'Values range from {min_val} to {max_val}',
'space_saving': 'High'
})
elif max_val <= 16777215:
recommendations.append({
'current': column_type,
'suggested': 'MEDIUMINT UNSIGNED',
'reason': f'Values range from {min_val} to {max_val}',
'space_saving': 'Medium'
})
elif max_val <= 4294967295 and 'bigint' in column_type.lower():
recommendations.append({
'current': column_type,
'suggested': 'INT UNSIGNED',
'reason': f'Values range from {min_val} to {max_val}',
'space_saving': 'Medium'
})
else:
# 음수 포함
if min_val >= -128 and max_val <= 127:
recommendations.append({
'current': column_type,
'suggested': 'TINYINT',
'reason': f'Values range from {min_val} to {max_val}',
'space_saving': 'Very High'
})
elif min_val >= -32768 and max_val <= 32767:
recommendations.append({
'current': column_type,
'suggested': 'SMALLINT',
'reason': f'Values range from {min_val} to {max_val}',
'space_saving': 'High'
})
elif min_val >= -8388608 and max_val <= 8388607:
recommendations.append({
'current': column_type,
'suggested': 'MEDIUMINT',
'reason': f'Values range from {min_val} to {max_val}',
'space_saving': 'Medium'
})
# TEXT to VARCHAR 최적화
elif column_type.lower() in ['text', 'mediumtext', 'longtext']:
max_length = results.get('max_length', 0) or 0
if max_length > 0 and max_length <= 65535:
if max_length <= 255:
recommendations.append({
'current': column_type,
'suggested': f'VARCHAR({int(max_length * 1.2)})',
'reason': f'Max length is only {max_length}, TEXT type is overkill',
'space_saving': 'Very High'
})
else:
recommendations.append({
'current': column_type,
'suggested': f'VARCHAR({min(int(max_length * 1.2), 65535)})',
'reason': f'Max length is {max_length}, can use VARCHAR instead of TEXT',
'space_saving': 'High'
})
# DECIMAL 최적화
elif 'decimal' in column_type.lower():
# 실제 소수점 자리수 확인
try:
self.cursor.execute(f"""
SELECT MAX(LENGTH(SUBSTRING_INDEX(`{column_name}`, '.', -1))) as max_decimal_places
FROM `{table_name}`
WHERE `{column_name}` IS NOT NULL AND `{column_name}` LIKE '%.%'
""")
result = self.cursor.fetchone()
max_decimal_places = result['max_decimal_places'] if result['max_decimal_places'] else 0
current_precision = column_type.split('(')[1].split(',')[0]
current_scale = column_type.split(',')[1].split(')')[0]
if max_decimal_places < int(current_scale):
recommendations.append({
'current': column_type,
'suggested': f'DECIMAL({current_precision},{max_decimal_places})',
'reason': f'Maximum decimal places used is {max_decimal_places}',
'space_saving': 'Medium'
})
except:
pass
# ENUM 제안 (distinct 값이 적은 경우)
distinct_count = results.get('distinct_count', 0)
total_count = results.get('total_count', 0)
if distinct_count and total_count and distinct_count <= 20 and total_count > 100:
if 'varchar' in column_type.lower() or 'char' in column_type.lower():
try:
self.cursor.execute(f"SELECT DISTINCT `{column_name}` FROM `{table_name}` WHERE `{column_name}` IS NOT NULL LIMIT 20")
distinct_values = [row[column_name] for row in self.cursor.fetchall()]
if all(isinstance(v, str) and len(v) < 64 for v in distinct_values):
enum_values = "','".join(str(v).replace("'", "''") for v in distinct_values)
recommendations.append({
'current': column_type,
'suggested': f"ENUM('{enum_values}')",
'reason': f'Only {distinct_count} distinct values found',
'space_saving': 'High'
})
except:
pass
return recommendations
def analyze_database(self):
"""전체 데이터베이스 분석"""
if not self.connect():
return
all_recommendations = []
tables = self.get_all_tables()
print(f"\nAnalyzing {len(tables)} tables in database '{self.db_config['database']}'...\n")
for table in tables:
print(f"Analyzing table: {table}")
# 테이블의 컬럼 정보 가져오기
self.cursor.execute(f"SHOW COLUMNS FROM `{table}`")
columns = self.cursor.fetchall()
for column in columns:
column_name = column['Field']
column_type = column['Type']
is_nullable = column['Null'] == 'YES'
recommendations = self.analyze_column(table, column_name, column_type, is_nullable)
for rec in recommendations:
rec['table'] = table
rec['column'] = column_name
all_recommendations.append(rec)
self.disconnect()
return all_recommendations
def generate_report(self, recommendations):
"""최적화 보고서 생성"""
if not recommendations:
print("\nNo optimization recommendations found. Your database schema appears to be well-optimized!")
return
print("\n" + "="*80)
print("DATABASE OPTIMIZATION REPORT")
print("="*80)
print(f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Database: {self.db_config['database']}")
print(f"Total recommendations: {len(recommendations)}")
print("="*80 + "\n")
# 테이블별로 그룹화
df = pd.DataFrame(recommendations)
grouped = df.groupby('table')
for table, group in grouped:
print(f"\nTable: {table}")
print("-" * 60)
for _, rec in group.iterrows():
print(f"\nColumn: {rec['column']}")
print(f"Current Type: {rec['current']}")
print(f"Suggested Type: {rec['suggested']}")
print(f"Reason: {rec['reason']}")
print(f"Expected Space Saving: {rec['space_saving']}")
print(f"ALTER TABLE `{table}` MODIFY COLUMN `{rec['column']}` {rec['suggested']};")
# 요약 통계
print("\n" + "="*80)
print("SUMMARY")
print("="*80)
space_saving_counts = df['space_saving'].value_counts()
print("\nOptimization Impact Distribution:")
for impact, count in space_saving_counts.items():
print(f" {impact}: {count} columns")
# CSV 파일로 저장
filename = f"db_optimization_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
df.to_csv(filename, index=False)
print(f"\nDetailed report saved to: {filename}")
# 사용 예제
if __name__ == "__main__":
db_config = {
'host': 'localhost',
'user': 'root',
'password': '', # 비밀번호가 있다면 여기에 입력하세요
'database': 'norm_project_db'
}
optimizer = DatabaseOptimizer(db_config)
recommendations = optimizer.analyze_database()
optimizer.generate_report(recommendations)
이 코드는 다음과 같은 기능을 제공합니다:
-
데이터베이스 전체 스캔: 모든 테이블과 컬럼을 자동으로 분석합니다.
-
다양한 최적화 제안:
- VARCHAR 길이 최적화
- INT 타입 크기 최적화 (TINYINT, SMALLINT, MEDIUMINT 등)
- UNSIGNED 타입 제안
- TEXT를 VARCHAR로 변경
- DECIMAL 정밀도 최적화
- ENUM 타입 제안 (반복되는 값이 적을 때)
-
상세한 분석 보고서:
- 각 컬럼별 현재 타입과 제안 타입
- 변경 이유와 예상 공간 절약 효과
- 즉시 실행 가능한 ALTER TABLE 명령어
-
CSV 파일 저장: 분석 결과를 CSV 파일로 저장하여 추후 검토 가능
코드를 실행하면 데이터베이스의 모든 테이블을 분석하고, 용량을 줄일 수 있는 컬럼들과 구체적인 변경 방법을 제시합니다.