데이터베이스의 모든 테이블에서 3NF 위반 사항을 확인하는 Python 코드를 작성해드리겠습니다.
python
import mysql.connector
from collections import defaultdict
import pandas as pd
TARGET_DB_CONFIG = {
'host': 'localhost',
'user': 'root',
'password': '',
'database': 'norm_project_db'
}
class ThirdNormalFormChecker:
def __init__(self, db_config):
self.db_config = db_config
self.connection = None
self.cursor = None
def connect(self):
"""데이터베이스 연결"""
try:
self.connection = mysql.connector.connect(**self.db_config)
self.cursor = self.connection.cursor()
return True
except Exception as e:
print(f"데이터베이스 연결 실패: {e}")
return False
def disconnect(self):
"""데이터베이스 연결 해제"""
if self.cursor:
self.cursor.close()
if self.connection:
self.connection.close()
def get_all_tables(self):
"""모든 테이블 목록 조회"""
self.cursor.execute("SHOW TABLES")
return [table[0] for table in self.cursor.fetchall()]
def get_table_info(self, table_name):
"""테이블 구조 정보 조회"""
self.cursor.execute(f"DESCRIBE {table_name}")
columns = self.cursor.fetchall()
# 기본키 조회
self.cursor.execute(f"""
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = '{self.db_config['database']}'
AND TABLE_NAME = '{table_name}'
AND CONSTRAINT_NAME = 'PRIMARY'
""")
primary_keys = [row[0] for row in self.cursor.fetchall()]
return columns, primary_keys
def get_sample_data(self, table_name, limit=100):
"""테이블의 샘플 데이터 조회"""
self.cursor.execute(f"SELECT * FROM {table_name} LIMIT {limit}")
return self.cursor.fetchall()
def check_functional_dependencies(self, table_name, columns, primary_keys, sample_data):
"""함수적 종속성 확인"""
violations = []
column_names = [col[0] for col in columns]
if not sample_data:
return violations
# 데이터를 DataFrame으로 변환
df = pd.DataFrame(sample_data, columns=column_names)
# 기본키가 아닌 컬럼들에 대해 검사
non_key_columns = [col for col in column_names if col not in primary_keys]
for col1 in non_key_columns:
for col2 in non_key_columns:
if col1 != col2:
# col1이 col2를 결정하는지 확인
if self.determines(df, col1, col2):
# col1이 기본키의 부분집합이 아니고 col2를 결정한다면 3NF 위반
if col1 not in primary_keys:
violations.append({
'type': 'Transitive Dependency',
'determinant': col1,
'dependent': col2,
'description': f"'{col1}' determines '{col2}' but '{col1}' is not a superkey"
})
return violations
def determines(self, df, col1, col2):
"""col1이 col2를 함수적으로 결정하는지 확인"""
try:
# 같은 col1 값에 대해 col2 값이 항상 같은지 확인
grouped = df.groupby(col1)[col2].nunique()
return all(count == 1 for count in grouped)
except:
return False
def check_partial_dependencies(self, table_name, columns, primary_keys, sample_data):
"""부분 함수적 종속성 확인 (복합키가 있는 경우)"""
violations = []
column_names = [col[0] for col in columns]
if len(primary_keys) <= 1 or not sample_data:
return violations
df = pd.DataFrame(sample_data, columns=column_names)
non_key_columns = [col for col in column_names if col not in primary_keys]
# 기본키의 부분집합이 다른 컬럼을 결정하는지 확인
for pk_subset in primary_keys:
for non_key_col in non_key_columns:
if self.determines(df, pk_subset, non_key_col):
violations.append({
'type': 'Partial Dependency',
'determinant': pk_subset,
'dependent': non_key_col,
'description': f"'{pk_subset}' (part of primary key) determines '{non_key_col}'"
})
return violations
def analyze_table(self, table_name):
"""특정 테이블의 3NF 위반 사항 분석"""
try:
columns, primary_keys = self.get_table_info(table_name)
sample_data = self.get_sample_data(table_name)
violations = []
# 이행적 종속성 확인
transitive_violations = self.check_functional_dependencies(
table_name, columns, primary_keys, sample_data
)
violations.extend(transitive_violations)
# 부분 함수적 종속성 확인
partial_violations = self.check_partial_dependencies(
table_name, columns, primary_keys, sample_data
)
violations.extend(partial_violations)
return {
'table_name': table_name,
'columns': [col[0] for col in columns],
'primary_keys': primary_keys,
'violations': violations,
'record_count': len(sample_data)
}
except Exception as e:
return {
'table_name': table_name,
'error': str(e),
'violations': []
}
def generate_markdown_report(self, analysis_results):
"""마크다운 형태의 보고서 생성"""
md_content = []
md_content.append("# 3NF 위반 사항 분석 보고서\n")
md_content.append(f"**데이터베이스:** {self.db_config['database']}\n")
md_content.append(f"**분석 일시:** {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
total_violations = 0
tables_with_violations = 0
for result in analysis_results:
table_name = result['table_name']
violations = result.get('violations', [])
md_content.append(f"## 테이블: `{table_name}`\n")
if 'error' in result:
md_content.append(f"**❌ 분석 오류:** {result['error']}\n\n")
continue
md_content.append(f"**컬럼:** {', '.join(result['columns'])}\n")
md_content.append(f"**기본키:** {', '.join(result['primary_keys']) if result['primary_keys'] else 'None'}\n")
md_content.append(f"**레코드 수:** {result['record_count']}\n\n")
if violations:
tables_with_violations += 1
total_violations += len(violations)
md_content.append(f"### 🚨 3NF 위반 사항 ({len(violations)}개)\n")
for i, violation in enumerate(violations, 1):
md_content.append(f"**{i}. {violation['type']}**\n")
md_content.append(f"- **결정자:** `{violation['determinant']}`\n")
md_content.append(f"- **종속자:** `{violation['dependent']}`\n")
md_content.append(f"- **설명:** {violation['description']}\n\n")
else:
md_content.append("### ✅ 3NF 위반 사항 없음\n\n")
md_content.append("---\n\n")
# 요약 정보 추가
md_content.insert(4, f"## 📊 분석 요약\n")
md_content.insert(5, f"- **총 테이블 수:** {len(analysis_results)}\n")
md_content.insert(6, f"- **위반 사항이 있는 테이블:** {tables_with_violations}\n")
md_content.insert(7, f"- **총 위반 사항 수:** {total_violations}\n\n")
return ''.join(md_content)
def run_full_analysis(self):
"""전체 데이터베이스 3NF 분석 실행"""
if not self.connect():
return None
try:
tables = self.get_all_tables()
print(f"분석할 테이블 수: {len(tables)}")
analysis_results = []
for table in tables:
print(f"분석 중: {table}")
result = self.analyze_table(table)
analysis_results.append(result)
# 마크다운 보고서 생성
markdown_report = self.generate_markdown_report(analysis_results)
# 파일로 저장
with open('3nf_violation_report.md', 'w', encoding='utf-8') as f:
f.write(markdown_report)
print("\n분석 완료! '3nf_violation_report.md' 파일이 생성되었습니다.")
return markdown_report
finally:
self.disconnect()
# 실행
if __name__ == "__main__":
checker = ThirdNormalFormChecker(TARGET_DB_CONFIG)
report = checker.run_full_analysis()
if report:
print("\n" + "="*50)
print("마크다운 보고서 미리보기:")
print("="*50)
print(report[:1000] + "..." if len(report) > 1000 else report)
코드를 실행하면 데이터베이스의 모든 테이블을 분석하여 3NF 위반 사항을 찾아 마크다운 형태로 정리된 보고서를 생성합니다.