Skip to content

Commit

Permalink
Merge pull request #35 from funktechno/f/lastlink
Browse files Browse the repository at this point in the history
more foreign key improvements
  • Loading branch information
lastlink authored Oct 13, 2022
2 parents ea8f354 + 11cd895 commit 09a2d3e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 16 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@funktechno/sqlsimpleparser",
"version": "0.0.8",
"version": "0.0.9",
"description": "",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
50 changes: 35 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export class SqlSimpleParser {
const removedComments = chunk
// remove database comments, multiline, --, and //
.replace(/\/\*[\s\S]*?\*\/|\/\/|--.*/g, "")
.replace(/IF NOT EXISTS/gi, "")
.trim();
const cleanedLines = removedComments
.split("\n")
Expand All @@ -92,20 +93,38 @@ export class SqlSimpleParser {
const lines: string[] = [];
let insertSameLine = false;
cleanedLines.forEach((n) => {
if (
(lines.length > 0 &&
n[0] == "(" &&
lines[lines.length - 1].toLocaleLowerCase().indexOf(CreateTable) ==
-1) ||
insertSameLine
) {
if (lines.length > 0) {
insertSameLine = true;
lines[lines.length - 1] += n;
if (n[0] == ")") insertSameLine = false;
}
} else {
lines.push(n);
if (lines.length > 0){
if((n[0] == "(" &&
lines[lines.length - 1].toLocaleLowerCase().indexOf(CreateTable) ==
-1) ||
insertSameLine) {
if (lines.length > 0) {
insertSameLine = true;
lines[lines.length - 1] += ` ${n}`;
if (n[0] == ")")
insertSameLine = false;
}
}
else if(lines[lines.length - 1].match(/CONSTRAINT/gi) &&
(n.match(/FOREIGN KEY/gi) && !n.match(/CONSTRAINT/gi))
){
lines[lines.length - 1] += ` ${n}`;
}
// add to previous line if current has references and previous has foreign key
else if(lines[lines.length - 1].match(/FOREIGN KEY/gi) &&
(n.match(/REFERENCES/gi) && !n.match(/FOREIGN KEY/gi))
){
lines[lines.length - 1] += ` ${n}`;
}
else if(n.substring(0,2).toUpperCase() == "ON"){
lines[lines.length - 1] += ` ${n}`;
}
else {
lines.push(n);
}
}
else {
lines.push(n);
}
});
// dx = 0,
Expand Down Expand Up @@ -543,7 +562,8 @@ export class SqlSimpleParser {

private ParseMySQLForeignKey(name: string, currentTableModel: TableModel) {
const referencesIndex = name.toLowerCase().indexOf("references");
const foreignKeySQL = name.substring(0, referencesIndex);
let foreignKeySQL = name.substring(0, referencesIndex);
foreignKeySQL = foreignKeySQL.substring(foreignKeySQL.toUpperCase().indexOf("FOREIGN KEY"));
let referencesSQL = name.substring(referencesIndex, name.length);

//Remove references syntax
Expand Down

0 comments on commit 09a2d3e

Please sign in to comment.