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"✅ 데이터베이스 '{self.db_config['database']}'에 연결되었습니다.")
return True
except Error as e:
print(f"❌ 연결 오류: {e}")
return False
def disconnect(self):
"""데이터베이스 연결 해제"""
if self.cursor:
self.cursor.close()
if self.connection:
self.connection.close()
def get_all_tables(self):
"""모든 테이블 목록 조회"""
query = """
SELECT TABLE_NAME, TABLE_ROWS, DATA_LENGTH, INDEX_LENGTH
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = %s
"""
self.cursor.execute(query, (self.db_config['database'],))
return self.cursor.fetchall()
def analyze_column(self, table_name, column_name, data_type, column_type):
"""개별 컬럼 분석 및 최적화 제안"""
recommendations = []
# 실제 데이터 분석
if 'int' in data_type.lower():
recommendation = self.analyze_integer_column(table_name, column_name, column_type)
if recommendation:
recommendations.append(recommendation)
elif 'varchar' in data_type.lower():
recommendation = self.analyze_varchar_column(table_name, column_name, column_type)
if recommendation:
recommendations.append(recommendation)
elif 'text' in data_type.lower():
recommendation = self.analyze_text_column(table_name, column_name)
if recommendation:
recommendations.append(recommendation)
elif 'decimal' in data_type.lower() or 'numeric' in data_type.lower():
recommendation = self.analyze_decimal_column(table_name, column_name, column_type)
if recommendation:
recommendations.append(recommendation)
return recommendations
def analyze_integer_column(self, table_name, column_name, column_type):
"""정수형 컬럼 분석"""
try:
# 최대값과 최소값 확인
query = f"""
SELECT
MIN(`{column_name}`) as min_val,
MAX(`{column_name}`) as max_val,
COUNT(DISTINCT `{column_name}`) as distinct_count,
COUNT(*) as total_count
FROM `{table_name}`
WHERE `{column_name}` IS NOT NULL
"""
self.cursor.execute(query)
result = self.cursor.fetchone()
if not result or result['min_val'] is None:
return None
min_val = int(result['min_val'])
max_val = int(result['max_val'])
# 현재 타입 분석
current_type = column_type.upper()
# 최적 타입 결정
if min_val >= 0: # UNSIGNED 가능
if max_val <= 255:
optimal_type = "TINYINT UNSIGNED"
bytes_saved = self.get_int_bytes(current_type) - 1
elif max_val <= 65535:
optimal_type = "SMALLINT UNSIGNED"
bytes_saved = self.get_int_bytes(current_type) - 2
elif max_val <= 16777215:
optimal_type = "MEDIUMINT UNSIGNED"
bytes_saved = self.get_int_bytes(current_type) - 3
elif max_val <= 4294967295:
optimal_type = "INT UNSIGNED"
bytes_saved = self.get_int_bytes(current_type) - 4
else:
optimal_type = "BIGINT UNSIGNED"
bytes_saved = self.get_int_bytes(current_type) - 8
else: # SIGNED 필요
if min_val >= -128 and max_val <= 127:
optimal_type = "TINYINT"
bytes_saved = self.get_int_bytes(current_type) - 1
elif min_val >= -32768 and max_val <= 32767:
optimal_type = "SMALLINT"
bytes_saved = self.get_int_bytes(current_type) - 2
elif min_val >= -8388608 and max_val <= 8388607:
optimal_type = "MEDIUMINT"
bytes_saved = self.get_int_bytes(current_type) - 3
elif min_val >= -2147483648 and max_val <= 2147483647:
optimal_type = "INT"
bytes_saved = self.get_int_bytes(current_type) - 4
else:
optimal_type = "BIGINT"
bytes_saved = self.get_int_bytes(current_type) - 8
if bytes_saved > 0 and optimal_type.replace(' UNSIGNED', '') != current_type.replace(' UNSIGNED', '').split('(')[0]:
return {
'table': table_name,
'column': column_name,
'current_type': current_type,
'optimal_type': optimal_type,
'min_value': min_val,
'max_value': max_val,
'bytes_per_row_saved': bytes_saved,
'total_rows': result['total_count'],
'estimated_space_saved_mb': (bytes_saved * result['total_count']) / (1024 * 1024)
}
except Exception as e:
print(f"⚠️ {table_name}.{column_name} 분석 중 오류: {e}")
return None
def analyze_varchar_column(self, table_name, column_name, column_type):
"""VARCHAR 컬럼 분석"""
try:
# 최대 길이 확인
query = f"""
SELECT
MAX(CHAR_LENGTH(`{column_name}`)) as max_length,
AVG(CHAR_LENGTH(`{column_name}`)) as avg_length,
COUNT(*) as total_count,
COUNT(DISTINCT `{column_name}`) as distinct_count
FROM `{table_name}`
WHERE `{column_name}` IS NOT NULL
"""
self.cursor.execute(query)
result = self.cursor.fetchone()
if not result or result['max_length'] is None:
return None
# 현재 VARCHAR 크기 추출
import re
match = re.search(r'varchar\((\d+)\)', column_type.lower())
if not match:
return None
current_size = int(match.group(1))
max_length = int(result['max_length'])
avg_length = float(result['avg_length'])
# 최적화 제안
if max_length < current_size * 0.5: # 50% 미만 사용
optimal_size = min(max_length + 10, current_size) # 여유분 10 추가
# ENUM 가능성 체크
if result['distinct_count'] < 100 and result['distinct_count'] < result['total_count'] * 0.1:
# 고유값이 100개 미만이고 전체의 10% 미만인 경우 ENUM 제안
query = f"""
SELECT DISTINCT `{column_name}`
FROM `{table_name}`
WHERE `{column_name}` IS NOT NULL
LIMIT 20
"""
self.cursor.execute(query)
distinct_values = [row[column_name] for row in self.cursor.fetchall()]
return {
'table': table_name,
'column': column_name,
'current_type': column_type,
'optimal_type': f'VARCHAR({optimal_size}) 또는 ENUM',
'current_size': current_size,
'max_length_used': max_length,
'avg_length': round(avg_length, 2),
'distinct_count': result['distinct_count'],
'enum_suggestion': f"ENUM 가능 (고유값: {result['distinct_count']}개)",
'sample_values': distinct_values[:10]
}
else:
return {
'table': table_name,
'column': column_name,
'current_type': column_type,
'optimal_type': f'VARCHAR({optimal_size})',
'current_size': current_size,
'max_length_used': max_length,
'avg_length': round(avg_length, 2),
'space_reduction_percent': round((1 - optimal_size/current_size) * 100, 2)
}
except Exception as e:
print(f"⚠️ {table_name}.{column_name} 분석 중 오류: {e}")
return None
def analyze_text_column(self, table_name, column_name):
"""TEXT 컬럼 분석"""
try:
query = f"""
SELECT
MAX(CHAR_LENGTH(`{column_name}`)) as max_length,
AVG(CHAR_LENGTH(`{column_name}`)) as avg_length,
COUNT(*) as total_count
FROM `{table_name}`
WHERE `{column_name}` IS NOT NULL
"""
self.cursor.execute(query)
result = self.cursor.fetchone()
if not result or result['max_length'] is None:
return None
max_length = int(result['max_length'])
avg_length = float(result['avg_length'])
# TEXT 타입 최적화 제안
if max_length <= 255:
return {
'table': table_name,
'column': column_name,
'current_type': 'TEXT',
'optimal_type': f'VARCHAR({min(max_length + 20, 255)})',
'max_length_used': max_length,
'avg_length': round(avg_length, 2),
'recommendation': 'TEXT를 VARCHAR로 변경 가능'
}
elif max_length <= 65535:
return {
'table': table_name,
'column': column_name,
'current_type': 'TEXT',
'optimal_type': 'TEXT (유지)',
'max_length_used': max_length,
'avg_length': round(avg_length, 2),
'recommendation': '현재 타입이 적절함'
}
except Exception as e:
print(f"⚠️ {table_name}.{column_name} 분석 중 오류: {e}")
return None
def analyze_decimal_column(self, table_name, column_name, column_type):
"""DECIMAL 컬럼 분석"""
try:
query = f"""
SELECT
MIN(`{column_name}`) as min_val,
MAX(`{column_name}`) as max_val,
MAX(LENGTH(SUBSTRING_INDEX(`{column_name}`, '.', -1))) as max_decimal_places
FROM `{table_name}`
WHERE `{column_name}` IS NOT NULL
"""
self.cursor.execute(query)
result = self.cursor.fetchone()
if not result or result['min_val'] is None:
return None
# 소수점 이하 자릿수가 없으면 정수형 제안
if result['max_decimal_places'] == 0:
return {
'table': table_name,
'column': column_name,
'current_type': column_type,
'optimal_type': 'INT 또는 BIGINT',
'recommendation': '소수점 데이터가 없으므로 정수형 변환 가능'
}
except Exception as e:
print(f"⚠️ {table_name}.{column_name} 분석 중 오류: {e}")
return None
def get_int_bytes(self, column_type):
"""정수형 타입의 바이트 크기 반환"""
type_upper = column_type.upper().split('(')[0]
if 'TINYINT' in type_upper:
return 1
elif 'SMALLINT' in type_upper:
return 2
elif 'MEDIUMINT' in type_upper:
return 3
elif 'BIGINT' in type_upper:
return 8
else: # INT
return 4
def analyze_database(self):
"""전체 데이터베이스 분석"""
if not self.connect():
return
print(f"\n📊 데이터베이스 '{self.db_config['database']}' 분석 시작...\n")
tables = self.get_all_tables()
all_recommendations = []
for table in tables:
table_name = table['TABLE_NAME']
print(f"🔍 테이블 분석 중: {table_name}")
# 테이블의 모든 컬럼 정보 조회
query = """
SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
"""
self.cursor.execute(query, (self.db_config['database'], table_name))
columns = self.cursor.fetchall()
for column in columns:
recommendations = self.analyze_column(
table_name,
column['COLUMN_NAME'],
column['DATA_TYPE'],
column['COLUMN_TYPE']
)
if recommendations:
all_recommendations.extend(recommendations)
self.disconnect()
# 결과 출력
self.print_recommendations(all_recommendations)
return all_recommendations
def print_recommendations(self, recommendations):
"""최적화 제안 출력"""
print("\n" + "="*80)
print("📋 데이터베이스 최적화 제안 보고서")
print("="*80 + "\n")
if not recommendations:
print("✅ 최적화가 필요한