다음은 allrecords2 테이블에서 1NF(제1정규형) 위반 사항을 체크하는 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")
# 1. 다중값 검사 (쉼표, 세미콜론, 파이프 등으로 구분된 값)
print("1. 다중값 검사 중...")
delimiters = [',', ';', '|', '/', '&']
for column in column_names:
cursor.execute(f"""
SELECT {column}, COUNT(*) as count
FROM {table_name}
WHERE {column} IS NOT NULL
GROUP BY {column}
LIMIT 1000
""")
for value, count in cursor.fetchall():
value_str = str(value)
# 숫자나 날짜 형식이 아닌 경우에만 검사
if not value_str.replace('.', '').replace('-', '').isdigit():
for delimiter in delimiters:
if delimiter in value_str and len(value_str.split(delimiter)) > 1:
# 이메일 주소나 URL은 제외
if not ('@' in value_str and delimiter == '.') and \
not ('http' in value_str and delimiter == '/'):
violations['multi_values'].append({
'column': column,
'value': value_str[:100], # 처음 100자만 표시
'delimiter': delimiter,
'count': count
})
break
# 2. 반복 패턴 검사 (같은 유형의 데이터가 여러 컬럼에 분산)
print("2. 반복 그룹 패턴 검사 중...")
# 컬럼 이름에서 숫자 패턴 찾기 (예: address1, address2, phone1, phone2)
column_patterns = defaultdict(list)
for col in column_names:
# 숫자로 끝나는 컬럼 찾기
match = re.match(r'(.+?)(\d+)$', col)
if match:
base_name = match.group(1)
number = match.group(2)
column_patterns[base_name].append((col, number))
for base_name, cols in column_patterns.items():
if len(cols) > 1:
violations['repeating_groups'].append({
'pattern': base_name,
'columns': [col[0] for col in sorted(cols, key=lambda x: x[1])]
})
# 3. 중복 행 검사
print("3. 중복 행 검사 중...")
# 전체 행 중복 검사
columns_str = ', '.join(column_names)
cursor.execute(f"""
SELECT {columns_str}, COUNT(*) as duplicate_count
FROM {table_name}
GROUP BY {columns_str}
HAVING COUNT(*) > 1
LIMIT 10
""")
duplicate_rows = cursor.fetchall()
if duplicate_rows:
violations['duplicate_rows'].append({
'total_duplicate_groups': len(duplicate_rows),
'sample_duplicates': duplicate_rows[:5]
})
# 4. NULL 값이 과도하게 많은 컬럼 검사 (구조적 문제 가능성)
print("4. NULL 값 패턴 검사 중...")
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
total_rows = cursor.fetchone()[0]
for column in column_names:
cursor.execute(f"""
SELECT COUNT(*)
FROM {table_name}
WHERE {column} IS NULL
""")
null_count = cursor.fetchone()[0]
null_percentage = (null_count / total_rows * 100) if total_rows > 0 else 0
if null_percentage > 80: # 80% 이상이 NULL인 경우
violations['excessive_nulls'].append({
'column': column,
'null_count': null_count,
'null_percentage': f"{null_percentage:.2f}%"
})
# 5. 복합 데이터 타입 검사 (JSON, XML 등)
print("5. 복합 데이터 타입 검사 중...")
for column in column_names:
cursor.execute(f"""
SELECT {column}
FROM {table_name}
WHERE {column} IS NOT NULL
LIMIT 100
""")
for (value,) in cursor.fetchall():
value_str = str(value)
# JSON 패턴 검사
if (value_str.startswith('{') and value_str.endswith('}')) or \
(value_str.startswith('[') and value_str.endswith(']')):
violations['complex_types'].append({
'column': column,
'type': 'JSON-like',
'sample': value_str[:100]
})
break
# XML 패턴 검사
elif '<' in value_str and '>' in value_str:
violations['complex_types'].append({
'column': column,
'type': 'XML-like',
'sample': value_str[:100]
})
break
# 결과 출력
print("\n" + "="*80)
print("1NF 위반 검사 결과")
print("="*80 + "\n")
if not any(violations.values()):
print("✅ 1NF 위반 사항이 발견되지 않았습니다!")
else:
if violations['multi_values']:
print("❌ 다중값 위반:")
for v in violations['multi_values'][:10]: # 처음 10개만 표시
print(f" - 컬럼: {v['column']}, 구분자: '{v['delimiter']}', 예시: {v['value']}")
if len(violations['multi_values']) > 10:
print(f" ... 외 {len(violations['multi_values']) - 10}개 더 있음")
print()
if violations['repeating_groups']:
print("❌ 반복 그룹 패턴:")
for v in violations['repeating_groups']:
print(f" - 패턴: '{v['pattern']}', 컬럼들: {', '.join(v['columns'])}")
print()
if violations['duplicate_rows']:
print("❌ 중복 행:")
for v in violations['duplicate_rows']:
print(f" - 총 {v['total_duplicate_groups']}개의 중복 그룹 발견")
print()
if violations['excessive_nulls']:
print("❌ 과도한 NULL 값:")
for v in violations['excessive_nulls']:
print(f" - 컬럼: {v['column']}, NULL 비율: {v['null_percentage']}")
print()
if violations['complex_types']:
print("❌ 복합 데이터 타입:")
for v in violations['complex_types']:
print(f" - 컬럼: {v['column']}, 타입: {v['type']}")
print()
# 요약 통계
print("\n" + "-"*80)
print("요약:")
print(f"- 총 행 수: {total_rows}")
print(f"- 총 컬럼 수: {len(column_names)}")
print(f"- 발견된 위반 유형 수: {sum(1 for v in violations.values() if v)}")
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 (violations['multi_values'] or violations['complex_types']):
print("\n" + "="*80)
print("권장 사항:")
print("="*80)
print("1. 다중값이 있는 컬럼은 별도 테이블로 분리하세요.")
print("2. 반복 그룹은 정규화를 통해 별도 테이블로 분리하세요.")
print("3. JSON/XML 형태의 데이터는 파싱하여 개별 컬럼으로 분리하세요.")
print("4. 중복 행은 기본키를 설정하여 방지하세요.")
이 코드는 다음과 같은 1NF 위반 사항들을 검사합니다:
- 다중값 검사: 쉼표, 세미콜론 등으로 구분된 여러 값이 하나의 셀에 저장된 경우
- 반복 그룹 검사: address1, address2처럼 번호가 붙은 유사한 컬럼들
- 중복 행 검사: 완전히 동일한 행이 여러 개 존재하는 경우
- 과도한 NULL 검사: 대부분이 NULL인 컬럼 (잘못된 설계 가능성)
- 복합 데이터 타입 검사: JSON이나 XML 형태의 데이터
검사 결과는 각 위반 유형별로 정리되어 출력되며, 문제가 발견된 경우 해결 방안도 제시합니다.