이 코드가 부분함수 3NF 확인하는데 적합한 코드인지 검토해줘 import mysql.connector from itertools import…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
이 코드가 부분함수 3NF 확인하는데 적합한 코드인지 검토해줘
import mysql.connector from itertools import combinations from collections import defaultdict
TARGET_DB_CONFIG = { 'host': 'localhost', 'user': 'root', 'password': '', # 비밀번호가 없는 경우 빈 문자열로 설정 'database': 'norm_project_db' }
TABLE_NAME = 'HashKeyInfo'
def get_connection(): """데이터베이스 연결을 반환합니다.""" return mysql.connector.connect(**TARGET_DB_CONFIG)
def get_columns(cursor, table_name): """테이블의 모든 열 이름을 가져옵니다.""" cursor.execute(f"SHOW COLUMNS FROM {table_name}") return [column[0] for column in cursor.fetchall()]
def check_functional_dependency(cursor, table_name, determinant_cols, dependent_col): """주어진 결정자 열들이 종속 열을 함수적으로 결정하는지 확인합니다.""" determinant_str = ', '.join(determinant_cols)
# 결정자 조합별로 종속 열의 고유 값 개수를 확인
query = f"""
SELECT COUNT(DISTINCT {dependent_col}) as unique_dependent,
COUNT(*) as total_rows
FROM (
SELECT {determinant_str}, {dependent_col}
FROM {table_name}
GROUP BY {determinant_str}, {dependent_col}
) as subquery
GROUP BY {determinant_str}
HAVING COUNT(*) > 1
"""
try:
cursor.execute(query)
results = cursor.fetchall()
# 만약 결과가 있다면, 동일한 결정자에 대해 다른 종속 값이 존재한다는 의미
return len(results) == 0
except Exception as e:
print(f"쿼리 실행 중 오류 발생: {e}")
return False
def find_transitive_dependencies(cursor, table_name): """테이블에서 이행함수 종속성을 찾습니다.""" columns = get_columns(cursor, table_name) n_columns = len(columns)
print(f"테이블 '{table_name}'의 열 개수: {n_columns}")
print(f"열 목록: {columns}")
print(f"확인할 최대 조합 크기: {n_columns - 4}")
print("-" * 80)
transitive_dependencies = []
# 1개부터 n-4개까지의 조합 확인
max_combination_size = min(n_columns - 4, n_columns - 1) if n_columns > 4 else n_columns - 1
for combo_size in range(1, max_combination_size + 1):
print(f"\n{combo_size}개 열 조합 확인 중...")
# 가능한 모든 결정자 조합 생성
for determinant_combo in combinations(columns, combo_size):
# 결정자에 포함되지 않은 열들을 종속 열 후보로 확인
for dependent_col in columns:
if dependent_col not in determinant_combo:
# A -> B 확인
if check_functional_dependency(cursor, table_name, determinant_combo, dependent_col):
# A -> B가 성립하면, B -> C인 경우를 찾아 이행종속 확인
for third_col in columns:
if third_col not in determinant_combo and third_col != dependent_col:
# B -> C 확인
if check_functional_dependency(cursor, table_name, [dependent_col], third_col):
# A -> C도 확인 (이행종속이 맞는지 검증)
if check_functional_dependency(cursor, table_name, determinant_combo, third_col):
transitive_dep = {
'A': determinant_combo,
'B': dependent_col,
'C': third_col,
'description': f"{determinant_combo} -> {dependent_col} -> {third_col}"
}
# 중복 제거
if transitive_dep not in transitive_dependencies:
transitive_dependencies.append(transitive_dep)
print(f"이행종속 발견: {transitive_dep['description']}")
return transitive_dependencies
def main(): """메인 실행 함수""" connection = None cursor = None
try:
# 데이터베이스 연결
connection = get_connection()
cursor = connection.cursor()
print(f"데이터베이스 연결 성공!")
print(f"테이블 '{TABLE_NAME}'에서 이행함수 종속성을 확인합니다...\n")
# 이행함수 종속성 찾기
transitive_deps = find_transitive_dependencies(cursor, TABLE_NAME)
# 결과 출력
print("\n" + "=" * 80)
print("이행함수 종속성 분석 결과")
print("=" * 80)
if transitive_deps:
print(f"\n총 {len(transitive_deps)}개의 이행함수 종속성이 발견되었습니다:\n")
for i, dep in enumerate(transitive_deps, 1):
print(f"{i}. {dep['description']}")
print(f" - A (결정자): {', '.join(dep['A'])}")
print(f" - B (중간 속성): {dep['B']}")
print(f" - C (이행 종속 속성): {dep['C']}")
print()
print("\n2NF 위반 사항:")
print("위의 이행함수 종속성들은 2NF를 위반하는 것은 아니지만,")
print("3NF를 위반하는 사항들입니다. 2NF는 부분함수 종속성을 제거하는 것이고,")
print("3NF는 이행함수 종속성을 제거하는 것입니다.")
else:
print("\n이행함수 종속성이 발견되지 않았습니다.")
print("테이블이 이미 3NF를 만족하고 있을 가능성이 높습니다.")
except mysql.connector.Error as e:
print(f"데이터베이스 오류: {e}")
except Exception as e:
print(f"예상치 못한 오류: {e}")
finally:
# 연결 종료
if cursor:
cursor.close()
if connection:
connection.close()
print("\n데이터베이스 연결이 종료되었습니다.")
if name == "main": main()
아래는 주어진 스크립트가 “3NF(=2NF(부분함수종속 제거) + 이행함수종속 제거)” 검증용으로 얼마나 적합한지, 그리고 개선 포인트를 정리한 것입니다.
장점
itertools.combinations을 써서 결정자(combination) 조합을 자동 생성단점
combinations(columns, k) 조합이 기하급수적으로 늘어남Primary Key / Candidate Key 자동 추출
information_schema.key_column_usage 또는 SHOW INDEX FROM tbl WHERE Key_name='PRIMARY' 등을 써서 PK 컬럼 목록을 얻는다.is_superkey(determinant_cols)부분함수종속(2NF 위반) 검사 추가
check_functional_dependency(S, A)가 True이면 2NF 위반3NF 위반 검증 로직 재정립
쿼리 단순화 예시
-- X→A 를 검사하는 훨씬 간단한 패턴
SELECT COUNT(*)
FROM (
SELECT {X_cols}, COUNT(DISTINCT {A}) AS cnt
FROM {table}
GROUP BY {X_cols}
HAVING cnt > 1
) t;
-- 결과가 0 row 면 X→A 성립
조합(subset) 생성 범위 좁히기
예시 코드 스켈레톤
def get_primary_key(cursor, table):
cursor.execute(f"SHOW INDEX FROM {table} WHERE Key_name='PRIMARY'")
return [row[4] for row in cursor.fetchall()] # Column_name 위치 확인
def is_superkey(cursor, table, cols):
# cols 가 테이블의 모든 컬럼을 포함하면 당연히 슈퍼키
all_cols = get_columns(cursor, table)
if set(cols) == set(all_cols):
return True
# 그 외엔 cols→{all_cols - cols} 가 모두 성립해야 함 (비효율적이라 샘플링 등 고려)
for dep in set(all_cols) - set(cols):
if not check_fd(cursor, table, cols, dep):
return False
return True
def check_2NF(cursor, table):
pk = get_primary_key(cursor, table)
violations = []
for r in range(1, len(pk)):
for subset in combinations(pk, r):
for col in (set(get_columns(cursor, table)) - set(pk)):
if check_fd(cursor, table, subset, col):
violations.append((subset, col))
return violations
위 개선 사항을 반영하시면 “부분함수종속”→2NF, “이행함수종속”→3NF를 좀 더 정확하게 자동화하실 수 있을 거예요! 🚀