1NF(First Normal Form)는 데이터베이스 정규화의 첫 번째 단계로, 다음과 같은 조건을 만족해야 합니다:
1NF의 조건:
- 원자적 값(Atomic Values): 각 속성(Attribute)은 원자적(분할 불가능한) 값만 가져야 함.
- 중복 그룹 제거: 동일한 레코드 내에 반복되는 컬럼 그룹이 없어야 함.
- 기본 키 존재: 각 행을 유일하게 식별할 수 있는 기본 키(PK)가 있어야 함.
✅ allrecords2 테이블에서 1NF 위반 여부를 확인하는 파이썬 코드
아래 코드는 MySQL 데이터베이스에 연결하여 allrecords2 테이블을 분석하고, 1NF 위반 사항을 탐지합니다.
import mysql.connector
from mysql.connector import Error
# 데이터베이스 연결 설정
TARGET_DB_CONFIG = {
'host': 'localhost',
'user': 'root',
'password': '', # 비밀번호가 없는 경우 빈 문자열로 설정
'database': 'project_db'
}
def check_1nf_violations(table_name='allrecords2'):
try:
connection = mysql.connector.connect(**TARGET_DB_CONFIG)
if not connection.is_connected():
print("데이터베이스에 연결할 수 없습니다.")
return
cursor = connection.cursor(dictionary=True)
# 1. 테이블의 모든 열 정보 조회 (데이터 타입 포함)
cursor.execute(f"DESCRIBE {table_name}")
columns_info = cursor.fetchall()
columns = [col['Field'] for col in columns_info]
print("테이블의 컬럼 목록:")
for col in columns:
print(f" - {col}")
# 2. 각 컬럼의 데이터 검사: 원자적 값인지 확인
print("\n[1] 원자적 값 검사 시작...")
potential_non_atomic_columns = []
for col in columns:
query = f"SELECT DISTINCT `{col}` FROM `{table_name}` LIMIT 10"
cursor.execute(query)
sample_values = [row[col] for row in cursor.fetchall()]
# 예시 값 검사 (문자열이고 쉼표 또는 세미콜론 등으로 구분된 경우)
is_potentially_non_atomic = False
for val in sample_values:
if isinstance(val, str) and (',' in val or ';' in val or '|' in val):
is_potentially_non_atomic = True
break
if is_potentially_non_atomic:
print(f" - 경고: '{col}' 컬럼은 비원자적 값이 포함되어 있을 수 있습니다. 샘플: {sample_values[:3]}")
potential_non_atomic_columns.append(col)
else:
print(f" - '{col}' 컬럼은 원자적 값으로 보입니다.")
# 3. 중복된 컬럼 패턴이 있는지 확인 (예: phone1, phone2, phone3 등)
print("\n[2] 중복 그룹 검사 시작...")
from collections import defaultdict
column_prefixes = defaultdict(list)
for col in columns:
if '_' in col:
prefix = '_'.join(col.split('_')[:-1])
column_prefixes[prefix].append(col)
duplicate_groups = {k: v for k, v in column_prefixes.items() if len(v) > 1}
if duplicate_groups:
print("경고: 중복 그룹이 감지되었습니다. 아래 컬럼들은 1NF 위반 가능성이 있습니다:")
for group, cols in duplicate_groups.items():
print(f" - {group}_x 패턴: {cols}")
else:
print("중복 그룹이 발견되지 않았습니다.")
# 4. 기본 키 존재 여부 확인
print("\n[3] 기본 키 존재 여부 검사 시작...")
cursor.execute(f"""
SELECT COLUMN_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = '{TARGET_DB_CONFIG['database']}'
AND TABLE_NAME = '{table_name}'
AND CONSTRAINT_NAME = 'PRIMARY'
""")
primary_key = cursor.fetchone()
if primary_key:
print(f"기본 키가 존재합니다: {primary_key['COLUMN_NAME']}")
else:
print("⚠️ 경고: 기본 키가 정의되어 있지 않습니다.")
# 결과 요약
print("\n=== 1NF 검사 결과 요약 ===")
if potential_non_atomic_columns or duplicate_groups or not primary_key:
print("❗ 일부 1NF 위반 사항이 의심됩니다.")
if potential_non_atomic_columns:
print(f" - 비원자적 컬럼: {potential_non_atomic_columns}")
if duplicate_groups:
print(f" - 중복 그룹 컬럼: {list(duplicate_groups.keys())}")
if not primary_key:
print(" - 기본 키가 없습니다.")
else:
print("✅ 모든 1NF 조건을 충족합니다.")
except Error as e:
print(f"오류 발생: {e}")
finally:
if 'connection' in locals() and connection.is_connected():
cursor.close()
connection.close()
print("\nMySQL 연결이 종료되었습니다.")
# 실행
check_1nf_violations()
📌 사용 설명
🔧 추가 개선 방향
- 전체 데이터셋이 아닌 일부 샘플만 검사하므로, 실제 대량 데이터에서는 전체 스캔도 필요할 수 있음.
- 특정 컬럼에 대해 더 정교한 패턴 매칭을 통해 원자성 판단을 개선할 수 있음.
- JSON, SET 등의 비표준 데이터 타입 사용 시 별도 처리 필요.
필요하다면 특정 컬럼에 대한 상세한 진단이나 자동 수정 추천도 제공해드릴 수 있습니다!