부분 함수 종속성을 확인하는 파이썬 코드를 작성해드리겠습니다. 이 코드는 주어진 테이블의 모든 열에 대해 가능한 조합을 검사하고, 후보키와 부분 함수 종속성을 찾아냅니다.
import mysql.connector
from itertools import combinations
from collections import defaultdict
def check_partial_dependencies(config, table_name):
# DB 연결
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
# 테이블의 모든 컬럼 가져오기
cursor.execute(f"SHOW COLUMNS FROM {table_name}")
columns = [column[0] for column in cursor.fetchall()]
# 데이터 가져오기
cursor.execute(f"SELECT * FROM {table_name}")
data = cursor.fetchall()
def is_functionally_dependent(attr_set, dependent_attr, data):
# 함수적 종속성 검사
dependencies = defaultdict(set)
for row in data:
key_values = tuple(row[columns.index(attr)] for attr in attr_set)
dep_value = row[columns.index(dependent_attr)]
if key_values in dependencies and dep_value not in dependencies[key_values]:
return False
dependencies[key_values].add(dep_value)
return True
# 결과 저장을 위한 리스트
partial_dependencies = []
# 최대 검사할 속성 조합 개수 (n-4)
max_combination_size = len(columns) - 4 if len(columns) > 4 else 1
# 모든 가능한 속성 조합에 대해 검사
for i in range(1, max_combination_size + 1):
for attr_set in combinations(columns, i):
# 현재 속성 조합을 제외한 나머지 속성들에 대해
remaining_attrs = [col for col in columns if col not in attr_set]
for dependent_attr in remaining_attrs:
# 함수적 종속성 검사
if is_functionally_dependent(attr_set, dependent_attr, data):
partial_dependencies.append({
'determining_attributes': attr_set,
'dependent_attribute': dependent_attr
})
# 결과 출력
print("\n=== 부분 함수 종속성 결과 ===")
for dep in partial_dependencies:
print(f"{' -> '.join(dep['determining_attributes'])} -> {dep['dependent_attribute']}")
# 연결 종료
cursor.close()
conn.close()
return partial_dependencies
# 실행
if __name__ == "__main__":
try:
partial_deps = check_partial_dependencies(TARGET_DB_CONFIG, TABLE_NAME)
except Exception as e:
print(f"오류 발생: {str(e)}")
이 코드는 다음과 같은 기능을 수행합니다:
- 주어진 테이블의 모든 컬럼을 가져옵니다.
- n-4개까지의 속성 조합을 생성합니다.
- 각 속성 조합에 대해 다른 속성들과의 함수적 종속성을 검사합니다.
- 발견된 모든 부분 함수 종속성을 출력합니다.
주요 특징:
- 최대 검사 조합 개수를 n-4로 제한하여 성능을 개선했습니다.
- defaultdict를 사용하여 종속성 검사를 효율적으로 수행합니다.
- 결과를 보기 쉽게 포맷팅하여 출력합니다.
사용 방법:
# 코드를 실행하면 자동으로 설정된 데이터베이스와 테이블에 대해 검사를 수행합니다
# 결과는 다음과 같은 형식으로 출력됩니다:
# === 부분 함수 종속성 결과 ===
# column1 -> column2
# column1 -> column3
# column1, column2 -> column4
# ...
이 코드를 실행하면 테이블의 2NF 위반 여부를 확인할 수 있으며, 필요한 경우 테이블을 정규화하는데 도움이 될 것입니다.