1 // ER diagram description parser
4 constructor(description
)
7 this.inheritances
= [ ];
8 this.associations
= [ ];
10 this.mcdParsing(description
);
12 // Cache SVG graphs returned by server (in addition to server cache = good perfs)
30 ///////////////////////////////
31 // PARSING STAGE 1: text to MCD
32 ///////////////////////////////
34 // Parse a textual description into a json object
37 let lines
= text
.split("\n");
38 lines
.push(""); //easier parsing: always empty line at the end
40 for (let i
=0; i
< lines
.length
; i
++)
42 lines
[i
] = lines
[i
].trim();
44 if (lines
[i
].length
== 0)
46 if (start
>= 0) //there is some group of lines to parse
48 this.parseThing(lines
, start
, i
);
52 else //not empty line: just register starting point
60 // Parse a group of lines into entity, association, ...
61 parseThing(lines
, start
, end
) //start included, end excluded
63 switch (lines
[start
].charAt(0))
66 // Entity = { name: { attributes, [weak] } }
67 let name
= lines
[start
].match(/[^\[\]"\s]+/)[0];
68 let entity
= { attributes: this.parseAttributes(lines
, start
+1, end
) };
69 if (lines
[start
].charAt(1) == '[')
71 this.entities
[name
] = entity
;
73 case 'i': //inheritance (arrows)
74 this.inheritances
= this.inheritances
.concat(this.parseInheritance(lines
, start
+1, end
));
76 case '{': //association
77 // Association = { [name], [attributes], [weak], entities: ArrayOf entity indices }
78 let relationship
= { };
79 let nameRes
= lines
[start
].match(/[^{}"\s]+/);
81 relationship
.name
= nameRes
[0];
82 if (lines
[start
].charAt(1) == '{')
83 relationship
.weak
= true;
84 this.associations
.push(Object
.assign({}, relationship
, this.parseAssociation(lines
, start
+1, end
)));
89 // attributes: ArrayOf {name, [isKey], [type], [qualifiers]}
90 parseAttributes(lines
, start
, end
)
93 for (let i
=start
; i
<end
; i
++)
97 if (line
.charAt(0) == '#')
100 line
= line
.slice(1);
102 field
.name
= line
.match(/[^()"\s]+/)[0];
103 let parenthesis
= line
.match(/\((.+)\)/);
104 if (parenthesis
!== null)
106 let sqlClues
= parenthesis
[1];
107 field
.type
= sqlClues
.match(/[^\s]+/)[0]; //type is always the first indication (mandatory)
108 field
.qualifiers
= sqlClues
.substring(field
.type
.length
).trim();
110 attributes
.push(field
);
115 // GroupOf Inheritance: { parent, children: ArrayOf entity indices }
116 parseInheritance(lines
, start
, end
)
118 let inheritance
= [];
119 for (let i
=start
; i
<end
; i
++)
121 let lineParts
= lines
[i
].split(" ");
123 for (let j
=1; j
<lineParts
.length
; j
++)
124 children
.push(lineParts
[j
]);
125 inheritance
.push({ parent:lineParts
[0], children: children
});
130 // Association (parsed here): {
131 // entities: ArrayOf entity names + cardinality,
132 // [attributes: ArrayOf {name, [isKey], [type], [qualifiers]}]
134 parseAssociation(lines
, start
, end
)
141 if (lines
[i
].charAt(0) == '-')
143 assoce
.attributes
= this.parseAttributes(lines
, i
+1, end
);
148 // Read entity name + cardinality
149 let lineParts
= lines
[i
].split(" ");
150 entities
.push({ name:lineParts
[0], card:lineParts
[1] });
154 assoce
.entities
= entities
;
158 //////////////////////////////
159 // PARSING STAGE 2: MCD to MLD
160 //////////////////////////////
162 // From entities + relationships to tables
165 // Pass 1: initialize tables
166 Object
.keys(this.entities
).forEach( name
=> {
167 let newTable
= [ ]; //array of fields
168 this.entities
[name
].attributes
.forEach( attr
=> {
173 qualifiers: attr
.qualifiers
,
176 this.tables
[name
] = newTable
;
178 // Pass 2: parse associations, add foreign keys when cardinality is 0,1 or 1,1
179 this.associations
.forEach( a
=> {
180 let newTableAttrs
= [ ];
181 a
.entities
.forEach( e
=> {
182 if (['?','1'].includes(e
.card
[0]))
184 // Foreign key apparition (for each entity in association minus current one, for each identifying attribute)
185 a
.entities
.forEach( e2
=> {
186 if (e2
.name
== e
.name
)
188 e2
.attributes
.forEach( attr
=> {
191 this.tables
[e
.name
].push({
192 isKey: e
.card
.length
>= 2 && e
.card
[1] == 'R', //"weak tables" foreign keys become part of the key
193 name: "#" + e2
.name
+ "_" + attr
.name
,
195 qualifiers: "foreign key references " + e2
.name
+ " " + (e
.card
[0]=='1' : "not null" : ""),
196 ref: e2
.name
, //easier drawMld function (fewer regexps)
204 // Add all keys in current entity
205 let fields
= e
.attributes
.filter( attr
=> { return attr
.isKey
; });
212 if (newTableAttrs
.length
> 1)
214 // Ok, really create a new table
216 name: a
.name
|| newTableAttrs
.map( item
=> { return item
.entity
; }).join("_");
219 newTableAttrs
.forEach( item
=> {
220 item
.fields
.forEach( f
=> {
221 newTable
.fields
.push({
222 name: item
.entity
+ "_" + f
.name
,
225 qualifiers: (f
.qualifiers
+" " || "") + "foreign key references " + item
.entity
+ " not null",
230 // Add relationship potential own attributes
231 a
.attributes
.forEach( attr
=> {
232 newTable
.fields
.push({
236 qualifiers: attr
.qualifiers
,
239 this.tables
[newTable
.name
] = newTable
.fields
;
244 /////////////////////////////////
245 // DRAWING + GET SQL FROM PARSING
246 /////////////////////////////////
248 static AjaxGet(dotInput
, callback
)
250 let xhr
= new XMLHttpRequest();
251 xhr
.onreadystatechange = function() {
252 if (this.readyState
== 4 && this.status
== 200)
253 callback(this.responseText
);
255 xhr
.open("GET", "scripts/getGraphSvg.php?dot=" + encodeURIComponent(dotInput
), true);
259 // "Modèle conceptuel des données". TODO: option for graph size
260 // NOTE: randomizing helps to obtain better graphs (sometimes)
261 drawMcd(id
, mcdStyle
) //mcdStyle: bubble, or compact
263 let element
= document
.getElementById(id
);
264 mcdStyle
= mcdStyle
|| "compact";
265 if (this.mcdGraph
.length
> 0)
267 element
.innerHTML
= this.mcdGraph
;
270 // Build dot graph input
271 let mcdDot
= 'graph {\n';
272 mcdDot
+= 'rankdir="LR";\n';
274 if (mcdStyle
== "compact")
275 mcdDot
+= 'node [shape=plaintext];\n';
276 _
.shuffle(Object
.keys(this.entities
)).forEach( name
=> {
277 if (mcdStyle
== "bubble")
279 mcdDot
+= '"' + name
+ '" [shape=rectangle, label="' + name
+ '"';
280 if (this.entities
[name
].weak
)
281 mcdDot
+= ', peripheries=2';
283 if (!!this.entities
[name
].attributes
)
285 this.entities
[name
].attributes
.forEach( a
=> {
286 let label
= (a
.isKey
? '#' : '') + a
.name
;
287 let attrName
= name
+ '_' + a
.name
;
288 mcdDot
+= '"' + attrName
+ '" [shape=ellipse, label="' + label
+ '"];\n';
289 if (Math
.random() < 0.5)
290 mcdDot
+= '"' + attrName
+ '" -- "' + name
+ '";\n';
292 mcdDot
+= '"' + name
+ '" -- "' + attrName
+ '";\n';
298 mcdDot
+= '"' + name
+ '" [label=<';
299 if (this.entities
[name
].weak
)
301 mcdDot
+= '<table port="name" BORDER="1" ALIGN="LEFT" CELLPADDING="0" CELLSPACING="3" CELLBORDER="0">' +
302 '<tr><td><table BORDER="1" ALIGN="LEFT" CELLPADDING="5" CELLSPACING="0">\n';
305 mcdDot
+= '<table port="name" BORDER="1" ALIGN="LEFT" CELLPADDING="5" CELLSPACING="0">\n';
306 mcdDot
+= '<tr><td BGCOLOR="#ae7d4e" BORDER="0"><font COLOR="#FFFFFF">' + name
+ '</font></td></tr>\n';
307 if (!!this.entities
[name
].attributes
)
309 this.entities
[name
].attributes
.forEach( a
=> {
310 let label
= (a
.isKey
? '<u>' : '') + a
.name
+ (a
.isKey
? '</u>' : '');
311 mcdDot
+= '<tr><td BGCOLOR="#FFFFFF" BORDER="0" ALIGN="LEFT"><font COLOR="#000000" >' + label
+ '</font></td></tr>\n';
314 mcdDot
+= '</table>';
315 if (this.entities
[name
].weak
)
316 mcdDot
+= '</td></tr></table>';
321 _
.shuffle(this.inheritances
).forEach( i
=> {
322 // TODO: node shape = triangle fill yellow. See
323 // https://merise.developpez.com/faq/?page=MCD#CIF-ou-dependance-fonctionnelle-de-A-a-Z
324 // https://merise.developpez.com/faq/?page=MLD#Comment-transformer-un-MCD-en-MLD
325 // https://www.developpez.net/forums/d1088964/general-developpement/alm/modelisation/structure-agregation-l-association-d-association/
326 _
.shuffle(i
.children
).forEach( c
=> {
327 if (Math
.random() < 0.5)
328 mcdDot
+= '"' + c
+ '":name -- "' + i
.parent
;
330 mcdDot
+= '"' + i
.parent
+ '":name -- "' + c
;
331 mcdDot
+= '":name [dir="forward", arrowhead="vee", style="dashed"];\n';
335 if (mcdStyle
== "compact")
336 mcdDot
+= 'node [shape=rectangle, style=rounded];\n';
337 let assoceCounter
= 0;
338 _
.shuffle(this.associations
).forEach( a
=> {
339 let name
= a
.name
|| "_assoce" + assoceCounter
++;
340 if (mcdStyle
== "bubble")
342 mcdDot
+= '"' + name
+ '" [shape="diamond", style="filled", color="lightgrey", label="' + name
+ '"';
344 mcdDot
+= ', peripheries=2';
348 a
.attributes
.forEach( attr
=> {
349 let label
= (attr
.isKey
? '#' : '') + attr
.name
;
350 mcdDot
+= '"' + name
+ '_' + attr
.name
+ '" [shape=ellipse, label="' + label
+ '"];\n';
351 let attrName
= name
+ '_' + attr
.name
;
352 if (Math
.random() < 0.5)
353 mcdDot
+= '"' + attrName
+ '" -- "' + name
+ '";\n';
355 mcdDot
+= '"' + name
+ '" -- "' + attrName
+ '";\n';
361 let label
= '<' + name
+ '>';
364 a
.attributes
.forEach( attr
=> {
365 let attrLabel
= (attr
.isKey
? '#' : '') + attr
.name
;
366 label
+= '\\n' + attrLabel
;
369 mcdDot
+= '"' + name
+ '" [color="lightgrey", label="' + label
+ '"';
371 mcdDot
+= ', peripheries=2';
374 _
.shuffle(a
.entities
).forEach( e
=> {
375 if (Math
.random() < 0.5)
376 mcdDot
+= '"' + e
.name
+ '":name -- "' + name
+ '"';
378 mcdDot
+= '"' + name
+ '" -- "' + e
.name
+ '":name';
379 mcdDot
+= '[label="' + ErDiags
.CARDINAL
[e
.card
] + '"];\n';
384 ErDiags
.AjaxGet(mcdDot
, graphSvg
=> {
385 this.mcdGraph
= graphSvg
;
386 element
.innerHTML
= graphSvg
;
390 // "Modèle logique des données", from MCD without anomalies
391 // TODO: this one should draw links from foreign keys to keys (port=... in <TD>)
394 let element
= document
.getElementById(id
);
395 if (this.mldGraph
.length
> 0)
397 element
.innerHTML
= this.mcdGraph
;
400 // Build dot graph input (assuming foreign keys not already present...)
401 let mldDot
= 'graph {\n';
402 mldDot
+= 'node [shape=plaintext];\n';
404 _
.shuffle(Object
.keys(this.tables
)).forEach( name
=> {
405 mldDot
+= '"' + name
+ '" [label=<<table BORDER="1" ALIGN="LEFT" CELLPADDING="5" CELLSPACING="0">\n';
406 mldDot
+= '<tr><td BGCOLOR="#ae7d4e" BORDER="0"><font COLOR="#FFFFFF">' + name
+ '</font></td></tr>\n';
407 this.tables
[name
].fields
.forEach( f
=> {
408 let label
= (f
.isKey
? '<u>' : '') + (!!f
.qualifiers
&& f
.qualifiers
.indexOf("foreign")>=0 ? '#' : '') + f
.name
+ (f
.isKey
? '</u>' : '');
409 mldDot
+= '<tr><td port="' + f
.name
+ '"' + (f
.isKey
? ' port="__key"' : '')
410 + ' BGCOLOR="#FFFFFF" BORDER="0" ALIGN="LEFT"><font COLOR="#000000" >' + label
+ '</font></td></tr>\n';
413 if (Math
.random() < 0.5)
414 links
+= '"' + f
.ref
+ '":__key -- "' + '"'+name
+'":"'+f
.name
+'"\n';
416 links
+= '"'+name
+'":"'+f
.name
+'" -- "' + f
.ref
+ '":__key\n';
419 mldDot
+= '</table>>];\n';
421 mldDot
+= links
+ '\n';
423 //console.log(mldDot);
424 ErDiags
.AjaxGet(mldDot
, graphSvg
=> {
425 this.mldGraph
= graphSvg
;
426 element
.innerHTML
= graphSvg
;
432 let element
= document
.getElementById(id
);
433 if (this.sqlText
.length
> 0)
435 element
.innerHTML
= this.sqlText
;
439 Object
.keys(this.tables
).forEach( name
=> {
440 sqlText
+= "CREATE TABLE " + name
+ " (\n";
442 this.tables
[name
].forEach( f
=> {
443 sqlText
+= f
.name
+ " " + (f
.type
|| "TEXT") + (" "+f
.qualifiers
|| "") + ",\n";
445 key
+= (key
.length
>0 ? "," : "") + f
.name
;
447 sqlText
+= "PRIMARY KEY (" + key
+ ")\n";
450 //console.log(sqlText);
451 this.sqlText
= sqlText
;
452 element
.innerHTML
= "<pre><code>" + sqlText
+ "</code></pre>";