Skip to content

Commit

Permalink
Rename link relationship fields
Browse files Browse the repository at this point in the history
  • Loading branch information
adrinr committed Sep 3, 2024
1 parent ae0e3cd commit 74eb035
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 9 deletions.
3 changes: 3 additions & 0 deletions packages/server/src/api/controllers/table/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ export async function save(ctx: UserCtx<SaveTableRequest, SaveTableResponse>) {
} else {
await events.table.updated(savedTable)
}
if (renaming) {
await sdk.views.renameLinkedViews(savedTable, renaming)
}
if (isImport) {
await events.table.imported(savedTable)
}
Expand Down
18 changes: 9 additions & 9 deletions packages/server/src/api/routes/tests/viewV2.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!)

Expand Down
48 changes: 48 additions & 0 deletions packages/server/src/sdk/app/views/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
FieldType,
RelationSchemaField,
RelationshipFieldMetadata,
RenameColumn,
Table,
TableSchema,
Expand Down Expand Up @@ -252,3 +253,50 @@ export function syncSchema(

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)
}
}
}

0 comments on commit 74eb035

Please sign in to comment.