Rework dropForeign to use new tokenized structure (#4376)

Fixes #4369
This commit is contained in:
Rijk van Zanten 2021-03-15 16:45:28 -04:00 committed by GitHub
parent 79be494ed0
commit 910c009870
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -334,49 +334,40 @@ class SQLite3_DDL {
);
}
async dropForeign(columns, indexName) {
async dropForeign(columns, foreignKeyName) {
return this.client.transaction(
async (trx) => {
this.trx = trx;
const { createTable, createIndices } = await this.getTableSql();
const oneLineSql = createTable.replace(/\s+/g, ' ');
const matched = oneLineSql.match(/^CREATE TABLE\s+(\S+)\s*\((.*)\)/);
const parsedTable = parseCreateTable(createTable);
const defs = matched[2];
if (!defs) {
throw new Error('No column definitions in this statement!');
if (!foreignKeyName) {
parsedTable.columns = parsedTable.columns.map((column) => ({
...column,
references: columns.includes(column.name)
? null
: column.references,
}));
}
const updatedDefs = defs
.split(COMMA_NO_PAREN_REGEX)
.map((line) => line.trim())
.filter((defLine) => {
if (
defLine.toLowerCase().startsWith('constraint') === false &&
defLine.toLowerCase().includes('foreign key') === false
)
return true;
if (indexName) {
if (defLine.includes(indexName)) return false;
return true;
} else {
const matched = defLine.match(/\(`([^)]+)`\)/);
const columnNames = matched[1].split(', ');
const unknownColumnIncludedCheck = (col) =>
!columns.includes(col);
return columnNames.every(unknownColumnIncludedCheck) === false;
parsedTable.constraints = parsedTable.constraints.filter(
(constraint) => {
if (foreignKeyName) {
return constraint.name !== foreignKeyName;
}
})
.join(', ');
const newSql = oneLineSql.replace(defs, updatedDefs);
return (
constraint.columns.some((column) => columns.includes(column)) ===
false
);
}
);
return this.alter(newSql, createIndices, (row) => {
const newTable = compileCreateTable(parsedTable, this.wrap);
return this.alter(newTable, createIndices, (row) => {
return row;
});
},