import mysql.connector
db_config = {
'host': 'localhost',
'user': 'root',
'password': '', # 비밀번호가 있다면 여기에 입력하세요
'database': 'norm_project_db'
}
def analyze_database_for_optimization(db_config):
"""
데이터베이스의 테이블들을 분석하여 컬럼 타입 변경을 통한 용량 최적화 가능성을 진단합니다.
Args:
db_config (dict): 데이터베이스 연결 설정 정보 (host, user, password, database).
Returns:
dict: 테이블별로 최적화 가능한 컬럼 정보와 제안 사항을 담은 딕셔너리.
형식: {
'table_name': {
'column_name': {
'current_type': '현재 컬럼 타입',
'suggested_type': '제안하는 컬럼 타입',
'reason': '제안 이유',
'potential_savings': '예상 절감 효과 (설명)'
}
}
}
최적화할 컬럼이 없는 경우 빈 딕셔너리를 반환합니다.
"""
optimization_suggestions = {}
try:
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor()
# 1. 모든 테이블 이름 가져오기
cursor.execute("SHOW TABLES")
tables = [table[0] for table in cursor.fetchall()]
for table_name in tables:
optimization_suggestions[table_name] = {}
print(f"Analyzing table: {table_name}")
# 2. 테이블의 컬럼 정보 가져오기
cursor.execute(f"SHOW COLUMNS FROM `{table_name}`") # 테이블 이름에 backtick을 사용
columns = cursor.fetchall()
for column in columns:
column_name = column[0]
column_type = column[1].lower() # 소문자로 변경
is_nullable = column[2] == 'YES'
key = column[3] # PRI, UNI, MUL 등 (인덱스 정보)
default_value = column[4]
extra = column[5]
print(f" Analyzing column: {column_name} ({column_type})")
# 3. 컬럼 타입에 따른 최적화 가능성 분석
suggestion = analyze_column_type(column_name, column_type, is_nullable, table_name, conn)
if suggestion:
optimization_suggestions[table_name][column_name] = suggestion
return optimization_suggestions
except mysql.connector.Error as err:
print(f"Database error: {err}")
return {}
finally:
if conn:
cursor.close()
conn.close()
def analyze_column_type(column_name, column_type, is_nullable, table_name, conn):
"""
특정 컬럼의 타입을 분석하여 최적화된 타입으로 변경할 수 있는지 확인합니다.
Args:
column_name (str): 컬럼 이름.
column_type (str): 컬럼 타입 (소문자).
is_nullable (bool): NULL 허용 여부.
table_name (str): 테이블 이름.
conn: MySQL 연결 객체.
Returns:
dict: 최적화 제안 정보 (current_type, suggested_type, reason, potential_savings) 또는 None (최적화 불필요 시).
"""
cursor = conn.cursor()
if 'int' in column_type:
# Integer 타입 최적화
suggestion = optimize_integer_column(column_name, column_type, is_nullable, table_name, conn)
if suggestion:
return suggestion
elif 'varchar' in column_type or 'char' in column_type:
# 문자열 타입 최적화
suggestion = optimize_string_column(column_name, column_type, is_nullable, table_name, conn)
if suggestion:
return suggestion
elif 'text' in column_type:
suggestion = optimize_text_column(column_name, column_type, is_nullable, table_name, conn)
if suggestion:
return suggestion
elif 'date' in column_type or 'timestamp' in column_type or 'datetime' in column_type:
# Date 타입 최적화
suggestion = optimize_datetime_column(column_name, column_type, is_nullable, table_name, conn)
if suggestion:
return suggestion
return None # 최적화할 필요 없음
def optimize_integer_column(column_name, column_type, is_nullable, table_name, conn):
"""
Integer 타입 컬럼의 크기를 줄일 수 있는지 분석합니다.
"""
cursor = conn.cursor()
cursor.execute(f"SELECT MAX(`{column_name}`), MIN(`{column_name}`) FROM `{table_name}`") # 컬럼 이름에 backtick을 사용
max_val, min_val = cursor.fetchone()
if max_val is None and min_val is None:
return None # 데이터가 없는 경우 최적화 판단 불가
if 'tinyint' not in column_type and -128 <= min_val <= 127 and 0 <= max_val <= 255:
return {
'current_type': column_type,
'suggested_type': 'TINYINT UNSIGNED' if min_val >=0 else 'TINYINT',
'reason': '값의 범위가 TINYINT 범위 내에 있으므로 크기를 줄일 수 있습니다.',
'potential_savings': 'Integer 컬럼 크기 감소 (4 bytes -> 1 byte)'
}
elif 'smallint' not in column_type and -32768 <= min_val <= 32767 and 0 <= max_val <= 65535:
return {
'current_type': column_type,
'suggested_type': 'SMALLINT UNSIGNED' if min_val >= 0 else 'SMALLINT',
'reason': '값의 범위가 SMALLINT 범위 내에 있으므로 크기를 줄일 수 있습니다.',
'potential_savings': 'Integer 컬럼 크기 감소 (4 bytes -> 2 bytes)'
}
elif 'mediumint' not in column_type and -8388608 <= min_val <= 8388607 and 0 <= max_val <= 16777215:
return {
'current_type': column_type,
'suggested_type': 'MEDIUMINT UNSIGNED' if min_val >=0 else 'MEDIUMINT',
'reason': '값의 범위가 MEDIUMINT 범위 내에 있으므로 크기를 줄일 수 있습니다.',
'potential_savings': 'Integer 컬럼 크기 감소 (4 bytes -> 3 bytes)'
}
elif 'int' in column_type and 'bigint' not in column_type and (-2147483648 <= min_val <= 2147483647 and 0 <= max_val <= 4294967295):
# 일반 int를 unsigned int로 변경 가능한지 확인
if 'unsigned' not in column_type and min_val >= 0:
return {
'current_type': column_type,
'suggested_type': 'INT UNSIGNED',
'reason': '값이 음수를 포함하지 않으므로 UNSIGNED로 변경하여 최대값을 늘릴 수 있습니다.',
'potential_savings': '범위 확장'
}
return None
def optimize_string_column(column_name, column_type, is_nullable, table_name, conn):
"""
VARCHAR/CHAR 타입 컬럼의 길이를 줄일 수 있는지 분석합니다.
"""
cursor = conn.cursor()
# 정규표현식을 사용하여 괄호 안의 숫자 값만 추출합니다.
import re
match = re.search(r'\((\d+)\)', column_type)
if match:
length = int(match.group(1))
else:
return None # 길이 정보가 없으면 최적화 불가
cursor.execute(f"SELECT MAX(LENGTH(`{column_name}`)) FROM `{table_name}`") # 컬럼 이름에 backtick을 사용
max_length = cursor.fetchone()[0]
if max_length is None:
return None # 데이터가 없는 경우 최적화 판단 불가
if max_length < length:
# 현재 컬럼 타입에서 숫자만 추출
return {
'current_type': column_type,
'suggested_type': column_type.replace(str(length), str(max_length)),
'reason': f'최대 문자열 길이가 {max_length}이므로 VARCHAR 길이를 줄일 수 있습니다.',
'potential_savings': 'VARCHAR 컬럼 크기 감소'
}
if 'char' in column_type and max_length < length / 2:
return {
'current_type': column_type,
'suggested_type': f'VARCHAR({max_length})',
'reason': f'대부분의 문자열이 짧으므로 CHAR를 VARCHAR로 변경하는 것이 좋습니다.',
'potential_savings': 'CHAR -> VARCHAR로 변경, 용량 절약 효과'
}
return None
def optimize_text_column(column_name, column_type, is_nullable, table_name, conn):
"""
TEXT 타입 컬럼을 더 작은 타입으로 변경할 수 있는지 분석합니다.
"""
cursor = conn.cursor()
cursor.execute(f"SELECT MAX(LENGTH(`{column_name}`)) FROM `{table_name}`") # 컬럼 이름에 backtick을 사용
max_length = cursor.fetchone()[0]
if max_length is None:
return None # 데이터가 없는 경우 최적화 판단 불가
if 'tinytext' not in column_type and max_length <= 255:
return {
'current_type': column_type,
'suggested_type': 'TINYTEXT',
'reason': '최대 문자열 길이가 255 이하이므로 TINYTEXT로 변경할 수 있습니다.',
'potential_savings': 'TEXT -> TINYTEXT로 변경, 용량 절약 효과'
}
elif 'mediumtext' not in column_type and max_length <= 16777215:
return {
'current_type': column_type,
'suggested_type': 'MEDIUMTEXT',
'reason': '최대 문자열 길이가 16777215 이하이므로 MEDIUMTEXT로 변경할 수 있습니다.',
'potential_savings': 'TEXT -> MEDIUMTEXT로 변경, 용량 절약 효과'
}
elif 'longtext' not in column_type and max_length <= 4294967295:
return {
'current_type': column_type,
'suggested_type': 'LONGTEXT',
'reason': '최대 문자열 길이가 4294967295 이하이므로 LONGTEXT로 변경할 수 있습니다.',
'potential_savings': 'TEXT -> LONGTEXT로 변경, 용량 절약 효과'
}
return None
def optimize_datetime_column(column_name, column_type, is_nullable, table_name, conn):
"""
날짜/시간 타입 컬럼의 최적화를 분석합니다. 현재는 미구현.
"""
# 날짜/시간 컬럼은 데이터 분포에 따른 최적화보다는
# 필요에 따라 DATE, DATETIME, TIMESTAMP 간의 변경을 고려할 수 있습니다.
# 예: 시간 정보가 필요 없는 경우 DATETIME -> DATE
# 여기서는 간단하게 NULL 허용 여부에 따른 제안만 제공합니다.
if 'datetime' in column_type and not is_nullable:
return {
'current_type': column_type,
'suggested_type': column_type, # 대안이 없으므로 동일 타입
'reason': 'datetime은 NULL이 불가능하도록 설정하는 것이 좋습니다.',
'potential_savings': '일관성 및 데이터 정확성 향상'
}
return None
# 실행 예시
if __name__ == "__main__":
suggestions = analyze_database_for_optimization(db_config)
if suggestions:
for table_name, column_suggestions in suggestions.items():
if column_suggestions:
print(f"Table: {table_name}")
for column_name, suggestion in column_suggestions.items():
print(f" Column: {column_name}")
print(f" Current Type: {suggestion['current_type']}")
print(f" Suggested Type: {suggestion['suggested_type']}")
print(f" Reason: {suggestion['reason']}")
print(f" Potential Savings: {suggestion['potential_savings']}")
else:
print(f"Table {table_name}: No optimization opportunities found.")
else:
print("No optimization opportunities found in any table.")
코드 설명:
analyze_database_for_optimization(db_config) 함수:
주어진 데이터베이스 설정으로 연결을 수립합니다.
SHOW TABLES 쿼리를 사용하여 데이터베이스 내의 모든 테이블 이름을 가져옵니다.
각 테이블에 대해 다음을 수행합니다.
SHOW COLUMNS FROM table_name 쿼리를 사용하여 테이블의 컬럼 정보를 가져옵니다.
각 컬럼에 대해 analyze_column_type 함수를 호출하여 최적화 가능성을 분석합니다.