다음은 주어진 데이터베이스 연결 정보를 사용해 모든 테이블의 컬럼을 분석하고, 타입 변경으로 용량을 줄일 수 있는 컬럼을 찾아내는 파이썬 코드입니다.
python
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()
# 최적화 가능성 분석
suggestions = analyze_column(col_type, stats, row_count)
# 결과 출력
print(f"Column: {col_name}")
print(f"Current Type: {col_type}, Nullable: {nullable}")
print(f"Min: {stats['min_val']}, Max: {stats['max_val']}, Distinct: {stats['distinct_count']}, Nulls: {stats['null_count']}")
if suggestions:
print("Optimization Suggestions:")
for suggestion in suggestions:
print(f" - {suggestion}")
else:
print(" No optimization suggestions for this column.")
print()
except Error as e:
print(f"Database error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
def analyze_column(current_type, stats, row_count):
suggestions = []
current_type_lower = current_type.lower()
# NULL이 많은 경우 NULL 허용 여부 검토
if stats['null_count'] > 0 and stats['null_count'] == row_count:
suggestions.append("Consider dropping this column as it's entirely NULL")
elif stats['null_count'] == 0 and 'NOT NULL' not in current_type:
suggestions.append("Add NOT NULL constraint since there are no NULL values")
# 정수형 컬럼 분석
if 'int(' in current_type_lower:
int_type = current_type_lower.split('(')[0]
max_val = stats['max_val']
min_val = stats['min_val']
if max_val is not None and min_val is not None:
# SIGNED/UNSIGNED 검토
if min_val >= 0 and 'unsigned' not in current_type_lower:
suggestions.append(f"Consider UNSIGNED {int_type} as values are non-negative")
# 더 작은 정수 타입으로 변경 가능한지 검토
if max_val <= 127 and min_val >= -128 and int_type != 'tinyint':
suggestions.append("Consider TINYINT instead of current type")
elif max_val <= 32767 and min_val >= -32768 and int_type not in ('tinyint', 'smallint'):
suggestions.append("Consider SMALLINT instead of current type")
elif max_val <= 8388607 and min_val >= -8388608 and int_type not in ('tinyint', 'smallint', 'mediumint'):
suggestions.append("Consider MEDIUMINT instead of current type")
# 문자열 컬럼 분석
elif 'varchar(' in current_type_lower or 'char(' in current_type_lower:
max_length = int(current_type_lower.split('(')[1].split(')')[0])
distinct_count = stats['distinct_count']
# ENUM으로 변경 가능한지 검토
if distinct_count > 0 and distinct_count <= 20: # ENUM은 적은 수의 고정값에 적합
suggestions.append(f"Consider ENUM type for this column with {distinct_count} distinct values")
# VARCHAR 길이 조정 가능성 검토
cursor.execute(f"SELECT MAX(LENGTH({col_name})) as max_len FROM {table_name}")
max_len = cursor.fetchone()['max_len']
if max_len and max_len < max_length:
suggestions.append(f"Reduce VARCHAR length from {max_length} to {max_len}")
# 날짜/시간 타입 분석
elif 'datetime' in current_type_lower:
if stats['min_val'] and stats['min_val'].year >= 1970:
suggestions.append("Consider TIMESTAMP if range is post-1970 (more efficient storage)")
elif 'timestamp' in current_type_lower:
if stats['min_val'] and stats['min_val'].year < 1970:
suggestions.append("Switch to DATETIME as you have pre-1970 dates")
# TEXT 타입 분석
elif 'text' in current_type_lower:
cursor.execute(f"SELECT MAX(LENGTH({col_name})) as max_len FROM {table_name}")
max_len = cursor.fetchone()['max_len']
if max_len and max_len <= 255:
suggestions.append("Consider VARCHAR(255) instead of TEXT for shorter content")
return suggestions
# 데이터베이스 설정
db_config = {
'host': 'localhost',
'user': 'root',
'password': '', # 비밀번호가 있다면 여기에 입력하세요
'database': 'norm_project_db'
}
# 분석 실행
analyze_columns_for_optimization(db_config)
코드 설명
데이터베이스 연결 및 테이블 조회:
주어진 DB 설정으로 연결한 후 모든 테이블을 조회합니다.
컬럼 분석:
각 테이블의 컬럼 정보를 조회하고, 실제 데이터 분포를 분석합니다.
각 컬럼의 최소값, 최대값, 고유값 수, NULL 값 수 등을 확인합니다.
최적화 제안:
analyze_column 함수에서 현재 타입과 데이터 분포를 기반으로 최적화 가능성을 분석합니다.
정수형 컬럼: 더 작은 정수 타입으로 변경 제안
문자열 컬럼: VARCHAR 길이 조정 또는 ENUM 타입 전환 제안
날짜 타입: TIMESTAMP/DATETIME 전환 제안
NULL 허용 여부 검토
결과 출력:
각 컬럼의 현재 상태와 최적화 제안 사항을 출력합니다.
실행 방법
위 코드를 Python 파일로 저장합니다.
db_config 딕셔너리에 실제 데이터베이스 연결 정보를 입력합니다.
스크립트를 실행하면 모든 테이블의 컬럼을 분석하고 최적화 제안을 출력합니다.
이 코드는 MySQL/MariaDB에 최적화되어 있으며, 다른 DBMS를 사용할 경우 일부 쿼리 문법을 수정해야 할 수 있습니다.