다음은 allrecords2 테이블에서 1NF(제1정규형) 위반 사항을 꼼꼼하게 확인하는 Python 코드입니다:
python
import mysql.connector
import pandas as pd
import re
from collections import defaultdict
# 데이터베이스 연결 설정
TARGET_DB_CONFIG = {
'host': 'localhost',
'user': 'root',
'password': '',
'database': 'project_db'
}
def check_1nf_violations(table_name='allrecords2'):
"""
테이블의 1NF 위반 사항을 체크하는 함수
1NF 규칙:
1. 각 컬럼은 원자값(atomic value)만 포함해야 함
2. 중복되는 그룹이 없어야 함
3. 각 행은 유일해야 함
4. 컬럼의 순서가 데이터에 영향을 주지 않아야 함
"""
violations = defaultdict(list)
try:
# 데이터베이스 연결
conn = mysql.connector.connect(**TARGET_DB_CONFIG)
cursor = conn.cursor()
# 테이블 구조 확인
cursor.execute(f"DESCRIBE {table_name}")
columns_info = cursor.fetchall()
column_names = [col[0] for col in columns_info]
print(f"=== {table_name} 테이블 1NF 위반 검사 시작 ===\n")
print(f"컬럼 목록: {', '.join(column_names)}\n")
# 전체 데이터 가져오기
cursor.execute(f"SELECT * FROM {table_name}")
data = cursor.fetchall()
df = pd.DataFrame(data, columns=column_names)
# 1. 다중값 검사 (쉼표, 세미콜론, 파이프 등으로 구분된 값)
print("1. 다중값 검사 중...")
multi_value_patterns = [
(r',\s*', '쉼표'),
(r';\s*', '세미콜론'),
(r'\|\s*', '파이프'),
(r'/\s*', '슬래시'),
(r'\n', '줄바꿈')
]
for col in column_names:
for idx, value in enumerate(df[col]):
if value is not None and isinstance(value, str):
for pattern, delimiter_name in multi_value_patterns:
if re.search(pattern, str(value)):
# 숫자나 날짜 형식이 아닌 경우만 체크
if not re.match(r'^\d+[,./]\d+', str(value)):
violations['multi_values'].append({
'column': col,
'row': idx + 1,
'value': value,
'delimiter': delimiter_name
})
# 2. 반복 그룹 검사 (컬럼명에 숫자가 포함된 경우)
print("2. 반복 그룹 검사 중...")
repeating_group_pattern = r'(.+?)(\d+)$'
column_groups = defaultdict(list)
for col in column_names:
match = re.match(repeating_group_pattern, col)
if match:
base_name = match.group(1)
column_groups[base_name].append(col)
for base_name, cols in column_groups.items():
if len(cols) > 1:
violations['repeating_groups'].append({
'base_name': base_name,
'columns': cols
})
# 3. 중복 행 검사
print("3. 중복 행 검사 중...")
duplicates = df[df.duplicated(keep=False)]
if not duplicates.empty:
duplicate_groups = []
for _, group in duplicates.groupby(list(df.columns)):
duplicate_groups.append({
'count': len(group),
'rows': group.index.tolist()
})
violations['duplicate_rows'] = duplicate_groups
# 4. NULL 값이 과도하게 많은 컬럼 검사
print("4. NULL 값 검사 중...")
null_threshold = 0.5 # 50% 이상 NULL인 경우
for col in column_names:
null_count = df[col].isnull().sum()
null_ratio = null_count / len(df)
if null_ratio > null_threshold:
violations['excessive_nulls'].append({
'column': col,
'null_count': null_count,
'total_rows': len(df),
'null_percentage': f"{null_ratio * 100:.2f}%"
})
# 5. 복합 데이터 타입 검사 (JSON, XML 등)
print("5. 복합 데이터 타입 검사 중...")
for col in column_names:
for idx, value in enumerate(df[col]):
if value is not None and isinstance(value, str):
# JSON 형식 검사
if (value.strip().startswith('{') and value.strip().endswith('}')) or \
(value.strip().startswith('[') and value.strip().endswith(']')):
violations['complex_types'].append({
'column': col,
'row': idx + 1,
'type': 'JSON-like',
'value_preview': value[:50] + '...' if len(value) > 50 else value
})
# XML 형식 검사
elif value.strip().startswith('<') and value.strip().endswith('>'):
violations['complex_types'].append({
'column': col,
'row': idx + 1,
'type': 'XML-like',
'value_preview': value[:50] + '...' if len(value) > 50 else value
})
# 6. 기본키 존재 여부 확인
print("6. 기본키 검사 중...")
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_keys = cursor.fetchall()
if not primary_keys:
violations['no_primary_key'] = True
# 결과 출력
print("\n=== 1NF 위반 검사 결과 ===\n")
if not any(violations.values()):
print("✅ 1NF 위반 사항이 발견되지 않았습니다!")
else:
if violations['multi_values']:
print(f"❌ 다중값 위반: {len(violations['multi_values'])}건")
for v in violations['multi_values'][:5]: # 처음 5개만 표시
print(f" - {v['column']} 컬럼, {v['row']}행: '{v['value'][:30]}...' ({v['delimiter']}로 구분)")
if len(violations['multi_values']) > 5:
print(f" ... 외 {len(violations['multi_values']) - 5}건")
print()
if violations['repeating_groups']:
print(f"❌ 반복 그룹 위반: {len(violations['repeating_groups'])}개 그룹")
for v in violations['repeating_groups']:
print(f" - {v['base_name']}: {', '.join(v['columns'])}")
print()
if violations['duplicate_rows']:
print(f"❌ 중복 행: {len(violations['duplicate_rows'])}개 그룹")
for v in violations['duplicate_rows'][:3]:
print(f" - {v['count']}개 중복 행 (인덱스: {v['rows'][:5]}...)")
print()
if violations['excessive_nulls']:
print(f"❌ 과도한 NULL 값: {len(violations['excessive_nulls'])}개 컬럼")
for v in violations['excessive_nulls']:
print(f" - {v['column']}: {v['null_percentage']} NULL")
print()
if violations['complex_types']:
print(f"❌ 복합 데이터 타입: {len(violations['complex_types'])}건")
for v in violations['complex_types'][:5]:
print(f" - {v['column']} 컬럼, {v['row']}행: {v['type']} 형식")
if len(violations['complex_types']) > 5:
print(f" ... 외 {len(violations['complex_types']) - 5}건")
print()
if violations.get('no_primary_key'):
print("❌ 기본키가 설정되지 않았습니다")
print()
# 상세 통계
print("\n=== 상세 통계 ===")
print(f"총 행 수: {len(df)}")
print(f"총 컬럼 수: {len(column_names)}")
print(f"NULL 값 총 개수: {df.isnull().sum().sum()}")
return violations
except mysql.connector.Error as err:
print(f"데이터베이스 오류: {err}")
return None
finally:
if 'cursor' in locals():
cursor.close()
if 'conn' in locals():
conn.close()
# 실행
if __name__ == "__main__":
violations = check_1nf_violations('allrecords2')
# 위반 사항이 있으면 수정 제안
if violations and any(violations.values()):
print("\n=== 1NF 정규화 제안 ===")
if violations['multi_values']:
print("\n1. 다중값 분리:")
print(" - 별도의 테이블로 분리하여 1:N 관계로 모델링")
print(" - 예: 태그, 카테고리 등은 별도 테이블로 분리")
if violations['repeating_groups']:
print("\n2. 반복 그룹 제거:")
print(" - 반복되는 컬럼들을 별도 테이블로 분리")
print(" - 예: address1, address2, address3 → addresses 테이블")
if violations['duplicate_rows']:
print("\n3. 중복 행 제거:")
print(" - 중복 데이터 제거 또는 고유 식별자 추가")
if violations.get('no_primary_key'):
print("\n4. 기본키 추가:")
print(" - 각 행을 고유하게 식별할 수 있는 기본키 설정")
이 코드는 다음과 같은 1NF 위반 사항들을 체크합니다:
다중값 검사: 쉼표, 세미콜론, 파이프 등으로 구분된 여러 값이 하나의 셀에 있는지 확인
반복 그룹 검사: 컬럼명에 숫자가 붙어있는 패턴 (예: address1, address2)