diff --git a/packages/server/src/api/controllers/table/index.ts b/packages/server/src/api/controllers/table/index.ts index bb97a89f6d7..0e160770928 100644 --- a/packages/server/src/api/controllers/table/index.ts +++ b/packages/server/src/api/controllers/table/index.ts @@ -116,6 +116,9 @@ export async function save(ctx: UserCtx) { } else { await events.table.updated(savedTable) } + if (renaming) { + await sdk.views.renameLinkedViews(savedTable, renaming) + } if (isImport) { await events.table.imported(savedTable) } diff --git a/packages/server/src/api/routes/tests/viewV2.spec.ts b/packages/server/src/api/routes/tests/viewV2.spec.ts index 699d388a6d7..9d14a528156 100644 --- a/packages/server/src/api/routes/tests/viewV2.spec.ts +++ b/packages/server/src/api/routes/tests/viewV2.spec.ts @@ -1204,18 +1204,18 @@ describe.each([ ) await config.api.table.save({ ...table, - schema: { + schema: { ...table.schema, - aux: { - name: "aux", - relationshipType: RelationshipType.ONE_TO_MANY, - type: FieldType.LINK, - tableId: auxTable._id!, - fieldName: "fk_aux", + aux: { + name: "aux", + relationshipType: RelationshipType.ONE_TO_MANY, + type: FieldType.LINK, + tableId: auxTable._id!, + fieldName: "fk_aux", constraints: { type: "array" }, - }, }, - }) + }, + }) // Refetch auxTable auxTable = await config.api.table.get(auxTable._id!) diff --git a/packages/server/src/sdk/app/views/index.ts b/packages/server/src/sdk/app/views/index.ts index 9cd11712ed4..120b56183c4 100644 --- a/packages/server/src/sdk/app/views/index.ts +++ b/packages/server/src/sdk/app/views/index.ts @@ -1,6 +1,7 @@ import { FieldType, RelationSchemaField, + RelationshipFieldMetadata, RenameColumn, Table, TableSchema, @@ -252,3 +253,50 @@ export function syncSchema( return view } + +export async function renameLinkedViews(table: Table, renaming: RenameColumn) { + const relatedLinks: Record = {} + + for (const field of Object.values(table.schema)) { + if (field.type !== FieldType.LINK) { + continue + } + + relatedLinks[field.tableId] ??= [] + relatedLinks[field.tableId].push(field) + } + + const relatedTables = await sdk.tables.getTables(Object.keys(relatedLinks)) + for (const relatedTable of relatedTables) { + let toSave = false + const viewsV2 = Object.values(relatedTable.views || {}).filter( + sdk.views.isV2 + ) + if (!viewsV2) { + continue + } + + for (const view of viewsV2) { + for (const relField of Object.keys(view.schema || {}).filter(f => { + const tableField = relatedTable.schema[f] + if (tableField.type !== FieldType.LINK) { + return false + } + + return tableField.tableId === table._id + })) { + const columns = view.schema && view.schema[relField]?.columns + + if (columns && columns[renaming.old]) { + columns[renaming.updated] = columns[renaming.old] + delete columns[renaming.old] + toSave = true + } + } + } + + if (toSave) { + await sdk.tables.saveTable(relatedTable) + } + } +}