0ab6a4321a15f59a62718d39cbfc699d17563e39
[erdiag.git] / parser.js
1 // ER diagram description parser
2 class ErDiags
3 {
4 constructor(description, output, image)
5 {
6 this.entities = { };
7 this.inheritances = [ ];
8 this.associations = [ ];
9 this.tables = { };
10 this.mcdParsing(description);
11 this.mldParsing();
12 this.output = output || "graph";
13 this.image = image || "svg";
14 }
15
16 static CARDINAL(symbol)
17 {
18 let res = { "*": "0,n", "+": "1,n", "?": "0,1", "1": "1,1" } [ symbol[0] ];
19 if (symbol.length >= 2)
20 {
21 if (symbol[1] == 'R')
22 res = '(' + res + ')';
23 else if (['>','<'].includes(symbol[1]))
24 res += symbol[1];
25 }
26 return res;
27 }
28
29 ///////////////////////////////
30 // PARSING STAGE 1: text to MCD
31 ///////////////////////////////
32
33 // Parse a textual description into a json object
34 mcdParsing(text)
35 {
36 let lines = text.split("\n");
37 lines.push(""); //easier parsing: always empty line at the end
38 let start = -1;
39 for (let i=0; i < lines.length; i++)
40 {
41 lines[i] = lines[i].trim();
42 // Empty line ?
43 if (lines[i].length == 0)
44 {
45 if (start >= 0) //there is some group of lines to parse
46 {
47 this.parseThing(lines, start, i);
48 start = -1;
49 }
50 }
51 else //not empty line: just register starting point
52 {
53 if (start < 0)
54 start = i;
55 }
56 }
57 }
58
59 // Parse a group of lines into entity, association, ...
60 parseThing(lines, start, end) //start included, end excluded
61 {
62 switch (lines[start].charAt(0))
63 {
64 case '[':
65 // Entity = { name: { attributes, [weak] } }
66 let name = lines[start].match(/[^\[\]"\s]+/)[0];
67 let entity = { attributes: this.parseAttributes(lines, start+1, end) };
68 if (lines[start].charAt(1) == '[')
69 entity.weak = true;
70 this.entities[name] = entity;
71 break;
72 case 'i': //inheritance (arrows)
73 this.inheritances = this.inheritances.concat(this.parseInheritance(lines, start+1, end));
74 break;
75 case '{': //association
76 // Association = { [name], [attributes], [weak], entities: ArrayOf entity indices }
77 let relationship = { };
78 let nameRes = lines[start].match(/[^{}"\s]+/);
79 if (nameRes !== null)
80 relationship.name = nameRes[0];
81 if (lines[start].charAt(1) == '{')
82 relationship.weak = true;
83 this.associations.push(Object.assign({}, relationship, this.parseAssociation(lines, start+1, end)));
84 break;
85 }
86 }
87
88 // attributes: ArrayOf {name, [isKey], [type], [qualifiers]}
89 parseAttributes(lines, start, end)
90 {
91 let attributes = [ ];
92 for (let i=start; i<end; i++)
93 {
94 let field = { };
95 let line = lines[i];
96 if (line.charAt(0) == '+')
97 {
98 field.isKey = true;
99 line = line.slice(1);
100 }
101 field.name = line.match(/[^"\s]+/)[0];
102 let sqlClues = line.substring(field.name.length).trim();
103 if (sqlClues.length > 0)
104 {
105 field.type = sqlClues.match(/[^\s]+/)[0]; //type is always the first indication (mandatory)
106 field.qualifiers = sqlClues.substring(field.type.length);
107 }
108 attributes.push(field);
109 }
110 return attributes;
111 }
112
113 // GroupOf Inheritance: { parent, children: ArrayOf entity indices }
114 parseInheritance(lines, start, end)
115 {
116 let inheritance = [];
117 for (let i=start; i<end; i++)
118 {
119 let lineParts = lines[i].split(" ");
120 let children = [];
121 for (let j=1; j<lineParts.length; j++)
122 children.push(lineParts[j]);
123 inheritance.push({ parent:lineParts[0], children: children });
124 }
125 return inheritance;
126 }
127
128 // Association (parsed here): {
129 // entities: ArrayOf entity names + cardinality,
130 // [attributes: ArrayOf {name, [isKey], [type], [qualifiers]}]
131 // }
132 parseAssociation(lines, start, end)
133 {
134 let assoce = { };
135 let entities = [];
136 let i = start;
137 while (i < end)
138 {
139 if (lines[i].charAt(0) == '-')
140 {
141 assoce.attributes = this.parseAttributes(lines, i+1, end);
142 break;
143 }
144 else
145 {
146 // Read entity name + cardinality
147 let lineParts = lines[i].split(" ");
148 entities.push({ name:lineParts[0], card:lineParts[1] });
149 }
150 i++;
151 }
152 assoce.entities = entities;
153 return assoce;
154 }
155
156 //////////////////////////////
157 // PARSING STAGE 2: MCD to MLD
158 //////////////////////////////
159
160 // From entities + relationships to tables
161 mldParsing()
162 {
163 // Pass 1: initialize tables
164 Object.keys(this.entities).forEach( name => {
165 let newTable = [ ]; //array of fields
166 this.entities[name].attributes.forEach( attr => {
167 let newField = {
168 name: attr.name,
169 type: attr.type,
170 isKey: attr.isKey,
171 };
172 if (!!attr.qualifiers && !!attr.qualifiers.match(/references/i))
173 {
174 Object.assign(newField, {ref: attr.qualifiers.match(/references ([^\s]+)/i)[1]});
175 newField.qualifiers = attr.qualifiers.replace(/references [^\s]+/i, "");
176 }
177 newTable.push(newField);
178 });
179 this.tables[name] = newTable;
180 });
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 || "",
191 ref: inh.parent + "(" + this.tables[inh.parent][idx].name + ")",
192 });
193 });
194 });
195 // Pass 2: parse associations, add foreign keys when cardinality is 0,1 or 1,1
196 this.associations.forEach( a => {
197 let newTableAttrs = [ ];
198 let hasZeroOne = false;
199 a.entities.forEach( e => {
200 if (['?','1'].includes(e.card[0]))
201 {
202 hasZeroOne = true;
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;
207 this.entities[e2.name].attributes.forEach( attr => {
208 if (attr.isKey)
209 {
210 // For "weak tables", foreign keys become part of the key
211 const isKey = e.card.length >= 2 && e.card[1] == 'R';
212 this.tables[e.name].push({
213 isKey: isKey,
214 name: e2.name + "_" + attr.name,
215 type: attr.type,
216 qualifiers: !isKey && e.card[0]=='1' ? "not null" : "",
217 ref: e2.name + "(" + attr.name + ")",
218 });
219 }
220 });
221 });
222 }
223 else
224 {
225 // Add all keys in current entity
226 let fields = this.entities[e.name].attributes.filter( attr => { return attr.isKey; });
227 newTableAttrs.push({
228 fields: fields,
229 entity: e.name,
230 });
231 }
232 });
233 if (!hasZeroOne && newTableAttrs.length > 1)
234 {
235 // Ok, really create a new table
236 let newTable = {
237 name: a.name || newTableAttrs.map( item => { return item.entity; }).join("_"),
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,
245 type: f.type,
246 qualifiers: f.qualifiers || "",
247 ref: item.entity + "(" + f.name + ")",
248 });
249 });
250 });
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 });
267 // Add relationship potential own attributes
268 (a.attributes || [ ]).forEach( attr => {
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 /////////////////////////////////
284
285 // "Modèle conceptuel des données". TODO: option for graph size
286 // NOTE: randomizing helps to obtain better graphs (sometimes)
287 drawMcd(id, mcdStyle) //mcdStyle: bubble, or compact
288 {
289 let element = document.getElementById(id);
290 mcdStyle = mcdStyle || "compact";
291 // Build dot graph input
292 let mcdDot = 'graph {\n';
293 mcdDot += 'rankdir="LR";\n';
294 // Nodes:
295 if (mcdStyle == "compact")
296 mcdDot += 'node [shape=plaintext];\n';
297 _.shuffle(Object.keys(this.entities)).forEach( name => {
298 if (mcdStyle == "bubble")
299 {
300 mcdDot += '"' + name + '" [shape=rectangle, label="' + name + '"';
301 if (this.entities[name].weak)
302 mcdDot += ', peripheries=2';
303 mcdDot += '];\n';
304 if (!!this.entities[name].attributes)
305 {
306 this.entities[name].attributes.forEach( a => {
307 let label = (a.isKey ? '#' : '') + a.name;
308 let attrName = name + '_' + a.name;
309 mcdDot += '"' + attrName + '" [shape=ellipse, label="' + label + '"];\n';
310 if (Math.random() < 0.5)
311 mcdDot += '"' + attrName + '" -- "' + name + '";\n';
312 else
313 mcdDot += '"' + name + '" -- "' + attrName + '";\n';
314 });
315 }
316 }
317 else
318 {
319 mcdDot += '"' + name + '" [label=<';
320 if (this.entities[name].weak)
321 {
322 mcdDot += '<table port="name" BORDER="1" ALIGN="LEFT" CELLPADDING="0" CELLSPACING="3" CELLBORDER="0">' +
323 '<tr><td><table BORDER="1" ALIGN="LEFT" CELLPADDING="5" CELLSPACING="0">\n';
324 }
325 else
326 mcdDot += '<table port="name" BORDER="1" ALIGN="LEFT" CELLPADDING="5" CELLSPACING="0">\n';
327 mcdDot += '<tr><td BGCOLOR="#ae7d4e" BORDER="0"><font COLOR="#FFFFFF">' + name + '</font></td></tr>\n';
328 if (!!this.entities[name].attributes)
329 {
330 this.entities[name].attributes.forEach( a => {
331 let label = (a.isKey ? '<u>' : '') + a.name + (a.isKey ? '</u>' : '');
332 mcdDot += '<tr><td BGCOLOR="#FFFFFF" BORDER="0" ALIGN="LEFT"><font COLOR="#000000" >' + label + '</font></td></tr>\n';
333 });
334 }
335 mcdDot += '</table>';
336 if (this.entities[name].weak)
337 mcdDot += '</td></tr></table>';
338 mcdDot += '>];\n';
339 }
340 });
341 // Inheritances:
342 _.shuffle(this.inheritances).forEach( i => {
343 // TODO: node shape = triangle fill yellow. See
344 // https://merise.developpez.com/faq/?page=MCD#CIF-ou-dependance-fonctionnelle-de-A-a-Z
345 // https://merise.developpez.com/faq/?page=MLD#Comment-transformer-un-MCD-en-MLD
346 // https://www.developpez.net/forums/d1088964/general-developpement/alm/modelisation/structure-agregation-l-association-d-association/
347 _.shuffle(i.children).forEach( c => {
348 if (Math.random() < 0.5)
349 mcdDot += '"' + c + '":name -- "' + i.parent + '":name [dir="forward",arrowhead="vee",';
350 else
351 mcdDot += '"' + i.parent + '":name -- "' + c + '":name [dir="back",arrowtail="vee",';
352 mcdDot += 'style="dashed"];\n';
353 });
354 });
355 // Relationships:
356 if (mcdStyle == "compact")
357 mcdDot += 'node [shape=rectangle, style=rounded];\n';
358 let assoceCounter = 0;
359 _.shuffle(this.associations).forEach( a => {
360 let name = a.name || "_assoce" + assoceCounter++;
361 if (mcdStyle == "bubble")
362 {
363 mcdDot += '"' + name + '" [shape="diamond", style="filled", color="lightgrey", label="' + name + '"';
364 if (a.weak)
365 mcdDot += ', peripheries=2';
366 mcdDot += '];\n';
367 if (!!a.attributes)
368 {
369 a.attributes.forEach( attr => {
370 let label = (attr.isKey ? '#' : '') + attr.name;
371 mcdDot += '"' + name + '_' + attr.name + '" [shape=ellipse, label="' + label + '"];\n';
372 let attrName = name + '_' + attr.name;
373 if (Math.random() < 0.5)
374 mcdDot += '"' + attrName + '" -- "' + name + '";\n';
375 else
376 mcdDot += '"' + name + '" -- "' + attrName + '";\n';
377 });
378 }
379 }
380 else
381 {
382 let label = '<' + name + '>';
383 if (!!a.attributes)
384 {
385 a.attributes.forEach( attr => {
386 let attrLabel = (attr.isKey ? '#' : '') + attr.name;
387 label += '\\n' + attrLabel;
388 });
389 }
390 mcdDot += '"' + name + '" [color="lightgrey", label="' + label + '"';
391 if (a.weak)
392 mcdDot += ', peripheries=2';
393 mcdDot += '];\n';
394 }
395 _.shuffle(a.entities).forEach( e => {
396 if (Math.random() < 0.5)
397 mcdDot += '"' + e.name + '":name -- "' + name + '"';
398 else
399 mcdDot += '"' + name + '" -- "' + e.name + '":name';
400 mcdDot += '[label="' + ErDiags.CARDINAL(e.card) + '"];\n';
401 });
402 });
403 mcdDot += '}';
404 if (this.output == "graph") //draw graph in element
405 element.innerHTML = "<img src='scripts/getGraph_" + this.image + ".php?dot=" + encodeURIComponent(mcdDot) + "'/>";
406 else //output = "text": just show dot input
407 element.innerHTML = mcdDot.replace(/</g,"&lt;").replace(/>/g,"&gt;");
408 }
409
410 // "Modèle logique des données", from MCD without anomalies
411 drawMld(id)
412 {
413 let element = document.getElementById(id);
414 // Build dot graph input (assuming foreign keys not already present...)
415 let mldDot = 'graph {\n';
416 mldDot += 'rankdir="LR";\n';
417 mldDot += 'node [shape=plaintext];\n';
418 let links = "";
419 _.shuffle(Object.keys(this.tables)).forEach( name => {
420 mldDot += '"' + name + '" [label=<<table BORDER="1" ALIGN="LEFT" CELLPADDING="5" CELLSPACING="0">\n';
421 mldDot += '<tr><td BGCOLOR="#ae7d4e" BORDER="0"><font COLOR="#FFFFFF">' + name + '</font></td></tr>\n';
422 this.tables[name].forEach( f => {
423 let label = (f.isKey ? '<u>' : '') + (!!f.ref ? '#' : '') + f.name + (f.isKey ? '</u>' : '');
424 mldDot += '<tr><td port="' + f.name + '"' + ' BGCOLOR="#FFFFFF" BORDER="0" ALIGN="LEFT"><font COLOR="#000000" >' + label + '</font></td></tr>\n';
425 if (!!f.ref)
426 {
427 const refPort = f.ref.slice(0,-1).replace('(',':');
428 if (Math.random() < 0.5)
429 links += refPort + ' -- "' + name+'":"'+f.name + '" [dir="forward",arrowhead="dot"';
430 else
431 links += '"'+name+'":"'+f.name+'" -- ' + refPort + ' [dir="back",arrowtail="dot"';
432 links += ']\n;';
433 }
434 });
435 mldDot += '</table>>];\n';
436 });
437 mldDot += links + '\n';
438 mldDot += '}';
439 if (this.output == "graph")
440 element.innerHTML = "<img src='scripts/getGraph_" + this.image + ".php?dot=" + encodeURIComponent(mldDot) + "'/>";
441 else
442 element.innerHTML = mldDot.replace(/</g,"&lt;").replace(/>/g,"&gt;");
443 }
444
445 fillSql(id)
446 {
447 let element = document.getElementById(id);
448 if (!!this.sqlText)
449 {
450 element.innerHTML = this.sqlText;
451 return;
452 }
453 let sqlText = "";
454 Object.keys(this.tables).forEach( name => {
455 sqlText += "CREATE TABLE " + name + " (\n";
456 let key = "";
457 let foreignKey = [ ];
458 this.tables[name].forEach( f => {
459 let type = f.type || (f.isKey ? "INTEGER" : "TEXT");
460 if (!!f.ref)
461 foreignKey.push({name: f.name, ref: f.ref});
462 sqlText += "\t" + f.name + " " + type + " " + (f.qualifiers || "") + ",\n";
463 if (f.isKey)
464 key += (key.length>0 ? "," : "") + f.name;
465 });
466 sqlText += "\tPRIMARY KEY (" + key + ")";
467 foreignKey.forEach( f => {
468 let refParts = f.ref.split("(");
469 const table = refParts[0];
470 const field = refParts[1].slice(0,-1); //remove last parenthesis
471 sqlText += ",\n\tFOREIGN KEY (" + f.name + ") REFERENCES " + table + "(" + field + ")";
472 });
473 sqlText += "\n);\n";
474 });
475 this.sqlText = sqlText;
476 element.innerHTML = "<pre><code>" + sqlText + "</code></pre>";
477 }
478 }