MySQL 데이터베이스 컬럼 타입 최적화 분석 코드
다음은 주어진 데이터베이스 연결 정보를 사용해 모든 테이블의 컬럼을 분석하고, 타입 변경으로 용량을 줄일 수 있는 컬럼을 찾아내는 파이썬 코드입니다.
import mysql.connector
from mysql.connector import Error
def analyze_columns_for_optimization(db_config):
try:
# 데이터베이스 연결
connection = mysql.connector.connect(**db_config)
cursor = connection.cursor(dictionary=True)
# 모든 테이블 조회
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
print(f"Analyzing database: {db_config['database']}")
print("="*60)
for table in tables:
table_name = table[f"Tables_in_{db_config['database']}"]
print(f"\nTable: {table_name}")
print("-"*50)
# 테이블의 컬럼 정보 조회
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:
col_name = column['Field']
col_type = column['Type']
nullable = "YES" if column['Null'] == "YES" else "NO"
# 컬럼의 실제 데이터 분포 분석
cursor.execute(f"""
SELECT
MIN({col_name}) as min_val,
MAX({col_name}) as max_val,
COUNT(DISTINCT {col_name}) as distinct_count,
SUM(CASE WHEN {col_name} IS NULL THEN 1 ELSE 0 END) as null_count
FROM {table_name}
""")
stats = cursor.fetchone()
# 최적화 가능한 타입 추천
recommendations = []
current_type = col_type.upper()
# 정수형 컬럼 분석
if 'INT' in current_type:
min_val = stats['min_val']
max_val = stats['max_val']
if min_val is not None and max_val is not None:
if 'BIGINT' in current_type and max_val <= 2147483647 and min_val >= -2147483648:
recommendations.append("INT")
if 'INT' in current_type and max_val <= 32767 and min_val >= -32768:
recommendations.append("SMALLINT")
if 'INT' in current_type and max_val <= 127 and min_val >= -128:
recommendations.append("TINYINT")
if 'INT' in current_type and max_val <= 16777215 and min_val >= 0:
recommendations.append("MEDIUMINT UNSIGNED")
# 문자열 컬럼 분석
elif 'CHAR' in current_type or 'TEXT' in current_type:
# 최대 길이 분석
cursor.execute(f"""
SELECT MAX(LENGTH({col_name})) as max_length
FROM {table_name}
WHERE {col_name} IS NOT NULL
""")
max_length = cursor.fetchone()['max_length']
if max_length is not None:
if 'TEXT' in current_type and max_length <= 255:
recommendations.append("VARCHAR(255)")
elif 'VARCHAR' in current_type:
current_max = int(current_type.split('(')[1].split(')')[0])
if max_length < current_max:
recommendations.append(f"VARCHAR({max_length})")
# ENUM 타입으로 변경 가능한지 확인 (낮은 카디널리티 문자열)
if ('CHAR' in current_type or 'TEXT' in current_type) and stats['distinct_count'] <= 10 and stats['distinct_count'] > 0:
cursor.execute(f"SELECT DISTINCT {col_name} FROM {table_name} WHERE {col_name} IS NOT NULL")
distinct_values = [str(row[col_name]) for row in cursor.fetchall()]
enum_values = "','".join(distinct_values)
recommendations.append(f"ENUM('{enum_values}')")
# NULL 허용 여부 확인
if nullable == "YES" and stats['null_count'] == 0:
recommendations.append("NOT NULL")
# 결과 출력
print(f"Column: {col_name}")
print(f"Current Type: {col_type} ({nullable})")
print(f"Rows: {row_count:,}, Distinct: {stats['distinct_count']:,}, Nulls: {stats['null_count']:,}")
if 'INT' in current_type:
print(f"Min: {stats['min_val']}, Max: {stats['max_val']}")
elif 'CHAR' in current_type or 'TEXT' in current_type:
print(f"Max Length: {max_length}")
if recommendations:
print("Optimization Recommendations:")
for rec in recommendations:
print(f" - Change to {rec}")
else:
print("No optimization recommendations")
print()
except Error as e:
print(f"Database error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
# 데이터베이스 설정
db_config = {
'host': 'localhost',
'user': 'root',
'password': '', # 비밀번호가 있다면 여기에 입력하세요
'database': 'norm_project_db'
}
# 분석 실행
analyze_columns_for_optimization(db_config)
코드 설명
- 데이터베이스 연결: 주어진 설정으로 MySQL에 연결합니다.
- 테이블 목록 조회: 데이터베이스의 모든 테이블을 가져옵니다.
- 컬럼 분석: 각 테이블의 컬럼을 분석합니다.
- 데이터 통계 수집: 각 컬럼의 최소값, 최대값, 고유값 수, NULL 수 등을 조사합니다.
- 최적화 권장사항 생성:
- 정수형 컬럼: 실제 사용 범위에 맞춰 더 작은 타입으로 변경 제안
- 문자열 컬럼: 실제 최대 길이에 맞춰 VARCHAR 크기 조정 또는 ENUM 타입으로 변경 제안
- NULL 허용: NULL 값이 없는 컬럼은 NOT NULL로 변경 제안
- 결과 출력: 각 컬럼의 현재 상태와 최적화 제안 사항을 출력합니다.
사용 방법
-
위 코드를 실행하기 전에 mysql-connector-python 패키지가 설치되어 있어야 합니다:
pip install mysql-connector-python
-
db_config 딕셔너리에 실제 데이터베이스 연결 정보를 입력합니다.
-
스크립트를 실행하면 모든 테이블과 컬럼을 분석한 후 최적화 가능한 부분을 제안해줍니다.
이 코드는 실제 데이터 분포를 기반으로 타입 최적화를 제안하므로, 변경 전에 항상 백업을 하고 테스트 환경에서 검증하는 것이 좋습니다.