Rename link relationship fields

This commit is contained in:
Adria Navarro 2024-09-03 10:15:26 +02:00
parent ae0e3cdb59
commit 74eb0357a4
3 changed files with 60 additions and 9 deletions

View File

@ -116,6 +116,9 @@ export async function save(ctx: UserCtx<SaveTableRequest, SaveTableResponse>) {
} else { } else {
await events.table.updated(savedTable) await events.table.updated(savedTable)
} }
if (renaming) {
await sdk.views.renameLinkedViews(savedTable, renaming)
}
if (isImport) { if (isImport) {
await events.table.imported(savedTable) await events.table.imported(savedTable)
} }

View File

@ -1204,18 +1204,18 @@ describe.each([
) )
await config.api.table.save({ await config.api.table.save({
...table, ...table,
schema: { schema: {
...table.schema, ...table.schema,
aux: { aux: {
name: "aux", name: "aux",
relationshipType: RelationshipType.ONE_TO_MANY, relationshipType: RelationshipType.ONE_TO_MANY,
type: FieldType.LINK, type: FieldType.LINK,
tableId: auxTable._id!, tableId: auxTable._id!,
fieldName: "fk_aux", fieldName: "fk_aux",
constraints: { type: "array" }, constraints: { type: "array" },
},
}, },
}) },
})
// Refetch auxTable // Refetch auxTable
auxTable = await config.api.table.get(auxTable._id!) auxTable = await config.api.table.get(auxTable._id!)

View File

@ -1,6 +1,7 @@
import { import {
FieldType, FieldType,
RelationSchemaField, RelationSchemaField,
RelationshipFieldMetadata,
RenameColumn, RenameColumn,
Table, Table,
TableSchema, TableSchema,
@ -252,3 +253,50 @@ export function syncSchema(
return view return view
} }
export async function renameLinkedViews(table: Table, renaming: RenameColumn) {
const relatedLinks: Record<string, RelationshipFieldMetadata[]> = {}
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)
}
}
}