아래는 MySQL 데이터베이스에서 테이블의 컬럼들을 분석하여 용량을 줄일 수 있는 컬럼과 타입 변경 권장 사항을 제공하는 파이썬 스크립트입니다.
python
import mysql.connector
from mysql.connector import Error
def analyze_database_for_optimization(db_config):
try:
# 데이터베이스 연결
connection = mysql.connector.connect(**db_config)
if connection.is_connected():
cursor = connection.cursor(dictionary=True)
# 데이터베이스 내 모든 테이블 조회
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
optimization_suggestions = []
for table in tables:
table_name = list(table.values())[0]
# 각 테이블의 컬럼 정보 조회
cursor.execute(f"SHOW COLUMNS FROM {table_name}")
columns = cursor.fetchall()
# 테이블의 행 수 조회
cursor.execute(f"SELECT COUNT(*) as row_count FROM {table_name}")
row_count = cursor.fetchone()['row_count']
for column in columns:
column_name = column['Field']
column_type = column['Type']
is_nullable = column['Null'] == 'YES'
max_length = None
avg_length = None
# 문자열 타입인 경우 길이 분석
if column_type.startswith(('varchar', 'char', 'text', 'tinytext', 'mediumtext', 'longtext')):
# 최대 길이 조회
cursor.execute(f"""
SELECT MAX(CHAR_LENGTH({column_name})) as max_length
FROM {table_name}
""")
max_length_result = cursor.fetchone()
max_length = max_length_result['max_length'] if max_length_result['max_length'] else 0
# 평균 길이 조회
cursor.execute(f"""
SELECT AVG(CHAR_LENGTH({column_name})) as avg_length
FROM {table_name}
""")
avg_length_result = cursor.fetchone()
avg_length = avg_length_result['avg_length'] if avg_length_result['avg_length'] else 0
# 현재 타입의 최대 길이
current_max_length = int(column_type.split('(')[1].split(')')[0]) if '(' in column_type and ')' in column_type else None
# 최적화 제안 생성
if current_max_length and max_length and max_length < current_max_length * 0.7:
# 현재 길이의 70% 미만만 사용 중인 경우
new_length = int(max_length * 1.2) # 20% 여유를 두고 설정
if new_length < current_max_length:
suggestion = {
'table': table_name,
'column': column_name,
'current_type': column_type,
'suggested_type': f"VARCHAR({new_length})",
'reason': f"현재 최대 길이 {max_length}로 현재 타입의 {current_max_length}보다 작음",
'row_count': row_count,
'max_length': max_length,
'avg_length': avg_length
}
optimization_suggestions.append(suggestion)
# 숫자 타입인 경우 분석
elif column_type.startswith(('int', 'bigint', 'smallint', 'tinyint', 'decimal', 'float', 'double')):
# 숫자 범위 분석
cursor.execute(f"""
SELECT MIN({column_name}) as min_value, MAX({column_name}) as max_value
FROM {table_name}
""")
range_result = cursor.fetchone()
min_value = range_result['min_value']
max_value = range_result['max_value']
# 현재 타입 분석
if column_type.startswith('int'):
if max_value is not None and max_value <= 2147483647:
if column_type == 'bigint':
suggestion = {
'table': table_name,
'column': column_name,
'current_type': column_type,
'suggested_type': 'INT',
'reason': f"최대값 {max_value}가 INT 범위 내에 있음",
'row_count': row_count
}
optimization_suggestions.append(suggestion)
elif max_value is not None and max_value <= 65535:
if column_type in ('int', 'bigint'):
suggestion = {
'table': table_name,
'column': column_name,
'current_type': column_type,
'suggested_type': 'SMALLINT',
'reason': f"최대값 {max_value}가 SMALLINT 범위 내에 있음",
'row_count': row_count
}
optimization_suggestions.append(suggestion)
elif max_value is not None and max_value <= 255:
if column_type in ('int', 'bigint', 'smallint'):
suggestion = {
'table': table_name,
'column': column_name,
'current_type': column_type,
'suggested_type': 'TINYINT',
'reason': f"최대값 {max_value}가 TINYINT 범위 내에 있음",
'row_count': row_count
}
optimization_suggestions.append(suggestion)
# 부동소수점 타입 분석
elif column_type.startswith(('decimal', 'float', 'double')):
# 실제 사용되는 소수점 자리수 분석
cursor.execute(f"""
SELECT {column_name} as value
FROM {table_name}
LIMIT 1000
""")
sample_values = cursor.fetchall()
decimal_places = 0
for row in sample_values:
value = row['value']
if value is not None:
decimal_str = str(value).split('.')
if len(decimal_str) > 1:
current_decimals = len(decimal_str[1])
if current_decimals > decimal_places:
decimal_places = current_decimals
if decimal_places < 2 and column_type.startswith('decimal'):
suggestion = {
'table': table_name,
'column': column_name,
'current_type': column_type,
'suggested_type': 'FLOAT',
'reason': f"소수점 자리수가 적어 FLOAT으로 충분함",
'row_count': row_count
}
optimization_suggestions.append(suggestion)
# 날짜/시간 타입 분석
elif column_type.startswith(('datetime', 'timestamp')):
# 실제 데이터 범위 분석
cursor.execute(f"""
SELECT MIN({column_name}) as min_date, MAX({column_name}) as max_date
FROM {table_name}
""")
date_range = cursor.fetchone()
if date_range['min_date'] and date_range['max_date']:
# 날짜 범위가 1년 이내인 경우 DATE 타입으로 변경 제안
min_date = date_range['min_date']
max_date = date_range['max_date']
if isinstance(min_date, str):
min_date = min_date[:10] # 날짜 부분만 추출
if isinstance(max_date, str):
max_date = max_date[:10]
if min_date and max_date and min_date[:4] == max_date[:4]:
suggestion = {
'table': table_name,
'column': column_name,
'current_type': column_type,
'suggested_type': 'DATE',
'reason': f"날짜 범위가 1년 이내로 DATE 타입으로 충분함",
'row_count': row_count
}
optimization_suggestions.append(suggestion)
# 결과 출력
print("\n데이터베이스 최적화 제안:")
print("=" * 80)
print(f"총 {len(optimization_suggestions)}개의 최적화 제안이 발견되었습니다.\n")
for suggestion in optimization_suggestions:
print(f"테이블: {suggestion['table']}")
print(f"컬럼: {suggestion['column']}")
print(f"현재 타입: {suggestion['current_type']}")
print(f"제안 타입: {suggestion['suggested_type']}")
print(f"이유: {suggestion['reason']}")
if 'max_length' in suggestion:
print(f"현재 최대 길이: {suggestion['max_length']}, 평균 길이: {suggestion['avg_length']:.2f}")
print(f"테이블 행 수: {suggestion['row_count']}")
print("-" * 60)
return optimization_suggestions
except Error as e:
print(f"MySQL 오류: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
# 데이터베이스 분석 실행
db_config = {
'host': 'localhost',
'user': 'root',
'password': '', # 비밀번호가 있다면 여기에 입력하세요
'database': 'norm_project_db'
}
optimization_suggestions = analyze_database_for_optimization(db_config)
스크립트 설명
이 스크립트는 다음과 같은 기능을 수행합니다:
문자열 타입 최적화:
VARCHAR, CHAR, TEXT 타입 컬럼의 실제 사용되는 최대 길이와 평균 길이를 분석
현재 정의된 길이보다 실제 사용되는 길이가 훨씬 짧은 경우 더 작은 길이로 변경 제안
숫자 타입 최적화:
INT, BIGINT, SMALLINT, TINYINT 타입의 실제 사용 범위 분석
더 작은 범위의 타입으로 변경 가능한 경우 제안 (예: BIGINT → INT, INT → SMALLINT 등)
부동소수점 타입 최적화:
DECIMAL, FLOAT, DOUBLE 타입의 실제 사용되는 소수점 자리수 분석
소수점 자리수가 적은 경우 더 간단한 타입으로 변경 제안
날짜/시간 타입 최적화:
DATETIME, TIMESTAMP 타입의 실제 데이터 범위 분석
날짜 범위가 좁은 경우 DATE 타입으로 변경 제안
주의사항
이 스크립트는 읽기 전용으로 동작하며 실제 데이터베이스 구조를 변경하지 않습니다.
제안된 변경 사항을 적용하기 전에 반드시 백업을 수행하세요.
일부 타입 변경은 데이터 손실을 일으킬 수 있으므로 신중하게 검토해야 합니다.
대용량 테이블의 경우 분석에 시간이 소요될 수 있습니다.
실제 적용 전에는 반드시 테스트 환경에서 검증해야 합니다.
이 스크립트를 실행하면 데이터베이스 내 모든 테이블의 컬럼을 분석하여 용량 최적화가 가능한 컬럼과 제안된 타입 변경 사항을 출력합니다.