-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava-entity-table-spec-generator.py
More file actions
902 lines (725 loc) · 37.5 KB
/
java-entity-table-spec-generator.py
File metadata and controls
902 lines (725 loc) · 37.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
import os
import re
import sys
import argparse
from pathlib import Path
import pandas as pd
from typing import List, Dict, Optional
import mysql.connector
from mysql.connector import Error
from datetime import datetime
class EntityParser:
"""Java Entity 클래스를 파싱하여 테이블 명세를 추출하는 클래스"""
def __init__(self, project_path: str, log_file: str = None):
self.project_path = project_path
self.entities = []
self.log_file = log_file or f"entity_parser_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
# 로그 파일 초기화
with open(self.log_file, 'w', encoding='utf-8') as f:
f.write(f"=== Entity Parser Log ===\n")
f.write(f"시작 시간: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"프로젝트 경로: {project_path}\n")
f.write("=" * 80 + "\n\n")
def log(self, message: str):
"""로그 메시지를 파일에 기록"""
with open(self.log_file, 'a', encoding='utf-8') as f:
f.write(message + "\n")
# 콘솔에도 중요 메시지는 출력
if any(keyword in message for keyword in ['✓ 엔티티 발견:', '총', '개 필드', 'ERROR', 'SKIP']):
print(message)
def parse_all_entities(self):
"""프로젝트 전체에서 모든 엔티티 파일을 파싱"""
entity_files = self._find_entity_files()
self.log(f"총 {len(entity_files)}개의 Java 파일을 검색 중...")
for file_path in entity_files:
entity_info = self._parse_entity_file(file_path)
if entity_info:
self.entities.append(entity_info)
return self.entities
def _find_entity_files(self) -> List[Path]:
"""프로젝트 전체에서 Java 파일 찾기"""
path = Path(self.project_path)
if not path.exists():
self.log(f"경로가 존재하지 않습니다: {self.project_path}")
return []
java_files = list(path.rglob("*.java"))
self.log(f"{len(java_files)}개의 Java 파일을 발견했습니다.")
return java_files
def _parse_entity_file(self, file_path: Path) -> Optional[Dict]:
"""개별 엔티티 파일 파싱"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
if '@Entity' not in content:
return None
self.log(f"\n{'='*80}")
self.log(f"파일 파싱: {file_path.name}")
self.log(f"{'='*80}")
package_name = self._extract_package_name(content)
class_description = self._extract_class_description(content)
entity_info = {
'file_name': file_path.name,
'file_path': str(file_path),
'package': package_name,
'class_name': self._extract_class_name(content),
'table_name': self._extract_table_name(content),
'table_description': class_description,
'columns': self._extract_columns(content)
}
# 요약 정보 출력
if entity_info['columns']:
summary = f"✓ 엔티티 발견: {package_name}.{entity_info['class_name']} -> {entity_info['table_name']}"
self.log(summary)
for col in entity_info['columns']:
desc_info = f" '{col['description']}'" if col['description'] else " [NO DESC]"
fk_info = " [FK]" if col['is_foreign_key'] else ""
enum_info = f" [Enum:{col.get('enum_type', 'ORDINAL')}]" if col.get('is_enum') else ""
self.log(f" └─ {col['column_name']} (field:{col['field_name']}){fk_info}{enum_info} -{desc_info}")
else:
self.log(f"✓ 엔티티 발견: {package_name}.{entity_info['class_name']} -> {entity_info['table_name']} (컬럼 없음)")
return entity_info
except Exception as e:
self.log(f"ERROR: 파일 파싱 오류 ({file_path}): {str(e)}")
import traceback
self.log(traceback.format_exc())
return None
def _extract_package_name(self, content: str) -> str:
"""패키지명 추출"""
pattern = r'package\s+([\w.]+)\s*;'
match = re.search(pattern, content)
return match.group(1) if match else "unknown"
def _extract_class_name(self, content: str) -> str:
"""클래스명 추출"""
pattern = r'public\s+class\s+(\w+)'
match = re.search(pattern, content)
return match.group(1) if match else "Unknown"
def _extract_class_description(self, content: str) -> str:
"""클래스 레벨의 @Description 추출"""
pattern = r'@Description\s*\(\s*["\']([^"\']+)["\']\s*\)\s*(?:@\w+\s*(?:\([^)]*\))?\s*)*public\s+class'
match = re.search(pattern, content, re.DOTALL)
if match:
return match.group(1)
table_comment_pattern = r'@Table\s*\([^)]*comment\s*=\s*["\']([^"\']+)["\']'
match = re.search(table_comment_pattern, content)
return match.group(1) if match else ""
def _extract_table_name(self, content: str) -> str:
"""테이블명 추출"""
pattern = r'@Table\s*\(\s*name\s*=\s*["\'](\w+)["\']'
match = re.search(pattern, content)
if match:
return match.group(1)
class_name = self._extract_class_name(content)
return self._camel_to_snake(class_name)
def _camel_to_snake(self, name: str) -> str:
"""CamelCase를 snake_case로 변환"""
pattern = re.compile(r'(?<!^)(?=[A-Z])')
return pattern.sub('_', name).lower()
def _extract_columns(self, content: str) -> List[Dict]:
"""컬럼 정보 추출 (Enum 타입 지원)"""
columns = []
# private 필드 패턴 - 더 정확하게 (초기화 포함)
field_pattern = r'private\s+(\w+(?:<[^>]+>)?)\s+(\w+)\s*(?:=\s*[^;]+)?;'
fields = list(re.finditer(field_pattern, content, re.MULTILINE))
self.log(f"\n === 필드 파싱 시작 (총 {len(fields)}개 필드) ===")
for i, field in enumerate(fields):
java_type = field.group(1)
field_name = field.group(2)
self.log(f"\n [{i+1}] 필드 발견: {java_type} {field_name}")
field_start = field.start()
# 현재 필드의 어노테이션 영역 찾기
preceding_text = content[:field_start]
lines = preceding_text.split('\n')
annotation_lines = []
self.log(f" 역방향 탐색 시작 (총 {len(lines)}줄)")
# 마지막 줄부터 역순으로 탐색
for idx, line in enumerate(reversed(lines)):
stripped = line.strip()
line_num = len(lines) - idx
log_line = stripped[:50] + '...' if len(stripped) > 50 else stripped
self.log(f" Line {line_num}: '{log_line}'")
# 빈 줄은 스킵
if not stripped:
self.log(f" -> 빈 줄, 계속")
continue
# 어노테이션이거나 주석인 경우 계속
if stripped.startswith('@') or stripped.startswith('//') or stripped.startswith('/*'):
annotation_lines.insert(0, line)
self.log(f" -> 어노테이션/주석 추가")
continue
# private, public, protected 등의 다른 선언을 만나면 중단
if any(keyword in stripped for keyword in ['private ', 'public ', 'protected ', 'class ', '{']):
if not stripped.startswith('@'):
self.log(f" -> 다른 선언 발견, 중단")
break
else:
annotation_lines.insert(0, line)
self.log(f" -> 어노테이션 추가")
continue
# 메서드나 생성자를 만나면 중단
if '(' in stripped and ')' in stripped:
self.log(f" -> 메서드/생성자 발견, 중단")
break
# 그 외는 중단
self.log(f" -> 기타, 중단")
break
field_annotations = '\n'.join(annotation_lines)
# 어노테이션 출력
annotation_list = [line.strip() for line in field_annotations.split('\n') if line.strip() and line.strip().startswith('@')]
if annotation_list:
self.log(f" 추출된 어노테이션: {', '.join(annotation_list)}")
else:
self.log(f" 추출된 어노테이션: 없음")
# @JoinTable이 있으면 스킵
if '@JoinTable' in field_annotations:
self.log(f" => SKIP: @JoinTable 발견")
continue
# @CollectionTable이 있으면 스킵
if '@CollectionTable' in field_annotations:
self.log(f" => SKIP: @CollectionTable 발견 (별도 테이블)")
continue
# @ElementCollection이 있으면 스킵
if '@ElementCollection' in field_annotations:
self.log(f" => SKIP: @ElementCollection 발견")
continue
# @OneToMany, @ManyToMany는 현재 테이블에 컬럼이 없음
if '@OneToMany' in field_annotations or '@ManyToMany' in field_annotations:
if '@JoinColumn' not in field_annotations:
self.log(f" => SKIP: @OneToMany 또는 @ManyToMany (FK 없음)")
continue
# Enum 타입 처리
is_enum = '@Enumerated' in field_annotations
enum_type = None
if is_enum:
enum_pattern = r'@Enumerated\s*\(\s*EnumType\.(\w+)\s*\)'
enum_match = re.search(enum_pattern, field_annotations)
enum_type = enum_match.group(1) if enum_match else 'ORDINAL'
self.log(f" Enum 타입: {enum_type}")
column_name = self._extract_column_name(field_annotations, field_name)
column_info = {
'field_name': field_name,
'column_name': column_name,
'java_type': java_type,
'db_type': self._java_to_db_type(java_type, is_enum, enum_type),
'length': self._extract_length(field_annotations),
'precision': self._extract_precision_scale(field_annotations)[0],
'scale': self._extract_precision_scale(field_annotations)[1],
'column_definition': self._extract_column_definition(field_annotations),
'nullable': self._is_nullable(field_annotations),
'primary_key': '@Id' in field_annotations,
'auto_increment': '@GeneratedValue' in field_annotations,
'unique': self._is_unique(field_annotations),
'is_foreign_key': '@JoinColumn' in field_annotations and ('@ManyToOne' in field_annotations or '@OneToOne' in field_annotations),
'foreign_key_info': self._extract_foreign_key_info(field_annotations, java_type),
'is_enum': is_enum,
'enum_type': enum_type,
'description': self._extract_description(field_annotations)
}
self.log(f" => 컬럼 추가: {column_name}")
columns.append(column_info)
self.log(f"\n === 파싱 완료: {len(columns)}개 컬럼 추출 ===\n")
return columns
def _extract_column_name(self, annotations: str, field_name: str) -> str:
"""컬럼명 추출 (@Column 또는 @JoinColumn)"""
self.log(f" 컬럼명 추출: 필드={field_name}")
# @JoinColumn에서 name 속성 찾기
if '@JoinColumn' in annotations:
pattern = r'name\s*=\s*["\']([^"\']+)["\']'
join_start = annotations.find('@JoinColumn')
if join_start != -1:
join_section = annotations[join_start:]
next_at = join_section.find('@', 1)
next_private = join_section.find('private')
if next_at != -1 and next_private != -1:
join_section = join_section[:min(next_at, next_private)]
elif next_at != -1:
join_section = join_section[:next_at]
elif next_private != -1:
join_section = join_section[:next_private]
match = re.search(pattern, join_section)
if match:
result = match.group(1)
self.log(f" -> @JoinColumn name 발견: {result}")
return result
# @Column에서 name 속성 찾기
if '@Column' in annotations:
pattern = r'name\s*=\s*["\']([^"\']+)["\']'
column_start = annotations.find('@Column')
if column_start != -1:
column_section = annotations[column_start:]
next_at = column_section.find('@', 1)
next_private = column_section.find('private')
if next_at != -1 and next_private != -1:
column_section = column_section[:min(next_at, next_private)]
elif next_at != -1:
column_section = column_section[:next_at]
elif next_private != -1:
column_section = column_section[:next_private]
match = re.search(pattern, column_section)
if match:
column_name = match.group(1)
self.log(f" -> @Column name 발견: {column_name}")
return column_name
# 어노테이션이 없거나 name 속성이 없으면 필드명을 snake_case로 변환
snake_name = self._camel_to_snake(field_name)
self.log(f" -> name 속성 없음, snake_case 변환: {field_name} -> {snake_name}")
return snake_name
def _extract_length(self, annotations: str) -> Optional[int]:
"""컬럼 길이 추출"""
pattern = r'length\s*=\s*(\d+)'
match = re.search(pattern, annotations)
return int(match.group(1)) if match else None
def _extract_precision_scale(self, annotations: str) -> tuple:
"""DECIMAL 타입의 precision과 scale 추출"""
precision_pattern = r'precision\s*=\s*(\d+)'
scale_pattern = r'scale\s*=\s*(\d+)'
precision_match = re.search(precision_pattern, annotations)
scale_match = re.search(scale_pattern, annotations)
precision = int(precision_match.group(1)) if precision_match else None
scale = int(scale_match.group(1)) if scale_match else None
return precision, scale
def _extract_column_definition(self, annotations: str) -> Optional[str]:
"""@Column의 columnDefinition 추출"""
pattern = r'columnDefinition\s*=\s*["\']([^"\']+)["\']'
match = re.search(pattern, annotations)
return match.group(1) if match else None
def _java_to_db_type(self, java_type: str, is_enum: bool = False, enum_type: str = None) -> str:
"""Java 타입을 DB 타입으로 변환 (Enum 지원)"""
# Enum 타입 처리
if is_enum:
if enum_type == 'STRING':
return 'VARCHAR'
else: # ORDINAL
return 'INT'
type_mapping = {
'String': 'VARCHAR',
'Integer': 'INT',
'int': 'INT',
'Long': 'BIGINT',
'long': 'BIGINT',
'Double': 'DOUBLE',
'double': 'DOUBLE',
'Float': 'FLOAT',
'float': 'FLOAT',
'Boolean': 'TINYINT',
'boolean': 'TINYINT',
'Date': 'DATETIME',
'LocalDate': 'DATE',
'LocalDateTime': 'DATETIME',
'LocalTime': 'TIME',
'BigDecimal': 'DECIMAL',
'Timestamp': 'TIMESTAMP'
}
return type_mapping.get(java_type, 'VARCHAR')
def _is_nullable(self, annotations: str) -> bool:
"""Nullable 여부 확인"""
# @Column(nullable=false) 명시적 확인
if '@Column' in annotations:
nullable_pattern = r'nullable\s*=\s*(true|false)'
match = re.search(nullable_pattern, annotations)
if match:
return match.group(1) == 'true'
# @JoinColumn(nullable=false) 확인
if '@JoinColumn' in annotations:
nullable_pattern = r'nullable\s*=\s*(true|false)'
match = re.search(nullable_pattern, annotations)
if match:
return match.group(1) == 'true'
# @NotNull이 있으면 nullable = false
if '@NotNull' in annotations:
return False
# @Id가 있으면 nullable = false
if '@Id' in annotations:
return False
# 기본값은 true (nullable)
return True
def _is_unique(self, annotations: str) -> bool:
"""Unique 여부 확인"""
unique_pattern = r'unique\s*=\s*true'
return re.search(unique_pattern, annotations) is not None
def _extract_description(self, annotations: str) -> str:
"""@Description 어노테이션에서 설명 추출"""
patterns = [
r'@Description\s*\(\s*"([^"]+)"\s*\)',
r"@Description\s*\(\s*'([^']+)'\s*\)",
r'@Description\s*\(\s*value\s*=\s*"([^"]+)"\s*\)',
r"@Description\s*\(\s*value\s*=\s*'([^']+)'\s*\)",
]
for pattern in patterns:
match = re.search(pattern, annotations, re.DOTALL)
if match:
return match.group(1)
return ""
def _extract_foreign_key_info(self, annotations: str, java_type: str) -> Dict[str, str]:
"""@JoinColumn에서 외래키 정보 추출"""
fk_info = {
'referenced_table': '',
'referenced_column': '',
'relationship_type': ''
}
if '@ManyToOne' in annotations:
fk_info['relationship_type'] = 'ManyToOne'
elif '@OneToOne' in annotations:
fk_info['relationship_type'] = 'OneToOne'
elif '@OneToMany' in annotations:
fk_info['relationship_type'] = 'OneToMany'
elif '@ManyToMany' in annotations:
fk_info['relationship_type'] = 'ManyToMany'
ref_pattern = r'referencedColumnName\s*=\s*["\']([^"\']+)["\']'
match = re.search(ref_pattern, annotations)
if match:
fk_info['referenced_column'] = match.group(1)
else:
fk_info['referenced_column'] = 'id'
target_pattern = r'targetEntity\s*=\s*(\w+)\.class'
match = re.search(target_pattern, annotations)
if match:
fk_info['referenced_table'] = self._camel_to_snake(match.group(1))
else:
clean_type = re.sub(r'<.*?>', '', java_type).strip()
if clean_type not in ['List', 'Set', 'Collection', 'Map']:
fk_info['referenced_table'] = self._camel_to_snake(clean_type)
return fk_info
class DatabaseConnector:
"""MySQL 데이터베이스 연결 및 정보 조회 클래스"""
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.connection = None
def connect(self):
"""데이터베이스 연결"""
try:
self.connection = mysql.connector.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database
)
print(f"✓ 데이터베이스 연결 성공: {self.database}")
return True
except Error as e:
print(f"✖ 데이터베이스 연결 오류: {e}")
return False
def get_table_columns(self) -> Dict[str, List[Dict]]:
"""모든 테이블의 컬럼 정보 조회"""
if not self.connection:
return {}
query = """
SELECT
TABLE_NAME,
COLUMN_NAME,
COLUMN_TYPE,
IS_NULLABLE,
COLUMN_KEY,
EXTRA,
COLUMN_COMMENT,
COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = %s
ORDER BY TABLE_NAME, ORDINAL_POSITION
"""
try:
cursor = self.connection.cursor(dictionary=True)
cursor.execute(query, (self.database,))
results = cursor.fetchall()
cursor.close()
tables = {}
for row in results:
table_name = row['TABLE_NAME']
if table_name not in tables:
tables[table_name] = []
tables[table_name].append(row)
print(f"✓ {len(tables)}개 테이블의 컬럼 정보 조회 완료")
return tables
except Error as e:
print(f"✖ 컬럼 정보 조회 오류: {e}")
return {}
def close(self):
"""데이터베이스 연결 종료"""
if self.connection and self.connection.is_connected():
self.connection.close()
print("✓ 데이터베이스 연결 종료")
class SpecGenerator:
"""테이블 명세서를 생성하는 클래스"""
def __init__(self, entities: List[Dict], db_columns: Optional[Dict[str, List[Dict]]] = None):
self.entities = entities
self.db_columns = db_columns or {}
def generate_excel(self, output_path: str = "table_specification.xlsx"):
"""엑셀 형태로 테이블 명세서 생성"""
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
self._create_table_list_sheet(writer)
for entity in self.entities:
self._create_table_detail_sheet(writer, entity)
print(f"✓ 테이블 명세서가 생성되었습니다: {output_path}")
def _create_table_list_sheet(self, writer):
"""테이블 목록 시트 생성"""
table_list = []
for entity in self.entities:
table_list.append({
'테이블명': entity['table_name'],
'테이블 설명': entity['table_description'],
'클래스명': entity['class_name'],
'패키지': entity['package'],
'컬럼 수': len(entity['columns']),
'파일 경로': entity['file_path']
})
df = pd.DataFrame(table_list)
df.to_excel(writer, sheet_name='테이블 목록', index=False)
def _create_table_detail_sheet(self, writer, entity: Dict):
"""개별 테이블 상세 시트 생성"""
columns_data = []
for idx, col in enumerate(entity['columns'], 1):
fk_display = ''
if col['is_foreign_key']:
fk_info = col['foreign_key_info']
fk_parts = []
if fk_info['relationship_type']:
fk_parts.append(fk_info['relationship_type'])
if fk_info['referenced_table']:
fk_parts.append(f"→ {fk_info['referenced_table']}")
if fk_info['referenced_column']:
fk_parts.append(f"({fk_info['referenced_column']})")
fk_display = ' '.join(fk_parts)
enum_display = ''
if col.get('is_enum'):
enum_display = f"[Enum: {col.get('enum_type', 'ORDINAL')}]"
java_type_display = col['java_type']
if enum_display:
java_type_display = f"{java_type_display} {enum_display}"
columns_data.append({
'No': idx,
'컬럼명': col['column_name'],
'필드명': col['field_name'],
'Java 타입': java_type_display,
'DB 타입': col['db_type'],
'PK': 'Y' if col['primary_key'] else 'N',
'FK': 'Y' if col['is_foreign_key'] else 'N',
'FK 정보': fk_display,
'AUTO_INCREMENT': 'Y' if col['auto_increment'] else 'N',
'Nullable': 'Y' if col['nullable'] else 'N',
'Unique': 'Y' if col['unique'] else 'N',
'설명': col['description']
})
df = pd.DataFrame(columns_data)
sheet_name = entity['table_name'][:31]
df.to_excel(writer, sheet_name=sheet_name, index=False)
def generate_markdown(self, output_path: str = "table_specification.md"):
"""마크다운 형태로 테이블 명세서 생성"""
with open(output_path, 'w', encoding='utf-8') as f:
f.write("# 테이블 명세서\n\n")
f.write(f"생성일: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write("## 테이블 목록\n\n")
f.write("| No | 테이블명 | 테이블 설명 | 클래스명 | 패키지 | 컬럼 수 |\n")
f.write("|---|---|---|---|---|---|\n")
for idx, entity in enumerate(self.entities, 1):
f.write(f"| {idx} | {entity['table_name']} | {entity['table_description']} | {entity['class_name']} | {entity['package']} | {len(entity['columns'])} |\n")
f.write("\n---\n\n")
for entity in self.entities:
f.write(f"## {entity['table_name']}\n\n")
f.write(f"**테이블 설명:** {entity['table_description']}\n")
f.write(f"**클래스명:** {entity['class_name']}\n")
f.write(f"**패키지:** {entity['package']}\n\n")
f.write("| No | 컬럼명 | Java 타입 | DB 타입 | PK | FK | AUTO_INCREMENT | Nullable | Unique | 설명 |\n")
f.write("|---|---|---|---|---|---|---|---|---|---|\n")
for idx, col in enumerate(entity['columns'], 1):
pk = 'Y' if col['primary_key'] else 'N'
fk = 'Y' if col['is_foreign_key'] else 'N'
auto_inc = 'Y' if col['auto_increment'] else 'N'
nullable = 'Y' if col['nullable'] else 'N'
unique = 'Y' if col['unique'] else 'N'
java_type_display = col['java_type']
if col.get('is_enum'):
java_type_display += f" [Enum:{col.get('enum_type', 'ORDINAL')}]"
f.write(f"| {idx} | {col['column_name']} | {java_type_display} | {col['db_type']} | {pk} | {fk} | {auto_inc} | {nullable} | {unique} | {col['description']} |\n")
f.write("\n")
print(f"✓ 테이블 명세서가 생성되었습니다: {output_path}")
def generate_ddl_comment(self, output_path: str = "add_comments.sql"):
"""실제 DB 정보를 기반으로 안전한 COMMENT 추가 DDL 생성"""
with open(output_path, 'w', encoding='utf-8') as f:
f.write("-- ===================================================================\n")
f.write("-- 테이블 및 컬럼 COMMENT 추가 스크립트 (MySQL 8.0)\n")
f.write("-- 실제 DB 컬럼 정의를 기반으로 생성되어 안전합니다.\n")
f.write(f"-- 생성일: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write("-- ===================================================================\n\n")
for entity in self.entities:
table_name = entity['table_name']
table_desc = entity['table_description']
if table_name not in self.db_columns:
f.write(f"-- ⚠️ 테이블 '{table_name}'이(가) DB에 존재하지 않습니다. 스킵합니다.\n\n")
continue
f.write(f"-- ====================\n")
f.write(f"-- 테이블: {table_name}\n")
if table_desc:
f.write(f"-- 설명: {table_desc}\n")
f.write(f"-- ====================\n\n")
if table_desc:
f.write(f"ALTER TABLE `{table_name}` COMMENT '{self._escape_sql(table_desc)}';\n\n")
db_columns = {col['COLUMN_NAME']: col for col in self.db_columns[table_name]}
has_comments = False
has_fk_info = False
for col in entity['columns']:
column_name = col['column_name']
description = col['description']
if not description and col['is_foreign_key']:
fk_info = col['foreign_key_info']
if fk_info['referenced_table']:
ref_display = fk_info['referenced_table']
if fk_info['referenced_column']:
ref_display += f".{fk_info['referenced_column']}"
description = f"참조: {ref_display}"
if not description:
continue
if column_name not in db_columns:
f.write(f"-- ⚠️ 컬럼 '{column_name}'이(가) DB에 존재하지 않습니다. (필드명: {col['field_name']}) 스킵합니다.\n")
continue
has_comments = True
db_col = db_columns[column_name]
final_description = description
if col['is_foreign_key']:
fk_info = col['foreign_key_info']
fk_parts = []
if fk_info['relationship_type']:
fk_parts.append(f"[{fk_info['relationship_type']}]")
if fk_info['referenced_table'] and col['description']:
ref_display = fk_info['referenced_table']
if fk_info['referenced_column']:
ref_display += f".{fk_info['referenced_column']}"
fk_parts.append(f"참조: {ref_display}")
if fk_parts:
has_fk_info = True
if col['description']:
final_description = col['description'] + " " + " ".join(fk_parts)
else:
final_description = " ".join(fk_parts)
column_type = db_col['COLUMN_TYPE']
is_nullable = "NULL" if db_col['IS_NULLABLE'] == 'YES' else "NOT NULL"
extra = db_col['EXTRA']
parts = [column_type, is_nullable]
if extra:
parts.append(extra)
parts.append(f"COMMENT '{self._escape_sql(final_description)}'")
column_def = " ".join(parts)
f.write(f"ALTER TABLE `{table_name}` MODIFY COLUMN `{column_name}` {column_def};\n")
if not has_comments and not table_desc:
f.write("-- 이 테이블에는 설정된 COMMENT가 없습니다.\n")
if has_fk_info:
f.write("\n-- ℹ️ FK 정보가 COMMENT에 포함되었습니다.\n")
f.write("\n")
print(f"✓ DDL 스크립트가 생성되었습니다: {output_path}")
if self.db_columns:
print("✅ DB 정보를 기반으로 안전하게 생성되었습니다!")
def _escape_sql(self, text: str) -> str:
"""SQL 문자열 이스케이프 처리"""
if not text:
return ""
return text.replace("'", "''")
def main():
"""메인 실행 함수"""
parser = argparse.ArgumentParser(
description='Java Entity 클래스를 분석하여 테이블 명세서 및 DDL 스크립트를 생성합니다.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
사용 예시:
# 기본 사용 (Entity만 분석)
python3 entity_spec_generator.py /path/to/project
# DB 연결하여 안전한 DDL 생성
python3 entity_spec_generator.py /path/to/project \\
--db-host localhost \\
--db-port 3306 \\
--db-user root \\
--db-password mypassword \\
--db-name mydatabase
"""
)
parser.add_argument('project_path', type=str, help='프로젝트 루트 경로')
parser.add_argument('-o', '--output', type=str, default='.', help='출력 파일 저장 경로')
parser.add_argument('--log', type=str, help='로그 파일 경로 (미지정시 자동 생성)')
parser.add_argument('--db-host', type=str, help='MySQL 호스트')
parser.add_argument('--db-port', type=int, default=3306, help='MySQL 포트')
parser.add_argument('--db-user', type=str, help='MySQL 사용자명')
parser.add_argument('--db-password', type=str, help='MySQL 비밀번호')
parser.add_argument('--db-name', type=str, help='데이터베이스명')
args = parser.parse_args()
project_path = os.path.expanduser(args.project_path)
output_dir = os.path.expanduser(args.output)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print("=" * 80)
print("Java Entity 테이블 명세서 생성기 (MySQL 8.0 + Enum 지원)")
print("=" * 80)
print(f"프로젝트 경로: {project_path}")
print(f"출력 경로: {output_dir}")
use_db = all([args.db_host, args.db_user, args.db_password, args.db_name])
if use_db:
print(f"DB 연결: {args.db_user}@{args.db_host}:{args.db_port}/{args.db_name}")
else:
print("DB 연결: 사용 안 함")
print()
if not os.path.exists(project_path):
print(f"✖ 오류: 프로젝트 경로를 찾을 수 없습니다: {project_path}")
sys.exit(1)
print("1. 프로젝트 전체에서 엔티티 파일 검색 중...\n")
if args.log:
log_path = args.log
else:
log_path = os.path.join(output_dir, f"entity_parser_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
entity_parser = EntityParser(project_path, log_path)
entities = entity_parser.parse_all_entities()
print(f"\n✓ 총 {len(entities)}개의 엔티티를 찾았습니다.")
print(f"✓ 상세 로그: {log_path}\n")
if not entities:
print("✖ 엔티티 파일을 찾을 수 없습니다.")
sys.exit(1)
package_count = {}
for entity in entities:
pkg = entity['package']
package_count[pkg] = package_count.get(pkg, 0) + 1
print("패키지별 엔티티 개수:")
for pkg, count in sorted(package_count.items()):
print(f" - {pkg}: {count}개")
db_columns = {}
if use_db:
print("\n2. 데이터베이스 연결 중...\n")
db_connector = DatabaseConnector(
args.db_host,
args.db_port,
args.db_user,
args.db_password,
args.db_name
)
if db_connector.connect():
db_columns = db_connector.get_table_columns()
db_connector.close()
else:
print("⚠️ DB 연결 실패. Entity 정보만 사용합니다.")
print("\n3. 테이블 명세서 생성 중...\n")
generator = SpecGenerator(entities, db_columns)
excel_path = os.path.join(output_dir, "테이블명세서.xlsx")
md_path = os.path.join(output_dir, "테이블명세서.md")
sql_path = os.path.join(output_dir, "add_comments.sql")
generator.generate_excel(excel_path)
generator.generate_markdown(md_path)
generator.generate_ddl_comment(sql_path)
print("\n" + "=" * 80)
print("✅ 테이블 명세서 생성이 완료되었습니다!")
print("=" * 80)
print("생성된 파일:")
print(f" - {excel_path}")
print(f" - {md_path}")
print(f" - {sql_path}")
print(f" - {log_path}")
if use_db and db_columns:
print("\n💡 Tip: SQL 파일은 실제 DB 정보를 기반으로 생성되어 안전합니다.")
else:
print("\n⚠️ 주의: SQL 파일은 Entity 정보만으로 생성되었습니다.")
print(" 실행 전 반드시 검토하세요!")
print("\n💡 더 안전하게 사용하려면 DB 연결 옵션을 사용하세요:")
print(" python3 entity_spec_generator.py <project_path> \\")
print(" --db-host localhost --db-user root \\")
print(" --db-password pass --db-name dbname")
print("=" * 80)
if __name__ == "__main__":
main()