데이터베이스 테이블의 컬럼 타입을 분석하여 용량 최적화 방안을 제시하는 파이썬 코드를 작성해드리겠습니다.
import mysql.connector
import pandas as pd
from collections import defaultdict
db_config = {
'host': 'localhost',
'user': 'root',
'password': '',
'database': 'norm_project_db'
}
def analyze_column_optimization():
try:
# 데이터베이스 연결
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor()
# 모든 테이블 목록 가져오기
cursor.execute("SHOW TABLES")
tables = [table[0] for table in cursor.fetchall()]
optimization_suggestions = []
for table_name in tables:
print(f"\n=== 테이블: {table_name} 분석 중... ===")
# 테이블 구조 정보 가져오기
cursor.execute(f"DESCRIBE {table_name}")
columns_info = cursor.fetchall()
# 테이블의 행 수 확인
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
row_count = cursor.fetchone()[0]
if row_count == 0:
print(f"테이블 {table_name}은 비어있습니다.")
continue
for column_info in columns_info:
column_name = column_info[0]
current_type = column_info[1]
is_nullable = column_info[2] == 'YES'
# 각 컬럼별 데이터 분석
suggestion = analyze_column(cursor, table_name, column_name, current_type, is_nullable, row_count)
if suggestion:
optimization_suggestions.append({
'table': table_name,
'column': column_name,
'current_type': current_type,
'suggested_type': suggestion['suggested_type'],
'reason': suggestion['reason'],
'potential_savings': suggestion['potential_savings']
})
# 결과 출력
print("\n" + "="*80)
print("컬럼 타입 최적화 제안사항")
print("="*80)
if not optimization_suggestions:
print("최적화 가능한 컬럼이 발견되지 않았습니다.")
else:
for suggestion in optimization_suggestions:
print(f"\n테이블: {suggestion['table']}")
print(f"컬럼: {suggestion['column']}")
print(f"현재 타입: {suggestion['current_type']}")
print(f"제안 타입: {suggestion['suggested_type']}")
print(f"이유: {suggestion['reason']}")
print(f"예상 절약: {suggestion['potential_savings']}")
print("-" * 50)
return optimization_suggestions
except mysql.connector.Error as err:
print(f"데이터베이스 오류: {err}")
return []
finally:
if 'conn' in locals():
conn.close()
def analyze_column(cursor, table_name, column_name, current_type, is_nullable, row_count):
"""개별 컬럼 분석 함수"""
try:
# 컬럼의 실제 데이터 분석
cursor.execute(f"""
SELECT
MIN(CHAR_LENGTH(CAST({column_name} AS CHAR))) as min_length,
MAX(CHAR_LENGTH(CAST({column_name} AS CHAR))) as max_length,
MIN({column_name}) as min_value,
MAX({column_name}) as max_value,
COUNT(DISTINCT {column_name}) as distinct_count,
COUNT(*) - COUNT({column_name}) as null_count
FROM {table_name}
""")
stats = cursor.fetchone()
min_length, max_length, min_value, max_value, distinct_count, null_count = stats
# 현재 타입 파싱
current_type_lower = current_type.lower()
# 정수형 컬럼 분석
if any(int_type in current_type_lower for int_type in ['int', 'bigint', 'smallint', 'tinyint', 'mediumint']):
return analyze_integer_column(current_type, min_value, max_value, null_count, row_count)
# 문자열 컬럼 분석
elif any(str_type in current_type_lower for str_type in ['varchar', 'char', 'text']):
return analyze_string_column(current_type, max_length, distinct_count, row_count)
# DECIMAL/FLOAT 컬럼 분석
elif any(dec_type in current_type_lower for dec_type in ['decimal', 'float', 'double']):
return analyze_decimal_column(cursor, table_name, column_name, current_type, min_value, max_value)
except Exception as e:
print(f"컬럼 {column_name} 분석 중 오류: {e}")
return None
def analyze_integer_column(current_type, min_value, max_value, null_count, row_count):
"""정수형 컬럼 최적화 분석"""
if min_value is None or max_value is None:
return None
current_type_lower = current_type.lower()
# 현재 타입별 바이트 크기
type_sizes = {
'tinyint': 1,
'smallint': 2,
'mediumint': 3,
'int': 4,
'bigint': 8
}
# 값의 범위에 따른 최적 타입 결정
if -128 <= min_value <= 127 and 'tinyint' not in current_type_lower:
if 'unsigned' in current_type_lower and max_value <= 255:
suggested_type = 'TINYINT UNSIGNED'
elif min_value >= 0 and max_value <= 255:
suggested_type = 'TINYINT UNSIGNED'
else:
suggested_type = 'TINYINT'
current_size = get_current_int_size(current_type_lower)
savings = calculate_savings(current_size, 1, row_count)
return {
'suggested_type': suggested_type,
'reason': f'값 범위({min_value}~{max_value})가 TINYINT 범위에 적합',
'potential_savings': savings
}
elif -32768 <= min_value <= 32767 and 'smallint' not in current_type_lower and 'tinyint' not in current_type_lower:
if 'unsigned' in current_type_lower and max_value <= 65535:
suggested_type = 'SMALLINT UNSIGNED'
elif min_value >= 0 and max_value <= 65535:
suggested_type = 'SMALLINT UNSIGNED'
else:
suggested_type = 'SMALLINT'
current_size = get_current_int_size(current_type_lower)
if current_size > 2:
savings = calculate_savings(current_size, 2, row_count)
return {
'suggested_type': suggested_type,
'reason': f'값 범위({min_value}~{max_value})가 SMALLINT 범위에 적합',
'potential_savings': savings
}
return None
def analyze_string_column(current_type, max_length, distinct_count, row_count):
"""문자열 컬럼 최적화 분석"""
if max_length is None:
return None
current_type_lower = current_type.lower()
# VARCHAR 길이 최적화
if 'varchar' in current_type_lower:
# 현재 VARCHAR 길이 추출
import re
match = re.search(r'varchar\((\d+)\)', current_type_lower)
if match:
current_length = int(match.group(1))
# 실제 최대 길이보다 현재 설정이 훨씬 큰 경우
if max_length < current_length * 0.7: # 70% 이하로 사용하는 경우
suggested_length = max(max_length + 10, 50) # 여유분 추가
suggested_type = f'VARCHAR({suggested_length})'
# 대략적인 절약 계산 (가변길이이므로 정확하지 않음)
avg_savings_per_row = (current_length - suggested_length) * 0.3 # 추정
total_savings = avg_savings_per_row * row_count
return {
'suggested_type': suggested_type,
'reason': f'실제 최대 길이({max_length})가 설정된 길이({current_length})보다 훨씬 작음',
'potential_savings': f'약 {total_savings/1024:.1f}KB 절약 가능 (추정)'
}
# TEXT 타입 최적화
elif 'text' in current_type_lower:
if max_length <= 255:
return {
'suggested_type': f'VARCHAR({max_length + 10})',
'reason': f'최대 길이({max_length})가 VARCHAR로 충분함',
'potential_savings': 'TEXT 오버헤드 제거로 성능 향상'
}
return None
def analyze_decimal_column(cursor, table_name, column_name, current_type, min_value, max_value):
"""DECIMAL/FLOAT 컬럼 최적화 분석"""
if min_value is None or max_value is None:
return None
# 소수점 자릿수 확인
try:
cursor.execute(f"""
SELECT MAX(
CHAR_LENGTH(
SUBSTRING_INDEX(CAST({column_name} AS CHAR), '.', -1)
)
) as max_decimal_places
FROM {table_name}
WHERE {column_name} LIKE '%.%'
""")
result = cursor.fetchone()
max_decimal_places = result[0] if result[0] is not None else 0
# 정수 부분의 자릿수 계산
max_integer_digits = len(str(int(abs(max(abs(min_value), abs(max_value))))))
current_type_lower = current_type.lower()
if 'decimal' in current_type_lower:
# 현재 DECIMAL 정밀도 추출
import re
match = re.search(r'decimal\((\d+),(\d+)\)', current_type_lower)
if match:
current_precision = int(match.group(1))
current_scale = int(match.group(2))
optimal_precision = max_integer_digits + max_decimal_places
optimal_scale = max_decimal_places
if optimal_precision < current_precision or optimal_scale < current_scale:
return {
'suggested_type': f'DECIMAL({optimal_precision},{optimal_scale})',
'reason': f'실제 필요 정밀도({optimal_precision},{optimal_scale})가 현재 설정보다 작음',
'potential_savings': f'DECIMAL 저장공간 최적화'
}
except Exception as e:
print(f"DECIMAL 분석 중 오류: {e}")
return None
def get_current_int_size(current_type_lower):
"""현재 정수 타입의 바이트 크기 반환"""
if 'bigint' in current_type_lower:
return 8
elif 'int' in current_type_lower:
return 4
elif 'mediumint' in current_type_lower:
return 3
elif 'smallint' in current_type_lower:
return 2
elif 'tinyint' in current_type_lower:
return 1
return 4 # 기본값
def calculate_savings(current_bytes, suggested_bytes, row_count):
"""절약 가능한 용량 계산"""
savings_per_row = current_bytes - suggested_bytes
total_savings = savings_per_row * row_count
if total_savings >= 1024 * 1024:
return f"{total_savings / (1024 * 1024):.1f}MB"
elif total_savings >= 1024:
return f"{total_savings / 1024:.1f}KB"
else:
return f"{total_savings}B"
# 실행
if __name__ == "__main__":
suggestions = analyze_column_optimization()
# 최적화 SQL 생성
if suggestions:
print("\n" + "="*80)
print("최적화 SQL 명령어")
print("="*80)
for suggestion in suggestions:
print(f"ALTER TABLE {suggestion['table']} MODIFY COLUMN {suggestion['column']} {suggestion['suggested_type']};")
이 코드는 다음과 같은 기능을 제공합니다:
주요 분석 항목:
- 정수형 컬럼: 실제 값의 범위를 분석하여 더 작은 정수 타입 제안
- 문자열 컬럼: VARCHAR 길이 최적화, TEXT를 VARCHAR로 변경 제안
- DECIMAL 컬럼: 실제 필요한 정밀도에 맞춰 크기 조정 제안
출력 정보:
- 테이블별, 컬럼별 최적화 제안
- 현재 타입과 제안 타입 비교
- 최적화 이유 설명
- 예상 절약 용량
- 실행 가능한 ALTER TABLE SQL 명령어
사용 전 주의사항:
- 실제 운영 환경에서는 백업 후 실행하세요
- 제안된 변경사항을 검토한 후 적용하세요
- 인덱스가 있는 컬럼의 경우 재생성이 필요할 수 있습니다
코드를 실행하면 데이터베이스의 모든 테이블을 분석하여 용량 최적화가 가능한 컬럼들을 찾아 구체적인 개선 방안을 제시해드립니다.