π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
fix: address LTAR v2 review comments β cardinality enforcement, transactional subqueries, cleanup
Pranav57f31b5bd81d
diff --git a/packages/nocodb-sdk/src/lib/UITypes.ts b/packages/nocodb-sdk/src/lib/UITypes.tsindex a49055d195..bc57ca20f1 100644--- a/packages/nocodb-sdk/src/lib/UITypes.ts+++ b/packages/nocodb-sdk/src/lib/UITypes.ts@@ -507,7 +507,9 @@ export function isLinkV2(}export function isMMOrMMLike(- col: ColumnType | { uidt: UITypes | string; colOptions?: any },+ col:+ | ColumnType+ | { uidt: UITypes | string; colOptions?: any; type?: RelationTypes },): boolean {if (typeof col === 'object' && isLinksOrLTAR(col)) {if (col.colOptions) {@@ -520,14 +522,13 @@ export function isMMOrMMLike(return opts.type === RelationTypes.MANY_TO_MANY;}- // colOptions not loaded β check v2-only relation types on the column itself- // These types (om, mo) only exist in v2 and are always MM-like- if ((col as any).type) {- const type = (col as any).type;+ // colOptions not loaded β check type on column root+ // (set during column creation in the UI before colOptions exists)+ if ('type' in col && col.type) {return (- type === RelationTypes.MANY_TO_MANY ||- type === RelationTypes.ONE_TO_MANY ||- type === RelationTypes.MANY_TO_ONE+ col.type === RelationTypes.MANY_TO_MANY ||+ col.type === RelationTypes.ONE_TO_MANY ||+ col.type === RelationTypes.MANY_TO_ONE);}}diff --git a/packages/nocodb/src/db/BaseModelSqlv2/add-remove-links.ts b/packages/nocodb/src/db/BaseModelSqlv2/add-remove-links.tsindex 1e5bbcae84..53366aec14 100644--- a/packages/nocodb/src/db/BaseModelSqlv2/add-remove-links.ts+++ b/packages/nocodb/src/db/BaseModelSqlv2/add-remove-links.ts@@ -1,6 +1,7 @@import {AuditV1OperationTypes,isLinksOrLTAR,+ isLinkV2,isMMOrMMLike,ncIsNullOrUndefined,RelationTypes,@@ -311,6 +312,11 @@ export const addOrRemoveLinks = (baseModel: IBaseModelSqlV2) => {switch (relationType) {case RelationTypes.MANY_TO_MANY:{+ // V2 mo/oo: child can only link to one parent β truncate to 1+ if (isLinkV2(column) && ['mo', 'oo'].includes(colOptions.type)) {+ childIds = childIds.slice(0, 1);+ }+validateRefIds(childIds, parentTable);const vChildCol = await colOptions.getMMChildColumn(mmContext);@@ -404,6 +410,133 @@ export const addOrRemoveLinks = (baseModel: IBaseModelSqlV2) => {if (!insertData.length) return true;}+ // V2 cardinality enforcement: remove conflicting junction rows before insert+ if (+ isLinkV2(column) &&+ colOptions.type !== RelationTypes.MANY_TO_MANY+ ) {+ const unlinkAuditParentObj = [];+ const unlinkAuditChildObj = [];++ // mo/oo: child can only link to one parent β clear existing child links+ if (['mo', 'oo'].includes(colOptions.type)) {+ const childFkValue =+ dataWrapper(row).getByColumnNameTitleOrId(childColumn);++ const existing = await assocBaseModel.execAndParse(+ baseModel+ .dbDriver(vTn)+ .select(vChildCol.column_name, vParentCol.column_name)+ .where(vChildCol.column_name, childFkValue),+ null,+ { raw: true },+ );++ if (existing.length) {+ await assocBaseModel.execAndParse(+ baseModel+ .dbDriver(vTn)+ .where(vChildCol.column_name, childFkValue)+ .delete(),+ null,+ { raw: true },+ );++ for (const r of existing) {+ unlinkAuditParentObj.push({+ rowId: r[vParentCol.column_name],+ refRowId: r[vChildCol.column_name],+ type: colOptions.type as RelationTypes,+ });+ if (parentTable.id !== childTable.id) {+ unlinkAuditChildObj.push({+ rowId: r[vChildCol.column_name],+ refRowId: r[vParentCol.column_name],+ type: getOppositeRelationType(colOptions.type),+ });+ }+ }+ }+ }++ // om/oo: each parent can only be linked by one child β clear existing parent links+ if (['om', 'oo'].includes(colOptions.type)) {+ for (const data of insertData) {+ const parentFkValue = data[vParentCol.column_name];++ const existing = await assocBaseModel.execAndParse(+ baseModel+ .dbDriver(vTn)+ .select(vChildCol.column_name, vParentCol.column_name)+ .where(vParentCol.column_name, parentFkValue),+ null,+ { raw: true },+ );++ if (existing.length) {+ await assocBaseModel.execAndParse(+ baseModel+ .dbDriver(vTn)+ .where(vParentCol.column_name, parentFkValue)+ .delete(),+ null,+ { raw: true },+ );++ for (const r of existing) {+ unlinkAuditParentObj.push({+ rowId: r[vParentCol.column_name],+ refRowId: r[vChildCol.column_name],+ type: colOptions.type as RelationTypes,+ });+ if (parentTable.id !== childTable.id) {+ unlinkAuditChildObj.push({+ rowId: r[vChildCol.column_name],+ refRowId: r[vParentCol.column_name],+ type: getOppositeRelationType(colOptions.type),+ });+ }+ }+ }+ }+ }++ // Emit unlink audit for cascaded removals+ if (unlinkAuditParentObj.length) {+ baseModel.dbDriver.attachToTransaction(async () => {+ const clone = baseModel.getNonTransactionalClone();+ await clone.afterAddOrRemoveChild(+ {+ opType: AuditV1OperationTypes.DATA_UNLINK,+ model: auditConfig.parentModel,+ refModel: auditConfig.childModel,+ columnTitle: auditConfig.parentColTitle,+ columnId: auditConfig.parentColId,+ refColumnTitle: auditConfig.childColTitle,+ refColumnId: auditConfig.childColId,+ req: cookie,+ },+ unlinkAuditParentObj,+ );+ if (unlinkAuditChildObj.length) {+ await clone.afterAddOrRemoveChild(+ {+ opType: AuditV1OperationTypes.DATA_UNLINK,+ model: auditConfig.childModel,+ refModel: auditConfig.parentModel,+ columnTitle: auditConfig.childColTitle,+ columnId: auditConfig.childColId,+ refColumnTitle: auditConfig.parentColTitle,+ refColumnId: auditConfig.parentColId,+ req: cookie,+ },+ unlinkAuditChildObj,+ );+ }+ });+ }+ }+// todo: use bulk insertawait baseModel.execAndParse(baseModel.dbDriver(vTn).insert(insertData),diff --git a/packages/nocodb/src/db/BaseModelSqlv2/ltar-cols-updater.ts b/packages/nocodb/src/db/BaseModelSqlv2/ltar-cols-updater.tsindex 902b9b736f..07310c67af 100644--- a/packages/nocodb/src/db/BaseModelSqlv2/ltar-cols-updater.ts+++ b/packages/nocodb/src/db/BaseModelSqlv2/ltar-cols-updater.ts@@ -1,4 +1,4 @@-import { isLinksOrLTAR, RelationTypes } from 'nocodb-sdk';+import { isLinksOrLTAR, isMMOrMMLike, RelationTypes } from 'nocodb-sdk';import type { Logger } from '@nestjs/common';import type { NcRequest } from 'nocodb-sdk';import type { IBaseModelSqlV2 } from '~/db/IBaseModelSqlV2';@@ -48,7 +48,7 @@ export const LTARColsUpdater = (param: {let existingLinks = [];profiler.log(`${col.colOptions.type} list start`);- if (col.colOptions.type === RelationTypes.MANY_TO_MANY) {+ if (isMMOrMMLike(col)) {existingLinks = await trxBaseModel.mmList({colId: col.id,parentId: rowId,diff --git a/packages/nocodb/src/db/relation-manager.ts b/packages/nocodb/src/db/relation-manager.tsindex ed2f503ebf..7a8f859a1b 100644--- a/packages/nocodb/src/db/relation-manager.ts+++ b/packages/nocodb/src/db/relation-manager.ts@@ -75,6 +75,7 @@ export class RelationManager {// for M2M and Belongs to relation, the relation stored in column option is reversed// parent become child, child become parent from the viewpoint of col options+ // In v2 we use junction table and it act like MM so we treat it as reversed relation as wellstatic isRelationReversed(relationColumn: Column<any>,colOptions: LinkToAnotherRecordColumn,@@ -367,7 +368,6 @@ export class RelationManager {vChildCol: Column;vParentCol: Column;vTn: string | Knex.Raw;- assocBaseModel: IBaseModelSqlV2;column: Column;req: any;refTableLinkColumnId: string;@@ -400,8 +400,7 @@ export class RelationManager {// ManyToOne / OneToOne: this child can only link to one parent// β remove all existing junction rows for this childif (['mo', 'oo'].includes(colOptions.type)) {- const childFkSubquery = childBaseModel- .dbDriver(childTn)+ const childFkSubquery = trx(childTn).select(childColumn.column_name).where(_wherePk(childTable.primaryKeys, childId)).first();@@ -436,8 +435,7 @@ export class RelationManager {// OneToMany / OneToOne: this parent can only be linked to by one child// β remove all existing junction rows for this parentif (['om', 'oo'].includes(colOptions.type)) {- const parentFkSubquery = parentBaseModel- .dbDriver(parentTn)+ const parentFkSubquery = trx(parentTn).select(parentColumn.column_name).where(_wherePk(parentTable.primaryKeys, parentId)).first();@@ -473,14 +471,12 @@ export class RelationManager {// Insert the new junction row within the same transactionif (baseModel.isSnowflake || baseModel.isDatabricks) {- const parentPK = parentBaseModel- .dbDriver(parentTn)+ const parentPK = trx(parentTn).select(parentColumn.column_name).where(_wherePk(parentTable.primaryKeys, parentId)).first();- const childPK = childBaseModel- .dbDriver(childTn)+ const childPK = trx(childTn).select(childColumn.column_name).where(_wherePk(childTable.primaryKeys, childId)).first();@@ -491,13 +487,11 @@ export class RelationManager {);} else {await trx(vTn).insert({- [vParentCol.column_name]: baseModel- .dbDriver(parentTn)+ [vParentCol.column_name]: trx(parentTn).select(parentColumn.column_name).where(_wherePk(parentTable.primaryKeys, parentId)).first(),- [vChildCol.column_name]: baseModel- .dbDriver(childTn)+ [vChildCol.column_name]: trx(childTn).select(childColumn.column_name).where(_wherePk(childTable.primaryKeys, childId)).first(),@@ -613,7 +607,6 @@ export class RelationManager {vChildCol,vParentCol,vTn,- assocBaseModel,column,req,refTableLinkColumnId,@@ -1049,6 +1042,14 @@ export class RelationManager {const { req } = params;+ // Resolve once β every branch uses the same column + table+ const refTableLinkColumnId = (+ await extractCorrespondingLinkColumn(childBaseModel.context, {+ ltarColumn: relationColumn,+ referencedTable: parentTable,+ })+ )?.id;+const webhookHandler = await RelationUpdateWebhookHandler.beginUpdate({childBaseModel,@@ -1103,14 +1104,7 @@ export class RelationManager {model: parentTable,rowIds: [parentId],cookie: req,- updatedColIds: [- (- await extractCorrespondingLinkColumn(childBaseModel.context, {- ltarColumn: this.relationContext.relationColumn,- referencedTable: parentTable,- })- )?.id,- ],+ updatedColIds: [refTableLinkColumnId],});await parentBaseModel.broadcastLinkUpdates([parentId]);@@ -1157,14 +1151,7 @@ export class RelationManager {model: parentTable,rowIds: [parentId],cookie: req,- updatedColIds: [- (- await extractCorrespondingLinkColumn(childBaseModel.context, {- ltarColumn: this.relationContext.relationColumn,- referencedTable: parentTable,- })- )?.id,- ],+ updatedColIds: [refTableLinkColumnId],});await parentBaseModel.broadcastLinkUpdates([parentId]);@@ -1202,14 +1189,7 @@ export class RelationManager {model: parentTable,rowIds: [parentId],cookie: req,- updatedColIds: [- (- await extractCorrespondingLinkColumn(childBaseModel.context, {- ltarColumn: this.relationContext.relationColumn,- referencedTable: parentTable,- })- )?.id,- ],+ updatedColIds: [refTableLinkColumnId],});await parentBaseModel.broadcastLinkUpdates([parentId]);@@ -1241,14 +1221,7 @@ export class RelationManager {model: parentTable,rowIds: [parentId],cookie: req,- updatedColIds: [- (- await extractCorrespondingLinkColumn(childBaseModel.context, {- ltarColumn: this.relationContext.relationColumn,- referencedTable: parentTable,- })- )?.id,- ],+ updatedColIds: [refTableLinkColumnId],});await parentBaseModel.broadcastLinkUpdates([parentId]);}