Do not add extra 'NOT NULL' when irrelevant
[erdiag.git] / parser.js
CommitLineData
525c4d2a
BA
1// ER diagram description parser
2class ErDiags
3{
4 constructor(description)
5 {
4ef6cded
BA
6 this.entities = { };
7 this.inheritances = [ ];
8 this.associations = [ ];
19addd10
BA
9 this.tables = { };
10 this.mcdParsing(description);
11 this.mldParsing();
525c4d2a
BA
12 // Cache SVG graphs returned by server (in addition to server cache = good perfs)
13 this.mcdGraph = "";
14 this.mldGraph = "";
15 this.sqlText = "";
16 }
17
7a80e6db 18 static CARDINAL(symbol)
525c4d2a 19 {
7a80e6db
BA
20 let res = { "*": "0,n", "+": "1,n", "?": "0,1", "1": "1,1" } [ symbol[0] ];
21 if (symbol.length >= 2)
22 {
23 if (symbol[1] == 'R')
24 res = '(' + res + ')';
25 else if (['>','<'].includes(symbol[1]))
26 res += symbol[1];
27 }
28 return res;
525c4d2a
BA
29 }
30
19addd10
BA
31 ///////////////////////////////
32 // PARSING STAGE 1: text to MCD
33 ///////////////////////////////
525c4d2a
BA
34
35 // Parse a textual description into a json object
19addd10 36 mcdParsing(text)
525c4d2a
BA
37 {
38 let lines = text.split("\n");
39 lines.push(""); //easier parsing: always empty line at the end
40 let start = -1;
41 for (let i=0; i < lines.length; i++)
42 {
43 lines[i] = lines[i].trim();
44 // Empty line ?
45 if (lines[i].length == 0)
46 {
47 if (start >= 0) //there is some group of lines to parse
48 {
49 this.parseThing(lines, start, i);
50 start = -1;
51 }
52 }
53 else //not empty line: just register starting point
54 {
55 if (start < 0)
56 start = i;
57 }
58 }
59 }
60
61 // Parse a group of lines into entity, association, ...
62 parseThing(lines, start, end) //start included, end excluded
63 {
64 switch (lines[start].charAt(0))
65 {
66 case '[':
67 // Entity = { name: { attributes, [weak] } }
006d95a3 68 let name = lines[start].match(/[^\[\]"\s]+/)[0];
525c4d2a
BA
69 let entity = { attributes: this.parseAttributes(lines, start+1, end) };
70 if (lines[start].charAt(1) == '[')
71 entity.weak = true;
72 this.entities[name] = entity;
73 break;
74 case 'i': //inheritance (arrows)
75 this.inheritances = this.inheritances.concat(this.parseInheritance(lines, start+1, end));
76 break;
77 case '{': //association
78 // Association = { [name], [attributes], [weak], entities: ArrayOf entity indices }
79 let relationship = { };
006d95a3 80 let nameRes = lines[start].match(/[^{}"\s]+/);
525c4d2a
BA
81 if (nameRes !== null)
82 relationship.name = nameRes[0];
83 if (lines[start].charAt(1) == '{')
84 relationship.weak = true;
85 this.associations.push(Object.assign({}, relationship, this.parseAssociation(lines, start+1, end)));
86 break;
87 }
88 }
89
90 // attributes: ArrayOf {name, [isKey], [type], [qualifiers]}
91 parseAttributes(lines, start, end)
92 {
5fe4fa10 93 let attributes = [ ];
525c4d2a
BA
94 for (let i=start; i<end; i++)
95 {
d6c9499e
BA
96 let field = { };
97 let line = lines[i];
6a430a22 98 if (line.charAt(0) == '+')
d6c9499e 99 {
525c4d2a 100 field.isKey = true;
d6c9499e
BA
101 line = line.slice(1);
102 }
8edb29ff
BA
103 field.name = line.match(/[^"\s]+/)[0];
104 let sqlClues = line.substring(field.name.length).trim();
105 if (sqlClues.length > 0)
525c4d2a 106 {
19addd10 107 field.type = sqlClues.match(/[^\s]+/)[0]; //type is always the first indication (mandatory)
8edb29ff 108 field.qualifiers = sqlClues.substring(field.type.length);
525c4d2a
BA
109 }
110 attributes.push(field);
111 }
112 return attributes;
113 }
114
115 // GroupOf Inheritance: { parent, children: ArrayOf entity indices }
116 parseInheritance(lines, start, end)
117 {
118 let inheritance = [];
119 for (let i=start; i<end; i++)
120 {
121 let lineParts = lines[i].split(" ");
122 let children = [];
123 for (let j=1; j<lineParts.length; j++)
124 children.push(lineParts[j]);
125 inheritance.push({ parent:lineParts[0], children: children });
126 }
127 return inheritance;
128 }
129
c728aeca
BA
130 // Association (parsed here): {
131 // entities: ArrayOf entity names + cardinality,
132 // [attributes: ArrayOf {name, [isKey], [type], [qualifiers]}]
133 // }
525c4d2a
BA
134 parseAssociation(lines, start, end)
135 {
136 let assoce = { };
137 let entities = [];
138 let i = start;
139 while (i < end)
140 {
141 if (lines[i].charAt(0) == '-')
142 {
143 assoce.attributes = this.parseAttributes(lines, i+1, end);
144 break;
145 }
146 else
147 {
148 // Read entity name + cardinality
149 let lineParts = lines[i].split(" ");
150 entities.push({ name:lineParts[0], card:lineParts[1] });
151 }
152 i++;
153 }
154 assoce.entities = entities;
155 return assoce;
156 }
157
19addd10
BA
158 //////////////////////////////
159 // PARSING STAGE 2: MCD to MLD
160 //////////////////////////////
161
162 // From entities + relationships to tables
163 mldParsing()
164 {
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 => {
8edb29ff 169 let newField = {
19addd10
BA
170 name: attr.name,
171 type: attr.type,
172 isKey: attr.isKey,
173 qualifiers: attr.qualifiers,
8edb29ff
BA
174 };
175 if (!!attr.qualifiers && !!attr.qualifiers.match(/foreign/i))
176 Object.assign(newField, {ref: attr.qualifiers.match(/references ([^\s]+)/i)[1]});
177 newTable.push(newField);
19addd10
BA
178 });
179 this.tables[name] = newTable;
180 });
3ca1e50c
BA
181 // Add foreign keys information for children (inheritance). TODO: allow several levels
182 // NOTE: modelisation assume each child has its own table, refering parent (other options exist)
183 this.inheritances.forEach( inh => {
184 let idx = this.tables[inh.parent].findIndex( item => { return item.isKey; });
185 inh.children.forEach( c => {
186 this.tables[c].push({
187 name: inh.parent + "_id",
188 type: this.tables[inh.parent][idx].type,
189 isKey: true,
190 qualifiers: (this.tables[inh.parent][idx].qualifiers || "") + " foreign key references " + inh.parent,
191 ref: inh.parent,
192 });
193 });
194 });
19addd10
BA
195 // Pass 2: parse associations, add foreign keys when cardinality is 0,1 or 1,1
196 this.associations.forEach( a => {
197 let newTableAttrs = [ ];
0133e929 198 let hasZeroOne = false;
19addd10
BA
199 a.entities.forEach( e => {
200 if (['?','1'].includes(e.card[0]))
201 {
0133e929 202 hasZeroOne = true;
19addd10
BA
203 // Foreign key apparition (for each entity in association minus current one, for each identifying attribute)
204 a.entities.forEach( e2 => {
205 if (e2.name == e.name)
206 return;
5fe4fa10 207 this.entities[e2.name].attributes.forEach( attr => {
19addd10
BA
208 if (attr.isKey)
209 {
2a12fea9
BA
210 // For "weak tables", foreign keys become part of the key
211 const isKey = e.card.length >= 2 && e.card[1] == 'R';
19addd10 212 this.tables[e.name].push({
2a12fea9 213 isKey: isKey,
3ca1e50c 214 name: e2.name + "_" + attr.name,
19addd10 215 type: attr.type,
2a12fea9 216 qualifiers: "foreign key references " + e2.name + " " + (!isKey && e.card[0]=='1' ? "not null" : ""),
19addd10
BA
217 ref: e2.name, //easier drawMld function (fewer regexps)
218 });
219 }
220 });
221 });
222 }
223 else
224 {
225 // Add all keys in current entity
351d7a84 226 let fields = this.entities[e.name].attributes.filter( attr => { return attr.isKey; });
19addd10
BA
227 newTableAttrs.push({
228 fields: fields,
229 entity: e.name,
230 });
231 }
351d7a84 232 });
0133e929 233 if (!hasZeroOne && newTableAttrs.length > 1)
19addd10
BA
234 {
235 // Ok, really create a new table
236 let newTable = {
351d7a84 237 name: a.name || newTableAttrs.map( item => { return item.entity; }).join("_"),
19addd10
BA
238 fields: [ ],
239 };
240 newTableAttrs.forEach( item => {
241 item.fields.forEach( f => {
242 newTable.fields.push({
243 name: item.entity + "_" + f.name,
244 isKey: true,
351d7a84 245 type: f.type,
2a12fea9 246 qualifiers: (f.qualifiers || "") + " foreign key references " + item.entity,
19addd10
BA
247 ref: item.entity,
248 });
249 });
250 });
7a80e6db
BA
251 // Check for duplicates (in case of self-relationship), rename if needed
252 newTable.fields.forEach( (f,i) => {
253 const idx = newTable.fields.findIndex( item => { return item.name == f.name; });
254 if (idx < i)
255 {
256 // Current field is a duplicate
257 let suffix = 2;
258 let newName = f.name + suffix;
259 while (newTable.fields.findIndex( item => { return item.name == newName; }) >= 0)
260 {
261 suffix++;
262 newName = f.name + suffix;
263 }
264 f.name = newName;
265 }
266 });
19addd10 267 // Add relationship potential own attributes
5fe4fa10 268 (a.attributes || [ ]).forEach( attr => {
19addd10
BA
269 newTable.fields.push({
270 name: attr.name,
271 isKey: false,
272 type: attr.type,
273 qualifiers: attr.qualifiers,
274 });
275 });
276 this.tables[newTable.name] = newTable.fields;
277 }
278 });
279 }
280
281 /////////////////////////////////
282 // DRAWING + GET SQL FROM PARSING
283 /////////////////////////////////
525c4d2a
BA
284
285 static AjaxGet(dotInput, callback)
286 {
287 let xhr = new XMLHttpRequest();
288 xhr.onreadystatechange = function() {
289 if (this.readyState == 4 && this.status == 200)
290 callback(this.responseText);
291 };
292 xhr.open("GET", "scripts/getGraphSvg.php?dot=" + encodeURIComponent(dotInput), true);
293 xhr.send();
294 }
295
296 // "Modèle conceptuel des données". TODO: option for graph size
48a55161 297 // NOTE: randomizing helps to obtain better graphs (sometimes)
525c4d2a
BA
298 drawMcd(id, mcdStyle) //mcdStyle: bubble, or compact
299 {
300 let element = document.getElementById(id);
301 mcdStyle = mcdStyle || "compact";
302 if (this.mcdGraph.length > 0)
303 {
304 element.innerHTML = this.mcdGraph;
305 return;
306 }
307 // Build dot graph input
308 let mcdDot = 'graph {\n';
48a55161 309 mcdDot += 'rankdir="LR";\n';
525c4d2a 310 // Nodes:
48a55161 311 if (mcdStyle == "compact")
c728aeca 312 mcdDot += 'node [shape=plaintext];\n';
48a55161 313 _.shuffle(Object.keys(this.entities)).forEach( name => {
525c4d2a
BA
314 if (mcdStyle == "bubble")
315 {
006d95a3 316 mcdDot += '"' + name + '" [shape=rectangle, label="' + name + '"';
525c4d2a
BA
317 if (this.entities[name].weak)
318 mcdDot += ', peripheries=2';
319 mcdDot += '];\n';
320 if (!!this.entities[name].attributes)
321 {
b74cfe41 322 this.entities[name].attributes.forEach( a => {
525c4d2a 323 let label = (a.isKey ? '#' : '') + a.name;
48a55161 324 let attrName = name + '_' + a.name;
006d95a3 325 mcdDot += '"' + attrName + '" [shape=ellipse, label="' + label + '"];\n';
48a55161 326 if (Math.random() < 0.5)
006d95a3 327 mcdDot += '"' + attrName + '" -- "' + name + '";\n';
48a55161 328 else
006d95a3 329 mcdDot += '"' + name + '" -- "' + attrName + '";\n';
525c4d2a
BA
330 });
331 }
332 }
333 else
334 {
006d95a3 335 mcdDot += '"' + name + '" [label=<';
525c4d2a
BA
336 if (this.entities[name].weak)
337 {
338 mcdDot += '<table port="name" BORDER="1" ALIGN="LEFT" CELLPADDING="0" CELLSPACING="3" CELLBORDER="0">' +
339 '<tr><td><table BORDER="1" ALIGN="LEFT" CELLPADDING="5" CELLSPACING="0">\n';
340 }
341 else
342 mcdDot += '<table port="name" BORDER="1" ALIGN="LEFT" CELLPADDING="5" CELLSPACING="0">\n';
343 mcdDot += '<tr><td BGCOLOR="#ae7d4e" BORDER="0"><font COLOR="#FFFFFF">' + name + '</font></td></tr>\n';
344 if (!!this.entities[name].attributes)
345 {
b74cfe41 346 this.entities[name].attributes.forEach( a => {
525c4d2a
BA
347 let label = (a.isKey ? '<u>' : '') + a.name + (a.isKey ? '</u>' : '');
348 mcdDot += '<tr><td BGCOLOR="#FFFFFF" BORDER="0" ALIGN="LEFT"><font COLOR="#000000" >' + label + '</font></td></tr>\n';
349 });
350 }
351 mcdDot += '</table>';
352 if (this.entities[name].weak)
353 mcdDot += '</td></tr></table>';
354 mcdDot += '>];\n';
355 }
356 });
357 // Inheritances:
006d95a3 358 _.shuffle(this.inheritances).forEach( i => {
a2d8ba72
BA
359 // TODO: node shape = triangle fill yellow. See
360 // https://merise.developpez.com/faq/?page=MCD#CIF-ou-dependance-fonctionnelle-de-A-a-Z
361 // https://merise.developpez.com/faq/?page=MLD#Comment-transformer-un-MCD-en-MLD
362 // https://www.developpez.net/forums/d1088964/general-developpement/alm/modelisation/structure-agregation-l-association-d-association/
48a55161
BA
363 _.shuffle(i.children).forEach( c => {
364 if (Math.random() < 0.5)
3ca1e50c 365 mcdDot += '"' + c + '":name -- "' + i.parent + '":name [dir="forward",arrowhead="vee",';
48a55161 366 else
3ca1e50c
BA
367 mcdDot += '"' + i.parent + '":name -- "' + c + '":name [dir="back",arrowtail="vee",';
368 mcdDot += 'style="dashed"];\n';
525c4d2a
BA
369 });
370 });
371 // Relationships:
c728aeca
BA
372 if (mcdStyle == "compact")
373 mcdDot += 'node [shape=rectangle, style=rounded];\n';
525c4d2a 374 let assoceCounter = 0;
48a55161 375 _.shuffle(this.associations).forEach( a => {
19addd10 376 let name = a.name || "_assoce" + assoceCounter++;
c728aeca
BA
377 if (mcdStyle == "bubble")
378 {
379 mcdDot += '"' + name + '" [shape="diamond", style="filled", color="lightgrey", label="' + name + '"';
380 if (a.weak)
381 mcdDot += ', peripheries=2';
382 mcdDot += '];\n';
383 if (!!a.attributes)
384 {
385 a.attributes.forEach( attr => {
386 let label = (attr.isKey ? '#' : '') + attr.name;
387 mcdDot += '"' + name + '_' + attr.name + '" [shape=ellipse, label="' + label + '"];\n';
388 let attrName = name + '_' + attr.name;
389 if (Math.random() < 0.5)
390 mcdDot += '"' + attrName + '" -- "' + name + '";\n';
391 else
392 mcdDot += '"' + name + '" -- "' + attrName + '";\n';
393 });
394 }
395 }
396 else
397 {
4ef6cded 398 let label = '<' + name + '>';
c728aeca
BA
399 if (!!a.attributes)
400 {
401 a.attributes.forEach( attr => {
402 let attrLabel = (attr.isKey ? '#' : '') + attr.name;
4ef6cded 403 label += '\\n' + attrLabel;
c728aeca
BA
404 });
405 }
406 mcdDot += '"' + name + '" [color="lightgrey", label="' + label + '"';
407 if (a.weak)
408 mcdDot += ', peripheries=2';
409 mcdDot += '];\n';
410 }
48a55161
BA
411 _.shuffle(a.entities).forEach( e => {
412 if (Math.random() < 0.5)
006d95a3 413 mcdDot += '"' + e.name + '":name -- "' + name + '"';
48a55161 414 else
006d95a3 415 mcdDot += '"' + name + '" -- "' + e.name + '":name';
7a80e6db 416 mcdDot += '[label="' + ErDiags.CARDINAL(e.card) + '"];\n';
525c4d2a 417 });
525c4d2a
BA
418 });
419 mcdDot += '}';
3ca1e50c 420 //console.log(mcdDot);
525c4d2a
BA
421 ErDiags.AjaxGet(mcdDot, graphSvg => {
422 this.mcdGraph = graphSvg;
423 element.innerHTML = graphSvg;
d6c9499e 424 });
525c4d2a
BA
425 }
426
19addd10 427 // "Modèle logique des données", from MCD without anomalies
48a55161 428 // TODO: this one should draw links from foreign keys to keys (port=... in <TD>)
525c4d2a
BA
429 drawMld(id)
430 {
431 let element = document.getElementById(id);
432 if (this.mldGraph.length > 0)
433 {
434 element.innerHTML = this.mcdGraph;
435 return;
436 }
4ef6cded 437 // Build dot graph input (assuming foreign keys not already present...)
e2610c05 438 let mldDot = 'graph {\n';
3ca1e50c 439 mldDot += 'rankdir="LR";\n';
19addd10
BA
440 mldDot += 'node [shape=plaintext];\n';
441 let links = "";
442 _.shuffle(Object.keys(this.tables)).forEach( name => {
443 mldDot += '"' + name + '" [label=<<table BORDER="1" ALIGN="LEFT" CELLPADDING="5" CELLSPACING="0">\n';
444 mldDot += '<tr><td BGCOLOR="#ae7d4e" BORDER="0"><font COLOR="#FFFFFF">' + name + '</font></td></tr>\n';
351d7a84 445 this.tables[name].forEach( f => {
8edb29ff 446 let label = (f.isKey ? '<u>' : '') + (!!f.ref ? '#' : '') + f.name + (f.isKey ? '</u>' : '');
3ca1e50c 447 mldDot += '<tr><td port="' + f.name + '"' + ' BGCOLOR="#FFFFFF" BORDER="0" ALIGN="LEFT"><font COLOR="#000000" >' + label + '</font></td></tr>\n';
19addd10 448 if (!!f.ref)
4ef6cded 449 {
3ca1e50c
BA
450 // Need to find a key attribute in reference entity (the first...)
451 let keyInRef = "";
452 for (let field of this.tables[f.ref])
453 {
454 if (field.isKey)
455 {
456 keyInRef = field.name;
457 break;
458 }
459 }
19addd10 460 if (Math.random() < 0.5)
3ca1e50c 461 links += '"' + f.ref + '":"' + keyInRef + '" -- "' + name+'":"'+f.name + '" [dir="forward",arrowhead="dot"';
19addd10 462 else
3ca1e50c
BA
463 links += '"'+name+'":"'+f.name+'" -- "' + f.ref + '":"' + keyInRef + '" [dir="back",arrowtail="dot"';
464 links += ']\n;';
19addd10 465 }
e2610c05 466 });
19addd10 467 mldDot += '</table>>];\n';
e2610c05 468 });
19addd10
BA
469 mldDot += links + '\n';
470 mldDot += '}\n';
3ca1e50c 471 //console.log(mldDot);
d6c9499e
BA
472 ErDiags.AjaxGet(mldDot, graphSvg => {
473 this.mldGraph = graphSvg;
474 element.innerHTML = graphSvg;
475 });
525c4d2a
BA
476 }
477
478 fillSql(id)
479 {
480 let element = document.getElementById(id);
481 if (this.sqlText.length > 0)
482 {
483 element.innerHTML = this.sqlText;
484 return;
485 }
19addd10
BA
486 let sqlText = "";
487 Object.keys(this.tables).forEach( name => {
488 sqlText += "CREATE TABLE " + name + " (\n";
489 let key = "";
490 this.tables[name].forEach( f => {
8edb29ff
BA
491 let type = f.type || (f.isKey ? "INTEGER" : "TEXT");
492 sqlText += "\t" + f.name + " " + type + " " + (f.qualifiers || "") + ",\n";
19addd10
BA
493 if (f.isKey)
494 key += (key.length>0 ? "," : "") + f.name;
495 });
3ca1e50c 496 sqlText += "\tPRIMARY KEY (" + key + ")\n";
19addd10
BA
497 sqlText += ");\n";
498 });
499 //console.log(sqlText);
500 this.sqlText = sqlText;
501 element.innerHTML = "<pre><code>" + sqlText + "</code></pre>";
525c4d2a
BA
502 }
503}