diff --git a/packages/server/src/sdk/app/tables/external/index.ts b/packages/server/src/sdk/app/tables/external/index.ts index 1045ef1e33..402baada78 100644 --- a/packages/server/src/sdk/app/tables/external/index.ts +++ b/packages/server/src/sdk/app/tables/external/index.ts @@ -41,9 +41,10 @@ export async function save( ...update, } + const tableId = opts?.tableId || update._id let oldTable: Table | undefined - if (opts?.tableId) { - oldTable = await getTable(opts.tableId) + if (tableId) { + oldTable = await getTable(tableId) } if (hasTypeChanged(tableToSave, oldTable)) { @@ -114,6 +115,11 @@ export async function save( relatedTable, relationType ) + if (fkTable.schema[foreignKey] != null) { + throw new Error( + `Unable to generate foreign key - column ${foreignKey} already in use.` + ) + } fkTable.schema[foreignKey] = foreignKeyStructure(foreignKey) if (fkTable.constrained == null) { fkTable.constrained = [] @@ -132,7 +138,7 @@ export async function save( cleanupRelationships(tableToSave, tables, oldTable) - const operation = oldTable ? Operation.UPDATE_TABLE : Operation.CREATE_TABLE + const operation = tableId ? Operation.UPDATE_TABLE : Operation.CREATE_TABLE await makeTableRequest( datasource, operation, diff --git a/packages/server/src/sdk/app/tables/external/utils.ts b/packages/server/src/sdk/app/tables/external/utils.ts index ef280472bf..10c755a7d6 100644 --- a/packages/server/src/sdk/app/tables/external/utils.ts +++ b/packages/server/src/sdk/app/tables/external/utils.ts @@ -52,7 +52,7 @@ export function cleanupRelationships( } } -export function otherRelationshipType(type?: string) { +export function otherRelationshipType(type: RelationshipType) { if (type === RelationshipType.MANY_TO_MANY) { return RelationshipType.MANY_TO_MANY } @@ -68,7 +68,10 @@ export function generateManyLinkSchema( relatedTable: Table ): Table { if (!table.primary || !relatedTable.primary) { - throw new Error("Unable to generate many link schema, no primary keys") + const noPrimaryName = !table.primary ? table.name : relatedTable.name + throw new Error( + `Unable to generate many link schema, "${noPrimaryName}" does not have a primary key` + ) } const primary = table.name + table.primary[0] const relatedPrimary = relatedTable.name + relatedTable.primary[0] diff --git a/packages/server/src/sdk/app/tables/getters.ts b/packages/server/src/sdk/app/tables/getters.ts index 69b2354196..81467bba6c 100644 --- a/packages/server/src/sdk/app/tables/getters.ts +++ b/packages/server/src/sdk/app/tables/getters.ts @@ -31,16 +31,12 @@ export async function getAllInternalTables(db?: Database): Promise