π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
fix: skip validation for unique constraint when both previous and existing are unique
Pranav C5fb02ec6c119
diff --git a/packages/nocodb-sdk/src/lib/UITypes.ts b/packages/nocodb-sdk/src/lib/UITypes.tsindex 08a9a1da0a..43fc00ed3b 100644--- a/packages/nocodb-sdk/src/lib/UITypes.ts+++ b/packages/nocodb-sdk/src/lib/UITypes.ts@@ -474,11 +474,20 @@ export function isLinksOrLTAR(export const isLTARType = isLinksOrLTAR;export function isLinkV2(- colOrUidt: ColumnType | { uidt: UITypes | string } | UITypes | string+ col: ColumnType | { uidt: UITypes | string; colOptions?: any } | UITypes | string) {+ // If it's just a string or simple object without colOptions, check if it's UITypes.Links+ if (typeof col === 'string' || !('colOptions' in col)) {+ return (+ <UITypes>(typeof col === 'object' ? col?.uidt : col) === UITypes.Links+ );+ }++ // For full column objects with colOptions, check version fieldreturn (- <UITypes>(typeof colOrUidt === 'object' ? colOrUidt?.uidt : colOrUidt) ===- UITypes.Links+ !!col &&+ isLinksOrLTAR(col) &&+ (col.colOptions as LinkToAnotherRecordType)?.version === LinksVersion.V2);}@@ -486,12 +495,16 @@ export function isMMOrMMLike(col: ColumnType | { uidt: UITypes | string; colOptions?: any }): boolean {if (typeof col === 'object') {- // Check if it's Links v2 (always MM-like)+ // Check if it's Links v2 (always MM-like because v2 uses junction tables for all relation types)if (col.uidt === UITypes.Links) {return true;}- // Check if it's LinkToAnotherRecord with MANY_TO_MANY type+ // Check if it's LinkToAnotherRecord with version V2 (also MM-like)if (col.uidt === UITypes.LinkToAnotherRecord && col.colOptions) {+ if ((col.colOptions as LinkToAnotherRecordType)?.version === LinksVersion.V2) {+ return true;+ }+ // Check if it's traditional MANY_TO_MANY typereturn (col.colOptions as LinkToAnotherRecordType)?.type === RelationTypes.MANY_TO_MANY;}}@@ -827,3 +840,8 @@ export const customLinkSupportedTypes: UITypes[] = [// column types that are not shown in the GUIexport const hiddenColumnTypes: UITypes[] = [UITypes.Meta];++export const LinksVersion = {+ V1: 1,+ V2: 2,+} as const;diff --git a/packages/nocodb-sdk/src/lib/columnHelper/utils/cell.ts b/packages/nocodb-sdk/src/lib/columnHelper/utils/cell.tsindex 5b69573544..6c10028bf6 100644--- a/packages/nocodb-sdk/src/lib/columnHelper/utils/cell.ts+++ b/packages/nocodb-sdk/src/lib/columnHelper/utils/cell.ts@@ -1,8 +1,12 @@import dayjs from 'dayjs';-import { ButtonActionsType, ColumnType } from '~/lib/Api';-import { LongTextAiMetaProp } from '~/lib/globals';+import {+ ButtonActionsType,+ ColumnType,+ LinkToAnotherRecordType,+} from '~/lib/Api';+import { LongTextAiMetaProp, RelationTypes } from '~/lib/globals';import { parseProp } from '~/lib/helperFunctions';-import UITypes, { isAIPromptCol } from '~/lib/UITypes';+import UITypes, { isAIPromptCol, isLinksOrLTAR, LinksVersion } from '~/lib/UITypes';export const dataTypeLow = (column: ColumnType) => column.dt?.toLowerCase();@@ -178,3 +182,20 @@ export const isNumericFieldType = (column: ColumnType, abstractType: any) => {isDuration(column));};++export const isMMOrMMLike = (column: ColumnType) => {+ return (+ (isLinksOrLTAR(column) &&+ (column.colOptions as LinkToAnotherRecordType)?.type ===+ RelationTypes.MANY_TO_MANY) ||+ (column.colOptions as LinkToAnotherRecordType)?.version === LinksVersion.V2+ );+};++export const isLinkV2 = (column: ColumnType) => {+ return (+ !!column &&+ isLinksOrLTAR(column) &&+ (column.colOptions as LinkToAnotherRecordType)?.version === LinksVersion.V2+ );+};diff --git a/packages/nocodb-sdk/src/lib/helperFunctions.ts b/packages/nocodb-sdk/src/lib/helperFunctions.tsindex ffd0017292..d574886909 100644--- a/packages/nocodb-sdk/src/lib/helperFunctions.ts+++ b/packages/nocodb-sdk/src/lib/helperFunctions.ts@@ -1,5 +1,5 @@-import UITypes, { isLinksOrLTAR, isNumericCol } from './UITypes';-import { RelationTypes, RolesObj, RolesType } from './globals';+import UITypes, {isLinksOrLTAR, isNumericCol} from './UITypes';+import { RolesObj, RolesType } from './globals';import { ClientType } from './enums';import {ColumnType,@@ -7,11 +7,12 @@ import {IntegrationsType,LinkToAnotherRecordType,} from './Api';-import { FormulaDataTypes } from './formula/enums';+import { FormulaDataTypes } from './formulaHelpers';import { ncIsNull, ncIsUndefined } from '~/lib/is';// import {RelationTypes} from "./globals";+// const systemCols = ['created_at', 'updated_at']const filterOutSystemColumns = (columns) => {return (columns && columns.filter((c) => !isSystemColumn(c))) || [];};@@ -25,6 +26,8 @@ const isSystemColumn = (col): boolean =>!!(col &&(col.uidt === UITypes.ForeignKey ||+ ((col.column_name === 'created_at' || col.column_name === 'updated_at') &&+ col.uidt === UITypes.DateTime) ||(col.pk && (col.ai || col.cdf)) ||(col.pk && col.meta && col.meta.ag) ||col.system)@@ -256,6 +259,7 @@ const testDataBaseNames = {mysql: null,[ClientType.PG]: 'postgres',oracledb: 'xe',+ [ClientType.MSSQL]: undefined,[ClientType.SQLITE]: 'a.sqlite',};@@ -272,21 +276,21 @@ export const integrationCategoryNeedDefault = (category: IntegrationsType) => {return [IntegrationsType.Ai].includes(category);};-export function parseProp(v: any, fallbackVal = {}): any {+export function parseProp(v: any): any {if (ncIsUndefined(v) || ncIsNull(v)) return {};try {- return typeof v === 'string' ? JSON.parse(v) ?? fallbackVal : v;+ return typeof v === 'string' ? JSON.parse(v) ?? {} : v;} catch {- return fallbackVal;+ return {};}}-export function stringifyProp(v: any, fallbackVal = '{}'): string {+export function stringifyProp(v: any): string {if (ncIsUndefined(v) || ncIsNull(v)) return '{}';try {- return typeof v === 'string' ? v : JSON.stringify(v) ?? fallbackVal;+ return typeof v === 'string' ? v : JSON.stringify(v) ?? '{}';} catch {- return fallbackVal;+ return '{}';}}@@ -322,29 +326,3 @@ export function isCrossBaseLink(col: ColumnType) {(col.colOptions as LinkToAnotherRecordType)?.base_id);}--export function lookupCanHaveRecursiveEvaluation(param: {- isEeUI: boolean;- relationCol: ColumnType;- relationType: RelationTypes;- dbClientType: ClientType;-}) {- const { isEeUI, dbClientType, relationType, relationCol } = param;- return (- isEeUI &&- dbClientType === ClientType.PG &&- isSelfReferencingTableColumn(relationCol) &&- [RelationTypes.HAS_MANY, RelationTypes.BELONGS_TO].includes(relationType)- );-}--export function formatBytes(bytes, decimals = 2, base = 1000) {- if (bytes === 0) return '0 Bytes';-- const k = base;- const dm = Math.max(0, decimals);- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];- const i = Math.floor(Math.log(bytes) / Math.log(k));-- return `${(bytes / k ** i).toFixed(dm)} ${sizes[i]}`;-}diff --git a/packages/nocodb-sdk/src/lib/index.ts b/packages/nocodb-sdk/src/lib/index.tsindex d341f6d33a..0893109c20 100644--- a/packages/nocodb-sdk/src/lib/index.ts+++ b/packages/nocodb-sdk/src/lib/index.ts@@ -54,6 +54,7 @@ export {UITypesSearchTerms,isInUIType,hiddenColumnTypes,+ LinksVersion,} from '~/lib/UITypes';export { default as CustomAPI, FileType } from '~/lib/CustomAPI';export { default as TemplateGenerator } from '~/lib/TemplateGenerator';diff --git a/packages/nocodb/src/db/BaseModelSqlv2.ts b/packages/nocodb/src/db/BaseModelSqlv2.tsindex d09a959781..b8e18cebd6 100644--- a/packages/nocodb/src/db/BaseModelSqlv2.ts+++ b/packages/nocodb/src/db/BaseModelSqlv2.ts@@ -20,6 +20,7 @@ import {isCreatedOrLastModifiedByCol,isCreatedOrLastModifiedTimeCol,isLinksOrLTAR,+ isMMOrMMLike,isOrderCol,isSelfLinkCol,isSystemColumn,@@ -1748,6 +1749,7 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {case UITypes.Links:case UITypes.LinkToAnotherRecord:{+ const isMMLike = isMMOrMMLike(column);this._columns[column.title] = column;const colOptions = (await column.getColOptions(this.context,@@ -1755,7 +1757,7 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {const { refContext } = colOptions.getRelContext(this.context);- if (colOptions?.type === 'hm') {+ if (colOptions?.type === 'hm' && !isMMLike) {const listLoader = new DataLoader(async (ids: string[]) => {if (ids.length > 1) {@@ -1802,7 +1804,7 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {getCompositePkValue(self.model.primaryKeys, this),);};- } else if (colOptions.type === 'mm') {+ } else if (colOptions.type === 'mm' || isMMLike) {const listLoader = new DataLoader(async (ids: string[]) => {if (ids?.length > 1) {@@ -1849,7 +1851,7 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {getCompositePkValue(self.model.primaryKeys, this),);};- } else if (colOptions.type === 'bt') {+ } else if (colOptions.type === 'bt' && !isMMLike) {// @ts-ignoreconst colOptions = (await column.getColOptions(this.context,@@ -1938,7 +1940,7 @@ class BaseModelSqlv2 implements IBaseModelSqlV2 {return await readLoader.load(this?.[cCol?.title]);};- } else if (colOptions.type === 'oo') {+ } else if (colOptions.type === 'oo' && !isMMLike) {const isBt = column.meta?.bt;if (isBt) {diff --git a/packages/nocodb/src/db/relation-manager.ts b/packages/nocodb/src/db/relation-manager.tsindex f26b84bf04..15ad8ec44c 100644--- a/packages/nocodb/src/db/relation-manager.ts+++ b/packages/nocodb/src/db/relation-manager.ts@@ -1,17 +1,23 @@-import { AuditOperationSubTypes, RelationTypes, UITypes } from 'nocodb-sdk';+import {+ AuditOperationSubTypes,+ isLinksOrLTAR,+ isLinkV2,+ isMMOrMMLike,+ RelationTypes,+} from 'nocodb-sdk';import type { NcContext, NcRequest } from 'nocodb-sdk';import type { Column, LinkToAnotherRecordColumn } from '~/models';import type { IBaseModelSqlV2 } from '~/db/IBaseModelSqlV2';import type { Knex } from 'knex';-import { RelationUpdateWebhookHandler } from '~/db/relation-update-webhook-handler';import { Model } from '~/models';+import { RelationUpdateWebhookHandler } from '~/db/relation-update-webhook-handler';import { NcError } from '~/helpers/catchError';import {_wherePk,getCompositePkValue,getOppositeRelationType,} from '~/helpers/dbHelpers';-import { extractCorrespondingLinkColumn } from '~/db/BaseModelSqlv2/add-remove-links';+import { getTargetTableRelColumn } from '~/helpers';interface AuditUpdateLog {pkValue?: Record<string, any>;@@ -25,6 +31,7 @@ interface AuditUpdateLog {type: RelationTypes;direction: 'parent_child' | 'child_parent';}+interface AuditUpdateObj extends AuditUpdateLog {columnTitle: string;refColumnTitle?: string;@@ -33,6 +40,7 @@ interface AuditUpdateObj extends AuditUpdateLog {model: Model;refModel?: Model;}+export class RelationManager {constructor(private relationContext: {@@ -70,7 +78,11 @@ export class RelationManager {) {const isBelongsTo =colOptions.type === RelationTypes.BELONGS_TO || relationColumn.meta?.bt;- return isBelongsTo || colOptions.type === RelationTypes.MANY_TO_MANY;+ return (+ isLinkV2(relationColumn) ||+ isBelongsTo ||+ colOptions.type === RelationTypes.MANY_TO_MANY+ );}static async getRelationManager(@@ -84,11 +96,7 @@ export class RelationManager {await baseModel.model.getColumns(baseModel.context);const column = baseModel.model.columnsById[colId];- if (- !column ||- ![UITypes.LinkToAnotherRecord, UITypes.Links].includes(column.uidt)- )- NcError.get(baseModel.context).fieldNotFound(colId);+ if (!column || !isLinksOrLTAR(column.uidt)) NcError.fieldNotFound(colId);const colOptions = await column.getColOptions<LinkToAnotherRecordColumn>(baseModel.context,@@ -168,6 +176,53 @@ export class RelationManager {);}+ async getLinkV2RelatedRow() {+ const {+ childTable,+ childBaseModel,+ childTn,+ childColumn,+ childId,+ parentBaseModel,+ parentTn,+ parentColumn,+ relationColOptions,+ mmContext,+ } = this.relationContext;++ const vChildCol = await relationColOptions.getMMChildColumn(mmContext);+ const vParentCol = await relationColOptions.getMMParentColumn(mmContext);+ const vTable = await relationColOptions.getMMModel(mmContext);++ const assocBaseModel = await Model.getBaseModelSQL(mmContext, {+ model: vTable,+ dbDriver: childBaseModel.dbDriver,+ });++ const vTn = assocBaseModel.getTnPath(vTable);++ // Get related records from parent table through junction table+ return await parentBaseModel.execAndParse(+ parentBaseModel+ .dbDriver(parentTn)+ .select(`${parentTn}.*`)+ .join(+ vTn,+ `${vTn}.${vParentCol.column_name}`,+ `${parentTn}.${parentColumn.column_name}`,+ )+ .where({+ [`${vTn}.${vChildCol.column_name}`]: childBaseModel+ .dbDriver(childTn)+ .select(childColumn.column_name)+ .where(_wherePk(childTable.primaryKeys, childId))+ .first(),+ }),+ null,+ { raw: true },+ );+ }+async getHmOrOoChildLinkedWithParent() {const {childBaseModel: baseModel,@@ -201,7 +256,6 @@ export class RelationManager {}) {const {relationColOptions: colOptions,- relationColumn: column,baseModel,parentBaseModel,parentColumn,@@ -215,18 +269,10 @@ export class RelationManager {childId,parentId,mmContext,+ relationColumn,} = this.relationContext;- // Get the corresponding link column ID for the parent table- const refTableLinkColumnId = (- await extractCorrespondingLinkColumn(baseModel.context, {- ltarColumn: column,- referencedTable:- colOptions.fk_related_model_id === parentTable.id- ? parentTable- : childTable,- })- )?.id;+ const isMMLike = isMMOrMMLike(this.relationContext.relationColumn);const { onlyUpdateAuditLogs, req } = params;if (onlyUpdateAuditLogs && colOptions.type !== RelationTypes.BELONGS_TO) {@@ -245,7 +291,12 @@ export class RelationManager {child: childId,},);- switch (colOptions.type) {++ const relationType = isMMLike+ ? RelationTypes.MANY_TO_MANY+ : colOptions.type;++ switch (relationType) {case RelationTypes.MANY_TO_MANY:{const vChildCol = await colOptions.getMMChildColumn(mmContext);@@ -258,6 +309,76 @@ export class RelationManager {});const vTn = assocBaseModel.getTnPath(vTable);+ // if relation type is Many to One / One to One, then remove the existing link+ if (+ [RelationTypes.MANY_TO_ONE, RelationTypes.ONE_TO_ONE].includes(+ colOptions.type as RelationTypes,+ )+ ) {+ // Get existing children linked to this parent+ const existingChildren = await this.getLinkV2RelatedRow();++ // Remove each existing child with proper audit logging+ for (const child of existingChildren) {+ // Create a new relation manager with the correct IDs for this relationship+ const relationManager = await RelationManager.getRelationManager(+ baseModel,+ this.relationContext.relationColumn.id,+ {+ // in case of LinkToAnotherRecordV2, childId is the rowId+ rowId: childId,+ childId: getCompositePkValue(parentTable.primaryKeys, child),+ },+ );+ await relationManager.removeChild({ req });+ // merge audit logs+ this.auditUpdateObj.push(...relationManager.auditUpdateObj);+ }+ }++ // if relation type is One to Many / One to One, then remove any existing parent link+ if (+ [RelationTypes.ONE_TO_MANY, RelationTypes.ONE_TO_ONE].includes(+ colOptions.type as RelationTypes,+ )+ ) {+ const targetRelationColumn = await getTargetTableRelColumn(+ childBaseModel.context,+ relationColumn,+ parentTable,+ );+ const targetRelationManager =+ await RelationManager.getRelationManager(+ parentBaseModel,+ targetRelationColumn.id,+ {+ // in case of LinkToAnotherRecordV2, childId is the rowId+ rowId: parentId,+ // provide a dummy value+ childId: '',+ },+ );++ // Get existing children linked to this parent+ const existingChildren =+ await targetRelationManager.getLinkV2RelatedRow();++ // Remove each existing child with proper audit logging+ for (const child of existingChildren) {+ // Create a new relation manager with the correct IDs for this relationship+ const relationManager = await RelationManager.getRelationManager(+ parentBaseModel,+ targetRelationColumn.id,+ {+ rowId: parentId,+ childId: getCompositePkValue(childTable.primaryKeys, child),+ },+ );+ await relationManager.removeChild({ req });+ // merge audit logs+ this.auditUpdateObj.push(...relationManager.auditUpdateObj);+ }+ }if (baseModel.isSnowflake || baseModel.isDatabricks) {const parentPK = parentBaseModel@@ -667,8 +788,8 @@ export class RelationManager {async removeChild(params: { req: any }) {const {+ relationColumn,relationColOptions: colOptions,- relationColumn: column,baseModel,parentBaseModel,parentColumn,@@ -698,7 +819,11 @@ export class RelationManager {},);- switch (colOptions.type) {+ const relationType = isMMOrMMLike(relationColumn)+ ? RelationTypes.MANY_TO_MANY+ : colOptions.type;++ switch (relationType) {case RelationTypes.MANY_TO_MANY:{const vChildCol = await colOptions.getMMChildColumn(mmContext);diff --git a/packages/nocodb/src/helpers/columnHelpers.ts b/packages/nocodb/src/helpers/columnHelpers.tsindex 9aa9a90260..f1bf05201f 100644--- a/packages/nocodb/src/helpers/columnHelpers.ts+++ b/packages/nocodb/src/helpers/columnHelpers.ts@@ -2,6 +2,7 @@ import { customAlphabet } from 'nanoid';import {AppEvents,getAvailableRollupForUiType,+ isLinkV2,RelationTypes,UITypes,WebhookActions,@@ -12,6 +13,7 @@ import { NcError } from './ncError';import type {BoolType,ColumnReqType,+ LinkToAnotherRecordType,LookupColumnReqType,NcRequest,RollupColumnReqType,@@ -19,10 +21,10 @@ import type {} from 'nocodb-sdk';import type LinkToAnotherRecordColumn from '~/models/LinkToAnotherRecordColumn';import type LookupColumn from '~/models/LookupColumn';-import type Model from '~/models/Model';import type { NcContext } from '~/interface/config';import type { RollupColumn, View } from '~/models';import type { ColumnWebhookManager } from '~/utils/column-webhook-manager';+import Model from '~/models/Model';import { GridViewColumn } from '~/models';import validateParams from '~/helpers/validateParams';import { getUniqueColumnAliasName } from '~/helpers/getUniqueName';@@ -755,3 +757,53 @@ export const deleteColumnSystemPropsFromRequest = (col: any) => {delete col.validate;delete col.system;};++// get the reverse type of the relation+export const getRevType = (type: RelationTypes) => {+ switch (type) {+ case RelationTypes.BELONGS_TO:+ return RelationTypes.HAS_MANY;+ case RelationTypes.HAS_MANY:+ return RelationTypes.BELONGS_TO;+ case RelationTypes.MANY_TO_ONE:+ return RelationTypes.ONE_TO_MANY;+ case RelationTypes.ONE_TO_MANY:+ return RelationTypes.MANY_TO_ONE;+ }++ return type;+};++export const getTargetTableRelColumn = async (+ context: NcContext,+ relationColumn: Column,+ _targetTable?: Model,+) => {+ if (!isLinkV2(relationColumn)) {+ NcError.notImplemented();+ }++ const colOptions =+ await relationColumn.getColOptions<LinkToAnotherRecordColumn>(context);+ const { refContext } = colOptions.getRelContext(context);++ const targetTable =+ _targetTable ||+ (await Model.get(refContext, colOptions.fk_related_model_id));++ return await targetTable+ .getColumns(refContext)+ .then((columns) =>+ columns.find(+ (col: Column<LinkToAnotherRecordColumn>) =>+ col.uidt === UITypes.LinkToAnotherRecord &&+ col.colOptions?.fk_related_model_id === relationColumn.fk_model_id &&+ col &&+ col.colOptions?.fk_child_column_id ===+ colOptions.fk_parent_column_id &&+ col.colOptions?.fk_parent_column_id ===+ colOptions.fk_child_column_id &&+ col.colOptions?.fk_mm_model_id === colOptions.fk_mm_model_id,+ ),+ );+};diff --git a/packages/nocodb/src/services/columns.service.ts b/packages/nocodb/src/services/columns.service.tsindex 65d6d78f2a..da3743ef16 100644--- a/packages/nocodb/src/services/columns.service.ts+++ b/packages/nocodb/src/services/columns.service.ts@@ -10,9 +10,11 @@ import {isCreatedOrLastModifiedByCol,isCreatedOrLastModifiedTimeCol,isLinksOrLTAR,+ isMMOrMMLike,isServiceUser,isSystemColumn,isVirtualCol,+ LinksVersion,LongTextAiMetaProp,MetaEventType,NcApiVersion,@@ -3654,7 +3656,11 @@ export class ColumnsService implements IColumnsService {);const custom = column.meta?.custom;- switch (relationColOpt.type) {+ const isMMLike = isMMOrMMLike(column);++ const relationType = isMMLike ? 'mm' : relationColOpt.type;++ switch (relationType) {case 'bt':case 'hm':{@@ -4594,6 +4600,10 @@ export class ColumnsService implements IColumnsService {const reuse = param.reuse ?? {};+ // in new LTAR type we treat all relation similar to mm, so check if it's new type+ // version 1 is deprecated and will be removed in future+ const isMMLike = (param.column as any).version !== LinksVersion.V1;+// get table and refTable modelsconst table = await Model.getWithInfo(context, {id: (param.column as LinkToAnotherColumnReqType).parentId,