Skip to content

Commit 09a2d3e

Browse files
authored
Merge pull request #35 from funktechno/f/lastlink
more foreign key improvements
2 parents ea8f354 + 11cd895 commit 09a2d3e

File tree

2 files changed

+36
-16
lines changed

2 files changed

+36
-16
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@funktechno/sqlsimpleparser",
3-
"version": "0.0.8",
3+
"version": "0.0.9",
44
"description": "",
55
"main": "lib/index.js",
66
"types": "lib/index.d.ts",

src/index.ts

+35-15
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ export class SqlSimpleParser {
8080
const removedComments = chunk
8181
// remove database comments, multiline, --, and //
8282
.replace(/\/\*[\s\S]*?\*\/|\/\/|--.*/g, "")
83+
.replace(/IF NOT EXISTS/gi, "")
8384
.trim();
8485
const cleanedLines = removedComments
8586
.split("\n")
@@ -92,20 +93,38 @@ export class SqlSimpleParser {
9293
const lines: string[] = [];
9394
let insertSameLine = false;
9495
cleanedLines.forEach((n) => {
95-
if (
96-
(lines.length > 0 &&
97-
n[0] == "(" &&
98-
lines[lines.length - 1].toLocaleLowerCase().indexOf(CreateTable) ==
99-
-1) ||
100-
insertSameLine
101-
) {
102-
if (lines.length > 0) {
103-
insertSameLine = true;
104-
lines[lines.length - 1] += n;
105-
if (n[0] == ")") insertSameLine = false;
106-
}
107-
} else {
108-
lines.push(n);
96+
if (lines.length > 0){
97+
if((n[0] == "(" &&
98+
lines[lines.length - 1].toLocaleLowerCase().indexOf(CreateTable) ==
99+
-1) ||
100+
insertSameLine) {
101+
if (lines.length > 0) {
102+
insertSameLine = true;
103+
lines[lines.length - 1] += ` ${n}`;
104+
if (n[0] == ")")
105+
insertSameLine = false;
106+
}
107+
}
108+
else if(lines[lines.length - 1].match(/CONSTRAINT/gi) &&
109+
(n.match(/FOREIGN KEY/gi) && !n.match(/CONSTRAINT/gi))
110+
){
111+
lines[lines.length - 1] += ` ${n}`;
112+
}
113+
// add to previous line if current has references and previous has foreign key
114+
else if(lines[lines.length - 1].match(/FOREIGN KEY/gi) &&
115+
(n.match(/REFERENCES/gi) && !n.match(/FOREIGN KEY/gi))
116+
){
117+
lines[lines.length - 1] += ` ${n}`;
118+
}
119+
else if(n.substring(0,2).toUpperCase() == "ON"){
120+
lines[lines.length - 1] += ` ${n}`;
121+
}
122+
else {
123+
lines.push(n);
124+
}
125+
}
126+
else {
127+
lines.push(n);
109128
}
110129
});
111130
// dx = 0,
@@ -543,7 +562,8 @@ export class SqlSimpleParser {
543562

544563
private ParseMySQLForeignKey(name: string, currentTableModel: TableModel) {
545564
const referencesIndex = name.toLowerCase().indexOf("references");
546-
const foreignKeySQL = name.substring(0, referencesIndex);
565+
let foreignKeySQL = name.substring(0, referencesIndex);
566+
foreignKeySQL = foreignKeySQL.substring(foreignKeySQL.toUpperCase().indexOf("FOREIGN KEY"));
547567
let referencesSQL = name.substring(referencesIndex, name.length);
548568

549569
//Remove references syntax

0 commit comments

Comments
 (0)