grok-3-preview-02-24· xAI LMArena Human Preference 140K
dbconfig = { 'host': 'localhost', 'user': 'root', 'password': '', # 비밀번호가 있다면 여기에 입력하세요…
- User
db_config = { 'host': 'localhost', 'user': 'root', 'password': '', # 비밀번호가 있다면 여기에 입력하세요 'database': 'norm_project_db' }
해당 db에서 table을 컬럼들을 전수 조사해서 컬럼 type 변경시 용량이 줄어들 수 있는 컬럼들과 어떻게 type을 조절해야할지 알려주는 파이썬 코드 작성해줘
- Assistant
데이터베이스 테이블의 컬럼 타입을 분석하고, 용량을 줄일 수 있는 최적화 방안을 제안하는 파이썬 코드를 작성해드리겠습니다. 이 코드는 MySQL 데이터베이스를 기준으로 작성되며, 주요 기능은 다음과 같습니다:
- 모든 테이블과 컬럼 정보를 수집
- 각 컬럼의 데이터 특성을 분석 (최대값, 최소값, 데이터 길이 등)
- 현재 타입과 데이터 특성을 비교하여 최적화 제안
- 용량 절감 가능성을 계산
import mysql.connector from mysql.connector import Error import sys # DB 연결 설정 db_config = { 'host': 'localhost', 'user': 'root', 'password': '', 'database': 'norm_project_db' } class DatabaseAnalyzer: def __init__(self, db_config): self.connection = None self.db_config = db_config self.type_recommendations = { 'int': [ ('TINYINT', 127, -128), ('SMALLINT', 32767, -32768), ('MEDIUMINT', 8388607, -8388608), ('INT', 2147483647, -2147483648), ('BIGINT', 9223372036854775807, -9223372036854775808) ], 'varchar': lambda length: f'VARCHAR({length})' if length < 255 else 'TEXT', 'char': lambda length: f'CHAR({length})' if length < 255 else 'TEXT' } def connect_db(self): try: self.connection = mysql.connector.connect(**self.db_config) return True except Error as e: print(f"Error connecting to MySQL: {e}") return False def close_connection(self): if self.connection and self.connection.is_connected(): self.connection.close() def get_tables(self): cursor = self.connection.cursor() cursor.execute("SHOW TABLES") tables = [table[0] for table in cursor.fetchall()] cursor.close() return tables def get_column_info(self, table): cursor = self.connection.cursor(dictionary=True) cursor.execute(f"SHOW COLUMNS FROM {table}") columns = cursor.fetchall() cursor.close() return columns def analyze_numeric_column(self, table, column): cursor = self.connection.cursor() query = f""" SELECT MAX({column}) as max_val, MIN({column}) as min_val, COUNT(*) as row_count FROM {table} """ cursor.execute(query) result = cursor.fetchone() cursor.close() return result def analyze_string_column(self, table, column): cursor = self.connection.cursor() query = f""" SELECT MAX(LENGTH({column})) as max_length, COUNT(*) as row_count FROM {table} """ cursor.execute(query) result = cursor.fetchone() cursor.close() return result def get_optimal_numeric_type(self, max_val, min_val, current_type): if max_val is None or min_val is None: return None, 0 current_type = current_type.lower() if 'int' not in current_type: return None, 0 for type_info in self.type_recommendations['int']: type_name, type_max, type_min = type_info if max_val <= type_max and min_val >= type_min: if type_name.lower() != current_type: # 용량 계산 (바이트 단위) size_map = { 'tinyint': 1, 'smallint': 2, 'mediumint': 3, 'int': 4, 'bigint': 8 } current_size = size_map.get(current_type, 4) new_size = size_map.get(type_name.lower(), 4) size_reduction = current_size - new_size return type_name, size_reduction break return None, 0 def get_optimal_string_type(self, max_length, current_type, current_length): if max_length is None: return None, 0 current_type = current_type.lower() if 'varchar' in current_type or 'char' in current_type: if max_length < current_length: new_type = f"{current_type.upper().split('(')[0]}({max_length})" size_reduction = current_length - max_length return new_type, size_reduction return None, 0 def analyze_database(self): if not self.connect_db(): return print("Starting database analysis...") print("-" * 80) total_savings = 0 tables = self.get_tables() for table in tables: print(f"\nAnalyzing table: {table}") columns = self.get_column_info(table) for column in columns: col_name = column['Field'] col_type = column['Type'] print(f"\n Column: {col_name} (Current Type: {col_type})") # 숫자형 컬럼 분석 if 'int' in col_type.lower(): stats = self.analyze_numeric_column(table, col_name) recommended_type, size_reduction = self.get_optimal_numeric_type( stats[0], stats[1], col_type.lower() ) if recommended_type: savings = size_reduction * stats[2] # row_count * size_reduction total_savings += savings print(f" Recommendation: Change to {recommended_type}") print(f" Potential savings: {savings:,} bytes") # 문자열 컬럼 분석 elif 'varchar' in col_type.lower() or 'char' in col_type.lower(): current_length = int(col_type[col_type.find('(')+1:col_type.find(')')]) stats = self.analyze_string_column(table, col_name) recommended_type, size_reduction = self.get_optimal_string_type( stats[0], col_type.lower(), current_length ) if recommended_type: savings = size_reduction * stats[1] # row_count * size_reduction total_savings += savings print(f" Recommendation: Change to {recommended_type}") print(f" Potential savings: {savings:,} bytes") print("\n" + "-" * 80) print(f"Total potential savings across all tables: {total_savings:,} bytes") print(f"Total potential savings in MB: {total_savings/1024/1024:.2f} MB") self.close_connection() if __name__ == "__main__": analyzer = DatabaseAnalyzer(db_config) analyzer.analyze_database()코드 사용 방법
- 필요한 라이브러리 설치:
pip install mysql-connector-python- 코드 실행:
- 위 코드를 파일로 저장 (예:
db_analyzer.py) - Python으로 실행:
python db_analyzer.py
코드의 주요 기능 설명
-
숫자형 컬럼 분석:
- INT 계열 타입(TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT)에 대해 실제 데이터의 최대/최소값을 확인
- 더 작은 타입으로 변경 가능한 경우 추천
- 용량 절감 효과 계산 (바이트 단위)
-
문자열 컬럼 분석:
- VARCHAR, CHAR 타입의 실제 데이터 길이를 분석
- 불필요하게 큰 길이가 설정된 경우 최적 길이 추천
- 용량 절감 효과 계산
-
결과 출력:
- 각 테이블과 컬럼별 분석 결과 출력
- 추천 타입과 예상 절감 용량 표시
- 전체 데이터베이스의 총 절감 가능 용량 요약
주의사항
-
데이터 무결성:
- 타입 변경 전 반드시 데이터를 백업하세요
- 추천된 타입으로 변경하기 전에 비즈니스 로직과 데이터 특성을 검토하세요
-
제약사항:
- 이 코드는 INT 계열과 VARCHAR/CHAR 타입만 분석합니다
- 다른 타입(DATE, DECIMAL, TEXT 등)은 추가 구현이 필요합니다
-
성능 고려:
- 용량 절감이 항상 성능 향상으로 이어지지는 않습니다
- 인덱스, 쿼리 패턴 등을 함께 고려해야 합니다
-
실제 적용:
- 추천사항을 바탕으로 ALTER TABLE 문을 작성하여 타입 변경을 적용해야 합니다
- 예:
ALTER TABLE table_name MODIFY COLUMN column_name NEW_TYPE;
이 코드를 실행하면 데이터베이스의 현재 상태를 분석하여 용량 최적화 가능성을 상세히 알려줄 것입니다. 필요에 따라 추가 타입 분석 기능이나 특정 요구사항을 반영하도록 코드를 확장할 수 있습니다.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- deepseek-v3-0324Compare side by side →
- claude-opus-4-20250514Compare side by side →
- claude-opus-4-20250514Compare side by side →
- gemini-2.5-flashCompare side by side →
- claude-sonnet-4-20250514Compare side by side →
- mistral-medium-2505Compare side by side →
- deepseek-v3-0324Compare side by side →
- claude-opus-4-20250514Compare side by side →
- gemini-2.0-flash-001Compare side by side →
- grok-3-mini-betaCompare side by side →
- gemini-2.5-proCompare side by side →