File size: 6,753 Bytes
f5754cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import graphviz
import json
from tempfile import NamedTemporaryFile
import os

def generate_entity_relationship_diagram(json_input: str, output_format: str) -> str:
    try:
        if not json_input.strip():
            return "Error: Empty input"
            
        data = json.loads(json_input)
        
        if 'entities' not in data:
            raise ValueError("Missing required field: entities")

        dot = graphviz.Graph(
            name='ERDiagram',
            format='png',
            graph_attr={
                'rankdir': 'TB',
                'splines': 'ortho',
                'bgcolor': 'white',
                'pad': '0.5',
                'nodesep': '2.0',
                'ranksep': '2.5'
            }
        )
        
        base_color = '#19191a'
        lightening_factor = 0.15
        
        entities = data.get('entities', [])
        relationships = data.get('relationships', [])
        
        for i, entity in enumerate(entities):
            entity_name = entity.get('name')
            entity_type = entity.get('type', 'strong')
            attributes = entity.get('attributes', [])
            
            if not entity_name:
                raise ValueError(f"Invalid entity: {entity}")
            
            current_depth = i % 6
            
            if not isinstance(base_color, str) or not base_color.startswith('#') or len(base_color) != 7:
                base_color_safe = '#19191a'
            else:
                base_color_safe = base_color
                
            base_r = int(base_color_safe[1:3], 16)
            base_g = int(base_color_safe[3:5], 16)
            base_b = int(base_color_safe[5:7], 16)
            
            current_r = base_r + int((255 - base_r) * current_depth * lightening_factor)
            current_g = base_g + int((255 - base_g) * current_depth * lightening_factor)
            current_b = base_b + int((255 - base_b) * current_depth * lightening_factor)
            
            current_r = min(255, current_r)
            current_g = min(255, current_g)
            current_b = min(255, current_b)
            
            node_color = f'#{current_r:02x}{current_g:02x}{current_b:02x}'
            font_color = 'white' if current_depth * lightening_factor < 0.6 else 'black'
            
            entity_label = f"{entity_name}\\n"
            
            if attributes:
                primary_keys = []
                foreign_keys = []
                regular_attrs = []
                
                for attr in attributes:
                    attr_name = attr.get('name', '')
                    attr_type = attr.get('type', 'key')
                    is_multivalued = attr.get('multivalued', False)
                    is_derived = attr.get('derived', False)
                    is_composite = attr.get('composite', False)
                    
                    if attr_type == 'primary_key':
                        if is_multivalued:
                            primary_keys.append(f"{{{{ {attr_name} }}}}")
                        else:
                            primary_keys.append(f"[PK] {attr_name}")
                    elif attr_type == 'foreign_key':
                        foreign_keys.append(f"[FK] {attr_name}")
                    else:
                        attr_display = attr_name
                        if is_derived:
                            attr_display = f"/ {attr_display} /"
                        if is_multivalued:
                            attr_display = f"{{ {attr_display} }}"
                        if is_composite:
                            attr_display = f"( {attr_display} )"
                        regular_attrs.append(attr_display)
                
                if primary_keys:
                    entity_label += "\\n".join(primary_keys) + "\\n"
                if foreign_keys:
                    entity_label += "\\n".join(foreign_keys) + "\\n"
                if regular_attrs:
                    entity_label += "\\n".join(regular_attrs)
            
            if entity_type == 'weak':
                shape = 'doubleoctagon'
                style = 'filled'
            else:
                shape = 'box'
                style = 'filled,rounded'
            
            dot.node(
                entity_name,
                entity_label,
                shape=shape,
                style=style,
                fillcolor=node_color,
                fontcolor=font_color,
                fontsize='10',
                fontname='Helvetica'
            )
        
        for relationship in relationships:
            rel_name = relationship.get('name')
            rel_type = relationship.get('type', 'regular')
            entities_involved = relationship.get('entities', [])
            cardinalities = relationship.get('cardinalities', {})
            
            if not rel_name or len(entities_involved) < 2:
                raise ValueError(f"Invalid relationship: {relationship}")
            
            rel_node_color = '#e6f3ff'
            
            if rel_type == 'identifying':
                rel_shape = 'diamond'
                rel_style = 'filled,bold'
                rel_color = '#4a90e2'
            elif rel_type == 'weak':
                rel_shape = 'diamond'
                rel_style = 'filled,dashed'
                rel_color = '#a0a0a0'
            else:
                rel_shape = 'diamond'
                rel_style = 'filled'
                rel_color = '#4a90e2'
            
            dot.node(
                rel_name,
                rel_name,
                shape=rel_shape,
                style=rel_style,
                fillcolor=rel_color,
                fontcolor='white',
                fontsize='10',
                fontname='Helvetica'
            )
            
            for entity in entities_involved:
                cardinality = cardinalities.get(entity, '1')
                
                edge_label = cardinality
                if cardinality in ['1:1', '1:N', 'M:N', '1', 'N', 'M']:
                    pass
                else:
                    edge_label = cardinality
                
                dot.edge(
                    entity,
                    rel_name,
                    label=edge_label,
                    color='#4a4a4a',
                    fontsize='9',
                    fontcolor='#4a4a4a'
                )

        with NamedTemporaryFile(delete=False, suffix=f'.{output_format}') as tmp:
            dot.render(tmp.name, format=output_format, cleanup=True)
            return f"{tmp.name}.{output_format}"

    except json.JSONDecodeError:
        return "Error: Invalid JSON format"
    except Exception as e:
        return f"Error: {str(e)}"