Skip to content

πŸ”₯ πŸ”₯ πŸ”₯ A Free & Self-hostable Airtable Alternative

feat: delete incompatible filters on column type change

Pranav C28f911dd9bec
diff --git a/packages/nocodb-sdk/src/lib/columnHelper/columns/Time.spec.ts b/packages/nocodb-sdk/src/lib/columnHelper/columns/Time.spec.ts
index f7223f815f..bf24e0a0b0 100644
--- a/packages/nocodb-sdk/src/lib/columnHelper/columns/Time.spec.ts
+++ b/packages/nocodb-sdk/src/lib/columnHelper/columns/Time.spec.ts
@@ -1,6 +1,6 @@
-import { ColumnType } from "~/lib/Api"
-import UITypes from "~/lib/UITypes"
-import { TimeHelper } from "./Time"
+import { ColumnType } from '~/lib/Api';
+import UITypes from '~/lib/UITypes';
+import { TimeHelper } from './Time';
describe('columnHelper', () => {
describe('Time', () => {
@@ -9,15 +9,17 @@ describe('columnHelper', () => {
const column = {
uidt: UITypes.Time,
meta: {
- time_format: 'HH:mm'
- }
+ time_format: 'HH:mm',
+ },
} as ColumnType;
const a = '02:15';
const b = '1999-01-01 02:15:00+07:00';
- const result = new TimeHelper().equalityComparison(a, b, {col: column})
- expect(result).toBe(true)
- })
- })
- })
-})
\ No newline at end of file
+ const result = new TimeHelper().equalityComparison(a, b, {
+ col: column,
+ });
+ expect(result).toBe(true);
+ });
+ });
+ });
+});
diff --git a/packages/nocodb-sdk/src/lib/filter/filterUtils.ts b/packages/nocodb-sdk/src/lib/filter/filterUtils.ts
new file mode 100644
index 0000000000..21e8b49ed6
--- /dev/null
+++ b/packages/nocodb-sdk/src/lib/filter/filterUtils.ts
@@ -0,0 +1,1130 @@
+import {
+ ClientType,
+ getEquivalentUIType,
+ isDateMonthFormat,
+ isNumericCol,
+ isSystemColumn,
+ isVirtualCol,
+ numericUITypes,
+ SqlUiFactory,
+ UITypes,
+} from '~/lib/UITypes';
+import type {
+ Api,
+ type ColumnType,
+ type FilterType,
+ type LinkToAnotherRecordType,
+ type LookupType,
+ type TableType,
+} from '~/lib/Api';
+
+export const MAX_NESTED_LEVEL = 5;
+export const excludedFilterColUidt = [
+ UITypes.QrCode,
+ UITypes.Barcode,
+ UITypes.Button,
+];
+
+export interface ComparisonOpUiType {
+ text: string;
+ value: string;
+ ignoreVal: boolean;
+ includedTypes?: UITypes[];
+ excludedTypes?: UITypes[];
+}
+
+export interface FilterGroupChangeEvent {
+ filters: ColumnFilterType[];
+ filter: ColumnFilterType | null;
+ type: 'row_changed' | 'add' | 'delete';
+ parentFilter?: ColumnFilterType;
+ fk_parent_id?: string;
+ prevValue?: any;
+ value: any;
+ index: number;
+}
+
+export interface FilterRowChangeEvent {
+ filter: ColumnFilterType;
+ type:
+ | 'logical_op'
+ | 'fk_column_id'
+ | 'fk_value_col_id'
+ | 'comparison_op'
+ | 'comparison_sub_op'
+ | 'value'
+ | 'dynamic'
+ | 'child_add'
+ | 'child_delete';
+ prevValue: any;
+ value: any;
+ index: number;
+}
+
+export type ColumnTypeForFilter = ColumnType & {
+ btLookupColumn?: ColumnTypeForFilter;
+ filterUidt?: UITypes;
+};
+
+export function isDateType(uidt: UITypes) {
+ return [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ ].includes(uidt);
+}
+
+const getEqText = (fieldUiType: UITypes) => {
+ if (isNumericCol(fieldUiType) || fieldUiType === UITypes.Time) {
+ return '=';
+ } else if (
+ [
+ UITypes.SingleSelect,
+ UITypes.Collaborator,
+ UITypes.LinkToAnotherRecord,
+ UITypes.Date,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ UITypes.DateTime,
+ ].includes(fieldUiType)
+ ) {
+ return 'is';
+ }
+ return 'is equal';
+};
+
+const getNeqText = (fieldUiType: UITypes) => {
+ if (isNumericCol(fieldUiType) || fieldUiType === UITypes.Time) {
+ return '!=';
+ } else if (
+ [
+ UITypes.SingleSelect,
+ UITypes.Collaborator,
+ UITypes.LinkToAnotherRecord,
+ UITypes.Date,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ UITypes.DateTime,
+ ].includes(fieldUiType)
+ ) {
+ return 'is not';
+ }
+ return 'is not equal';
+};
+
+const getLikeText = (fieldUiType: UITypes) => {
+ if (fieldUiType === UITypes.Attachment) {
+ return 'filenames contain';
+ }
+ return 'is like';
+};
+
+const getNotLikeText = (fieldUiType: UITypes) => {
+ if (fieldUiType === UITypes.Attachment) {
+ return "filenames don't contain";
+ }
+ return 'is not like';
+};
+
+const getGtText = (fieldUiType: UITypes) => {
+ if (
+ [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ ].includes(fieldUiType)
+ ) {
+ return 'is after';
+ }
+ return '>';
+};
+
+const getLtText = (fieldUiType: UITypes) => {
+ if (
+ [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ ].includes(fieldUiType)
+ ) {
+ return 'is before';
+ }
+ return '<';
+};
+
+const getGteText = (fieldUiType: UITypes) => {
+ if (
+ [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ ].includes(fieldUiType)
+ ) {
+ return 'is on or after';
+ }
+ return '>=';
+};
+
+const getLteText = (fieldUiType: UITypes) => {
+ if (
+ [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ ].includes(fieldUiType)
+ ) {
+ return 'is on or before';
+ }
+ return '<=';
+};
+
+export const comparisonOpList = (
+ fieldUiType: UITypes,
+
+ dateFormat?: string
+): ComparisonOpUiType[] => [
+ {
+ text: 'is checked',
+ value: 'checked',
+ ignoreVal: true,
+ includedTypes: [UITypes.Checkbox],
+ },
+ {
+ text: 'is not checked',
+ value: 'notchecked',
+ ignoreVal: true,
+ includedTypes: [UITypes.Checkbox],
+ },
+ {
+ text: getEqText(fieldUiType),
+ value: 'eq',
+ ignoreVal: false,
+ excludedTypes: [
+ UITypes.Checkbox,
+ UITypes.MultiSelect,
+ UITypes.Attachment,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ ],
+ },
+ {
+ text: getNeqText(fieldUiType),
+ value: 'neq',
+ ignoreVal: false,
+ excludedTypes: [
+ UITypes.Checkbox,
+ UITypes.MultiSelect,
+ UITypes.Attachment,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ ],
+ },
+ {
+ text: getLikeText(fieldUiType),
+ value: 'like',
+ ignoreVal: false,
+ excludedTypes: [
+ UITypes.Checkbox,
+ UITypes.SingleSelect,
+ UITypes.MultiSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ UITypes.Collaborator,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ UITypes.Time,
+ ...numericUITypes,
+ ],
+ },
+ {
+ text: getNotLikeText(fieldUiType),
+ value: 'nlike',
+ ignoreVal: false,
+ excludedTypes: [
+ UITypes.Checkbox,
+ UITypes.SingleSelect,
+ UITypes.MultiSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ UITypes.Collaborator,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ UITypes.Time,
+ ...numericUITypes,
+ ],
+ },
+ {
+ text: 'is empty',
+ value: 'empty',
+ ignoreVal: true,
+ excludedTypes: [
+ UITypes.Checkbox,
+ UITypes.SingleSelect,
+ UITypes.MultiSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ UITypes.Collaborator,
+ UITypes.Attachment,
+ UITypes.LinkToAnotherRecord,
+ UITypes.Lookup,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ UITypes.Time,
+ ...numericUITypes,
+ ],
+ },
+ {
+ text: 'is not empty',
+ value: 'notempty',
+ ignoreVal: true,
+ excludedTypes: [
+ UITypes.Checkbox,
+ UITypes.SingleSelect,
+ UITypes.MultiSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ UITypes.Collaborator,
+ UITypes.Attachment,
+ UITypes.LinkToAnotherRecord,
+ UITypes.Lookup,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ UITypes.Time,
+ ...numericUITypes,
+ ],
+ },
+ {
+ text: 'is null',
+ value: 'null',
+ ignoreVal: true,
+ excludedTypes: [
+ ...numericUITypes,
+ UITypes.Checkbox,
+ UITypes.SingleSelect,
+ UITypes.MultiSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ UITypes.Collaborator,
+ UITypes.Attachment,
+ UITypes.LinkToAnotherRecord,
+ UITypes.Lookup,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ UITypes.Time,
+ ],
+ },
+ {
+ text: 'is not null',
+ value: 'notnull',
+ ignoreVal: true,
+ excludedTypes: [
+ ...numericUITypes,
+ UITypes.Checkbox,
+ UITypes.SingleSelect,
+ UITypes.MultiSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ UITypes.Collaborator,
+ UITypes.Attachment,
+ UITypes.LinkToAnotherRecord,
+ UITypes.Lookup,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ UITypes.Time,
+ ],
+ },
+ {
+ text: 'contains all of',
+ value: 'allof',
+ ignoreVal: false,
+ includedTypes: [
+ UITypes.MultiSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ ],
+ },
+ {
+ text: 'contains any of',
+ value: 'anyof',
+ ignoreVal: false,
+ includedTypes: [
+ UITypes.MultiSelect,
+ UITypes.SingleSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ ],
+ },
+ {
+ text: 'does not contain all of',
+ value: 'nallof',
+ ignoreVal: false,
+ includedTypes: [
+ UITypes.MultiSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ ],
+ },
+ {
+ text: 'does not contain any of',
+ value: 'nanyof',
+ ignoreVal: false,
+ includedTypes: [
+ UITypes.MultiSelect,
+ UITypes.SingleSelect,
+ UITypes.User,
+ UITypes.CreatedBy,
+ UITypes.LastModifiedBy,
+ ],
+ },
+ {
+ text: getGtText(fieldUiType),
+ value: 'gt',
+ ignoreVal: false,
+ includedTypes: [
+ ...numericUITypes,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ UITypes.Time,
+ ],
+ },
+ {
+ text: getLtText(fieldUiType),
+ value: 'lt',
+ ignoreVal: false,
+ includedTypes: [
+ ...numericUITypes,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ UITypes.Time,
+ ],
+ },
+ {
+ text: getGteText(fieldUiType),
+ value: 'gte',
+ ignoreVal: false,
+ includedTypes: [
+ ...numericUITypes,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ UITypes.Time,
+ ],
+ },
+ {
+ text: getLteText(fieldUiType),
+ value: 'lte',
+ ignoreVal: false,
+ includedTypes: [
+ ...numericUITypes,
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.Time,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ ],
+ },
+ {
+ text: 'is within',
+ value: 'isWithin',
+ ignoreVal: true,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'is blank',
+ value: 'blank',
+ ignoreVal: true,
+ excludedTypes: [UITypes.Checkbox, UITypes.Links, UITypes.Rollup],
+ },
+ {
+ text: 'is not blank',
+ value: 'notblank',
+ ignoreVal: true,
+ excludedTypes: [UITypes.Checkbox, UITypes.Links, UITypes.Rollup],
+ },
+];
+
+export const comparisonSubOpList = (
+ // TODO: type
+ comparison_op: string,
+ dateFormat?: string
+): ComparisonOpUiType[] => {
+ const isDateMonth = dateFormat && isDateMonthFormat(dateFormat);
+
+ if (comparison_op === 'isWithin') {
+ return [
+ {
+ text: 'the past week',
+ value: 'pastWeek',
+ ignoreVal: true,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'the past month',
+ value: 'pastMonth',
+ ignoreVal: true,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'the past year',
+ value: 'pastYear',
+ ignoreVal: true,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'the next week',
+ value: 'nextWeek',
+ ignoreVal: true,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'the next month',
+ value: 'nextMonth',
+ ignoreVal: true,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'the next year',
+ value: 'nextYear',
+ ignoreVal: true,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'the next number of days',
+ value: 'nextNumberOfDays',
+ ignoreVal: false,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'the past number of days',
+ value: 'pastNumberOfDays',
+ ignoreVal: false,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ ];
+ }
+ return [
+ {
+ text: 'today',
+ value: 'today',
+ ignoreVal: true,
+ includedTypes: [
+ ...(isDateMonth
+ ? []
+ : [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ]),
+ ],
+ },
+ {
+ text: 'tomorrow',
+ value: 'tomorrow',
+ ignoreVal: true,
+ includedTypes: [
+ ...(isDateMonth
+ ? []
+ : [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ]),
+ ],
+ },
+ {
+ text: 'yesterday',
+ value: 'yesterday',
+ ignoreVal: true,
+ includedTypes: [
+ ...(isDateMonth
+ ? []
+ : [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ]),
+ ],
+ },
+ {
+ text: 'one week ago',
+ value: 'oneWeekAgo',
+ ignoreVal: true,
+ includedTypes: [
+ ...(isDateMonth
+ ? []
+ : [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ]),
+ ],
+ },
+ {
+ text: 'one week from now',
+ value: 'oneWeekFromNow',
+ ignoreVal: true,
+ includedTypes: [
+ ...(isDateMonth
+ ? []
+ : [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ]),
+ ],
+ },
+ {
+ text: 'one month ago',
+ value: 'oneMonthAgo',
+ ignoreVal: true,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'one month from now',
+ value: 'oneMonthFromNow',
+ ignoreVal: true,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ {
+ text: 'number of days ago',
+ value: 'daysAgo',
+ ignoreVal: false,
+ includedTypes: [
+ ...(isDateMonth
+ ? []
+ : [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ]),
+ ],
+ },
+ {
+ text: 'number of days from now',
+ value: 'daysFromNow',
+ ignoreVal: false,
+ includedTypes: [
+ ...(isDateMonth
+ ? []
+ : [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ]),
+ ],
+ },
+ {
+ text: isDateMonth ? 'exact month' : 'exact date',
+ value: 'exactDate',
+ ignoreVal: false,
+ includedTypes: [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.LastModifiedTime,
+ UITypes.CreatedTime,
+ ],
+ },
+ ];
+};
+
+export const getPlaceholderNewRow = (
+ filters: Filter[],
+ columns: ColumnType[],
+ option?: {
+ currentUser?: {
+ email: string;
+ id: string;
+ };
+ }
+) => {
+ if (filters.some((filter) => filter.logical_op === 'or')) {
+ return {};
+ }
+ const placeholderNewRow: Record<string, any> = {};
+ for (const eachFilter of filters) {
+ if (
+ ['checked', 'notchecked', 'allof', 'eq'].includes(
+ eachFilter.comparison_op as any
+ )
+ ) {
+ const column = columns.find((col) => col.id === eachFilter.fk_column_id);
+ if (column) {
+ if (
+ [
+ UITypes.Number,
+ UITypes.Decimal,
+ UITypes.SingleLineText,
+ UITypes.LongText,
+ UITypes.SingleSelect,
+ UITypes.GeoData,
+ UITypes.Email,
+ UITypes.PhoneNumber,
+ UITypes.URL,
+ UITypes.Time,
+ UITypes.Year,
+ UITypes.Currency,
+ UITypes.Percent,
+ UITypes.Rating,
+ UITypes.Duration,
+ UITypes.JSON,
+
+ // User is using allOf and anyOf so we cannot include it here
+ // UITypes.User,
+ ].includes(column.uidt as UITypes) ||
+ ([UITypes.Date, UITypes.DateTime].includes(column.uidt as UITypes) &&
+ eachFilter.comparison_sub_op === 'exactDate')
+ ) {
+ placeholderNewRow[column.title!] = eachFilter.value;
+ } else if (
+ [UITypes.Checkbox].includes(column.uidt as UITypes) &&
+ ['checked', 'notchecked'].includes(eachFilter.comparison_op as any)
+ ) {
+ placeholderNewRow[column.title!] =
+ eachFilter.comparison_op === 'checked';
+ } else if (
+ [UITypes.MultiSelect].includes(column.uidt as UITypes) &&
+ ['allof'].includes(eachFilter.comparison_op)
+ ) {
+ placeholderNewRow[column.title!] = eachFilter.value;
+ } else if (
+ [UITypes.User].includes(column.uidt as UITypes) &&
+ ['allof'].includes(eachFilter.comparison_op)
+ ) {
+ const isMulti = parseProp(column.meta)?.is_multi;
+ if (isMulti || eachFilter.value?.indexOf?.(',') < 0) {
+ const assignedValue = eachFilter.value
+ .split(',')
+ .map((k) => (k === '@me' ? option?.currentUser?.id : k))
+ .filter((k) => k)
+ .join(',');
+ placeholderNewRow[column.title!] = assignedValue;
+ }
+ }
+ }
+ }
+ }
+ return placeholderNewRow;
+};
+
+export const isComparisonOpAllowed = (
+ filter: ColumnFilterType,
+ compOp: {
+ text: string;
+ value: string;
+ ignoreVal?: boolean;
+ includedTypes?: UITypes[];
+ excludedTypes?: UITypes[];
+ },
+ uidt?: UITypes,
+ showNullAndEmptyInFilter?: boolean
+) => {
+ const isNullOrEmptyOp = ['empty', 'notempty', 'null', 'notnull'].includes(
+ compOp.value
+ );
+
+ if (compOp.includedTypes) {
+ // include allowed values only if selected column type matches
+ if (filter.fk_column_id && compOp.includedTypes.includes(uidt!)) {
+ // for 'empty', 'notempty', 'null', 'notnull',
+ // show them based on `showNullAndEmptyInFilter` in Base Settings
+ return isNullOrEmptyOp ? showNullAndEmptyInFilter : true;
+ } else {
+ return false;
+ }
+ } else if (compOp.excludedTypes) {
+ // include not allowed values only if selected column type not matches
+ if (filter.fk_column_id && !compOp.excludedTypes.includes(uidt!)) {
+ // for 'empty', 'notempty', 'null', 'notnull',
+ // show them based on `showNullAndEmptyInFilter` in Base Settings
+ return isNullOrEmptyOp ? showNullAndEmptyInFilter : true;
+ } else {
+ return false;
+ }
+ }
+ // explicitly include for non-null / non-empty ops
+ return isNullOrEmptyOp ? showNullAndEmptyInFilter : true;
+};
+
+export const isComparisonSubOpAllowed = (
+ filter: ColumnFilterType,
+ compOp: {
+ text: string;
+ value: string;
+ ignoreVal?: boolean;
+ includedTypes?: UITypes[];
+ excludedTypes?: UITypes[];
+ },
+ uidt?: UITypes
+) => {
+ if (compOp.includedTypes) {
+ // include allowed values only if selected column type matches
+ return filter.fk_column_id && compOp.includedTypes.includes(uidt!);
+ } else if (compOp.excludedTypes) {
+ // include not allowed values only if selected column type not matches
+ return filter.fk_column_id && !compOp.excludedTypes.includes(uidt!);
+ }
+};
+
+// filter is draft if it's not saved to db yet
+export const isFilterDraft = (filter: Filter, col: ColumnTypeForFilter) => {
+ if (filter.id) return false;
+
+ if (
+ filter.comparison_op &&
+ comparisonSubOpList(
+ filter.comparison_op,
+ parseProp(col?.meta)?.date_format
+ ).find((compOp) => compOp.value === filter.comparison_sub_op)?.ignoreVal
+ ) {
+ return false;
+ }
+
+ if (
+ comparisonOpList(
+ (col.filterUidt ?? col.uidt) as UITypes,
+ parseProp(col?.meta)?.date_format
+ ).find((compOp) => compOp.value === filter.comparison_op)?.ignoreVal
+ ) {
+ return false;
+ }
+
+ if (filter.value) {
+ return false;
+ }
+
+ return true;
+};
+
+export const isDynamicFilterAllowed = (
+ filter: ColumnFilterType,
+ column?: ColumnType,
+ dbClientType?: ClientType
+) => {
+ if (!column) {
+ return false;
+ }
+ // if virtual column, don't allow dynamic filter
+ if (isVirtualCol(column)) return false;
+ const sqlUi = SqlUiFactory.create({ client: dbClientType ?? ClientType.PG });
+
+ // disable dynamic filter for certain fields like rating, attachment, etc
+ if (
+ [
+ UITypes.Attachment,
+ UITypes.Rating,
+ UITypes.Checkbox,
+ UITypes.QrCode,
+ UITypes.Barcode,
+ UITypes.Collaborator,
+ UITypes.GeoData,
+ UITypes.SpecificDBType,
+ ].includes(column.uidt as UITypes)
+ )
+ return false;
+
+ const abstractType = sqlUi.getAbstractType(column);
+
+ if (!['integer', 'float', 'text', 'string'].includes(abstractType))
+ return false;
+
+ return (
+ !filter.comparison_op ||
+ ['eq', 'lt', 'gt', 'lte', 'gte', 'like', 'nlike', 'neq'].includes(
+ filter.comparison_op
+ )
+ );
+};
+
+export const getDynamicColumns = (
+ metaColumns: ColumnType[],
+ column?: ColumnType,
+ dbClientType?: ClientType
+) => {
+ if (!column) return [];
+ const sqlUi = SqlUiFactory.create({ client: dbClientType ?? ClientType.PG });
+
+ return metaColumns.filter((c: ColumnType) => {
+ if (
+ excludedFilterColUidt.includes(c.uidt as UITypes) ||
+ isVirtualCol(c) ||
+ (isSystemColumn(c) && !c.pk)
+ ) {
+ return false;
+ }
+
+ const dynamicColAbstractType = sqlUi.getAbstractType(c);
+
+ const filterColAbstractType = sqlUi.getAbstractType(column);
+
+ // treat float and integer as number
+ if (
+ [dynamicColAbstractType, filterColAbstractType].every((type) =>
+ ['float', 'integer'].includes(type)
+ )
+ ) {
+ return true;
+ }
+
+ // treat text and string as string
+ if (
+ [dynamicColAbstractType, filterColAbstractType].every((type) =>
+ ['text', 'string'].includes(type)
+ )
+ ) {
+ return true;
+ }
+
+ return filterColAbstractType === dynamicColAbstractType;
+ });
+};
+
+export const getFilterUidt = (col: ColumnTypeForFilter): UITypes => {
+ if (col.uidt === UITypes.Formula) {
+ const formulaUIType = getEquivalentUIType({
+ formulaColumn: col,
+ });
+
+ return (formulaUIType || col.uidt) as UITypes;
+ }
+ // if column is a lookup column, then use the lookup type extracted from the column
+ else if (col.btLookupColumn) {
+ return col.btLookupColumn.uidt as UITypes;
+ } else {
+ return col.uidt as UITypes;
+ }
+};
+
+export const composeColumnsForFilter = async ({
+ rootMeta,
+ getMeta,
+}: {
+ rootMeta: TableType;
+ getMeta: (metaIdOrTitle: string) => Promise<TableType | null>;
+}) => {
+ const result: ColumnTypeForFilter[] = [];
+ for (const column of rootMeta.columns!) {
+ if (column.uidt !== UITypes.Lookup) {
+ result.push({ ...column, filterUidt: getFilterUidt(column) });
+ continue;
+ }
+
+ let nextCol: ColumnType | undefined = column;
+ // check all the relation of nested lookup columns is bt or not
+ // include the column only if all only if all relations are bt
+ while (nextCol && nextCol.uidt === UITypes.Lookup) {
+ // extract the relation column meta
+ const lookupRelation: ColumnType | undefined = (
+ await getMeta(nextCol.fk_model_id!)
+ )?.columns?.find(
+ (c) =>
+ c.id === (nextCol!.colOptions as LookupType).fk_relation_column_id
+ );
+ // this is less likely to happen but if relation column is not found then break the loop
+ if (!lookupRelation) {
+ break;
+ }
+
+ const relatedTableMeta: TableType | null = await getMeta(
+ (lookupRelation?.colOptions as LinkToAnotherRecordType)
+ .fk_related_model_id!
+ );
+ nextCol = relatedTableMeta?.columns?.find(
+ (c) => c.id === (nextCol!.colOptions as LookupType).fk_lookup_column_id
+ );
+
+ // if next column is same as root lookup column then break the loop
+ // since it's going to be a circular loop
+ if (nextCol?.id === column.id) {
+ break;
+ }
+ }
+ const columnTypeForFilter: ColumnTypeForFilter = {
+ ...column,
+ btLookupColumn: nextCol,
+ };
+ columnTypeForFilter.filterUidt = getFilterUidt(columnTypeForFilter);
+ result.push(columnTypeForFilter);
+ }
+ return result;
+};
+
+export const getFilterCount = (filters: FilterType[]) => {
+ let result = 0;
+ for (const filter of filters) {
+ if (filter.is_group) {
+ result += getFilterCount(filter.children ?? []);
+ } else {
+ result += 1;
+ }
+ }
+ return result;
+};
+
+export const adjustFilterWhenColumnChange = ({
+ filter,
+ column,
+ showNullAndEmptyInFilter,
+}: {
+ filter: ColumnFilterType;
+ column: ColumnTypeForFilter;
+ showNullAndEmptyInFilter?: boolean;
+}) => {
+ const evalUidt: UITypes = column.filterUidt ?? column.uidt;
+ if (isVirtualCol(column)) {
+ filter.dynamic = false;
+ filter.fk_value_col_id = null;
+ } else {
+ filter.fk_value_col_id = null;
+ }
+ filter.comparison_op = comparisonOpList(
+ evalUidt,
+ parseProp(column.meta)?.date_format
+ ).find((compOp) =>
+ isComparisonOpAllowed(
+ filter,
+ compOp,
+ evalUidt as UITypes,
+ showNullAndEmptyInFilter
+ )
+ )?.value;
+
+ if (
+ isDateType(evalUidt) &&
+ !['blank', 'notblank'].includes(filter.comparison_op!)
+ ) {
+ if (filter.comparison_op === 'isWithin') {
+ filter.comparison_sub_op = 'pastNumberOfDays';
+ } else {
+ filter.comparison_sub_op = 'exactDate';
+ }
+ } else {
+ // reset
+ filter.comparison_sub_op = null;
+ }
+};
+
+export const deleteFilterWithSub = async (
+ $api: Api<unknown>,
+ filter: FilterType
+) => {
+ let result: string[] = [];
+ if (filter.is_group && filter.children?.length > 0) {
+ for (const child of filter.children) {
+ result = [...result, ...(await deleteFilterWithSub($api, child))];
+ }
+ }
+ await $api.dbTableFilter.delete(filter.id);
+ result.push(filter.id);
+ return result;
+};
+
+// Helper function to parse meta properties
+function parseProp(meta: any) {
+ if (typeof meta === 'string') {
+ try {
+ return JSON.parse(meta);
+ } catch {
+ return {};
+ }
+ }
+ return meta || {};
+}
+
+// Type definitions for compatibility
+export type Filter = FilterType;
+export type ColumnFilterType = FilterType;
diff --git a/packages/nocodb-sdk/src/lib/filter/index.ts b/packages/nocodb-sdk/src/lib/filter/index.ts
index 4175ac9673..c3f397fe18 100644
--- a/packages/nocodb-sdk/src/lib/filter/index.ts
+++ b/packages/nocodb-sdk/src/lib/filter/index.ts
@@ -1 +1,2 @@
export * from './validate-row-filters';
+export * from './filterUtils';
diff --git a/packages/nocodb-sdk/src/lib/scripts/index.ts b/packages/nocodb-sdk/src/lib/scripts/index.ts
index f0d1d65ed3..d9fafcbb7b 100644
--- a/packages/nocodb-sdk/src/lib/scripts/index.ts
+++ b/packages/nocodb-sdk/src/lib/scripts/index.ts
@@ -1,6 +1,5 @@
// Placeholder fns for scripts
export const hasInputCalls = (_scriptContent: string): boolean => {
- return false
-}
-
+ return false;
+};
diff --git a/packages/nocodb-sdk/src/lib/sync/index.ts b/packages/nocodb-sdk/src/lib/sync/index.ts
index f4d8c35b01..fbf49ea350 100644
--- a/packages/nocodb-sdk/src/lib/sync/index.ts
+++ b/packages/nocodb-sdk/src/lib/sync/index.ts
@@ -37,7 +37,7 @@ export const SyncTriggerMeta = {
label: 'Webhook',
description: 'Sync data via a webhook',
},
-}
+};
export const OnDeleteActionMeta = {
[OnDeleteAction.Delete]: {
@@ -50,7 +50,7 @@ export const OnDeleteActionMeta = {
label: 'Mark Deleted',
description: 'Mark data as deleted in NocoDB',
},
-}
+};
export const SyncTypeMeta = {
[SyncType.Full]: {
@@ -63,7 +63,7 @@ export const SyncTypeMeta = {
label: 'Incremental',
description: 'Sync only new and updated data',
},
-}
+};
export const SyncCategoryMeta = {
[SyncCategory.TICKETING]: {
@@ -90,7 +90,7 @@ export const SyncCategoryMeta = {
description: 'Sync data from a dynamic source',
icon: 'ncDatabase',
},
-}
+};
export enum TARGET_TABLES {
TICKETING_TICKET = 'ticketing_ticket',
@@ -132,4 +132,4 @@ export const TARGET_TABLES_META = {
description: 'Sync all teams from the source',
required: false,
},
-}
+};
diff --git a/packages/nocodb/src/modules/noco.module.ts b/packages/nocodb/src/modules/noco.module.ts
index c0f4335a51..8970976e7f 100644
--- a/packages/nocodb/src/modules/noco.module.ts
+++ b/packages/nocodb/src/modules/noco.module.ts
@@ -150,6 +150,7 @@ import { SortsV3Service } from '~/services/v3/sorts-v3.service';
import { TablesV3Service } from '~/services/v3/tables-v3.service';
import { ViewRowColorController } from '~/controllers/view-row-color.controller';
import { AttachmentUrlUploadHandler } from '~/services/emit-handler/attachment-url-upload.handler';
+import { FilterOperatorRegistryService } from '~/services/filter-operator-registry.service';
/* ACL */
import { AclMiddleware } from '~/middlewares/extract-ids/extract-ids.middleware';
@@ -341,6 +342,9 @@ export const nocoModuleMetadata = {
/* emit handlers */
AttachmentUrlUploadHandler,
+
+ /* Filter transformation services */
+ FilterOperatorRegistryService,
],
exports: [
/* Generic */
@@ -387,6 +391,9 @@ export const nocoModuleMetadata = {
DataAttachmentV3Service,
'IViewsV3Service',
+ /* Filter transformation services */
+ FilterOperatorRegistryService,
+
AttachmentUrlUploadHandler,
],
};
diff --git a/packages/nocodb/src/services/columns.service.ts b/packages/nocodb/src/services/columns.service.ts
index 17e952df37..c164bfe419 100644
--- a/packages/nocodb/src/services/columns.service.ts
+++ b/packages/nocodb/src/services/columns.service.ts
@@ -83,6 +83,7 @@ import Noco from '~/Noco';
import { AppHooksService } from '~/services/app-hooks/app-hooks.service';
import { IFormulaColumnTypeChanger } from '~/services/formula-column-type-changer.types';
import { ViewRowColorService } from '~/services/view-row-color.service';
+import { FiltersService } from '~/services/filters.service';
import NcConnectionMgrv2 from '~/utils/common/NcConnectionMgrv2';
import {
convertAIRecordTypeToValue,
@@ -208,6 +209,7 @@ export class ColumnsService implements IColumnsService {
@Inject(forwardRef(() => 'FormulaColumnTypeChanger'))
protected readonly formulaColumnTypeChanger: IFormulaColumnTypeChanger,
protected readonly viewRowColorService: ViewRowColorService,
+ protected readonly filtersService: FiltersService,
) {}
async updateFormulas(
@@ -1964,6 +1966,21 @@ export class ColumnsService implements IColumnsService {
// Get all the columns in the table and return
await table.getColumns(context, undefined, defaultViewId);
+ // Handle filter transformation if this is a column type change
+ if (column.uidt !== colBody.uidt) {
+ try {
+ await this.filtersService.transformFiltersForColumnTypeChange(
+ context,
+ column.id,
+ column.uidt as UITypes,
+ colBody.uidt as UITypes,
+ );
+ } catch (error) {
+ // Log error but don't fail the column update
+ console.error('Failed to transform filters for column type change:', error);
+ }
+ }
+
const updatedColumn = await Column.get(context, { colId: param.columnId });
this.appHooksService.emit(AppEvents.COLUMN_UPDATE, {
diff --git a/packages/nocodb/src/services/filter-operator-registry.service.ts b/packages/nocodb/src/services/filter-operator-registry.service.ts
new file mode 100644
index 0000000000..0b9eaf38ed
--- /dev/null
+++ b/packages/nocodb/src/services/filter-operator-registry.service.ts
@@ -0,0 +1,222 @@
+import { Injectable } from '@nestjs/common';
+
+// Define essential types locally since SDK has import issues
+export enum UITypes {
+ SingleLineText = 'SingleLineText',
+ LongText = 'LongText',
+ Number = 'Number',
+ Decimal = 'Decimal',
+ Currency = 'Currency',
+ Percent = 'Percent',
+ Date = 'Date',
+ DateTime = 'DateTime',
+ SingleSelect = 'SingleSelect',
+ MultiSelect = 'MultiSelect',
+ User = 'User',
+ CreatedBy = 'CreatedBy',
+ LastModifiedBy = 'LastModifiedBy',
+ Collaborator = 'Collaborator',
+ Email = 'Email',
+ PhoneNumber = 'PhoneNumber',
+ URL = 'URL',
+ GeoData = 'GeoData',
+ JSON = 'JSON',
+ Rating = 'Rating',
+ Duration = 'Duration',
+ Year = 'Year',
+ Time = 'Time',
+ CreatedTime = 'CreatedTime',
+ LastModifiedTime = 'LastModifiedTime',
+ Checkbox = 'Checkbox',
+ Attachment = 'Attachment',
+ LinkToAnotherRecord = 'LinkToAnotherRecord',
+ Links = 'Links',
+ Lookup = 'Lookup',
+ Rollup = 'Rollup',
+ QrCode = 'QrCode',
+ Barcode = 'Barcode',
+ Button = 'Button',
+ Formula = 'Formula',
+ Geometry = 'Geometry',
+}
+
+// Define FilterType interface locally
+export interface FilterType {
+ id?: string;
+ fk_column_id?: string;
+ comparison_op?: string;
+ comparison_sub_op?: string;
+ value?: any;
+ logical_op?: string;
+ is_group?: boolean;
+ children?: FilterType[];
+}
+
+export interface FilterTransformationResult {
+ shouldRemove: boolean;
+ transformedFilter?: FilterType;
+ reason?: string;
+}
+
+@Injectable()
+export class FilterOperatorRegistryService {
+ /**
+ * Check if an operator is compatible with a column type
+ * This method uses a simplified compatibility matrix focused on filter transformation needs
+ */
+ isOperatorCompatible(operator: string, columnType: UITypes): boolean {
+ // Define a focused compatibility matrix for filter transformation
+ const compatibilityMatrix: Record<string, UITypes[]> = {
+ // Equality operators - work with most types
+ eq: [UITypes.SingleLineText, UITypes.LongText, UITypes.Number, UITypes.Decimal, UITypes.Currency, UITypes.Percent, UITypes.Date, UITypes.DateTime, UITypes.SingleSelect, UITypes.MultiSelect, UITypes.User, UITypes.CreatedBy, UITypes.LastModifiedBy, UITypes.Collaborator, UITypes.Email, UITypes.PhoneNumber, UITypes.URL, UITypes.GeoData, UITypes.JSON, UITypes.Rating, UITypes.Duration, UITypes.Year, UITypes.Time, UITypes.CreatedTime, UITypes.LastModifiedTime, UITypes.Checkbox, UITypes.Attachment, UITypes.LinkToAnotherRecord, UITypes.Links, UITypes.Lookup, UITypes.Rollup],
+ neq: [UITypes.SingleLineText, UITypes.LongText, UITypes.Number, UITypes.Decimal, UITypes.Currency, UITypes.Percent, UITypes.Date, UITypes.DateTime, UITypes.SingleSelect, UITypes.MultiSelect, UITypes.User, UITypes.CreatedBy, UITypes.LastModifiedBy, UITypes.Collaborator, UITypes.Email, UITypes.PhoneNumber, UITypes.URL, UITypes.GeoData, UITypes.JSON, UITypes.Rating, UITypes.Duration, UITypes.Year, UITypes.Time, UITypes.CreatedTime, UITypes.LastModifiedTime, UITypes.Checkbox, UITypes.Attachment, UITypes.LinkToAnotherRecord, UITypes.Links, UITypes.Lookup, UITypes.Rollup],
+
+ // Text search operators - only for text-like types
+ like: [UITypes.SingleLineText, UITypes.LongText, UITypes.Email, UITypes.PhoneNumber, UITypes.URL, UITypes.GeoData, UITypes.JSON],
+ nlike: [UITypes.SingleLineText, UITypes.LongText, UITypes.Email, UITypes.PhoneNumber, UITypes.URL, UITypes.GeoData, UITypes.JSON],
+
+ // Numeric comparison operators - only for numeric and date types
+ gt: [UITypes.Number, UITypes.Decimal, UITypes.Currency, UITypes.Percent, UITypes.Date, UITypes.DateTime, UITypes.Time, UITypes.Year, UITypes.Duration, UITypes.Rating, UITypes.CreatedTime, UITypes.LastModifiedTime],
+ gte: [UITypes.Number, UITypes.Decimal, UITypes.Currency, UITypes.Percent, UITypes.Date, UITypes.DateTime, UITypes.Time, UITypes.Year, UITypes.Duration, UITypes.Rating, UITypes.CreatedTime, UITypes.LastModifiedTime],
+ lt: [UITypes.Number, UITypes.Decimal, UITypes.Currency, UITypes.Percent, UITypes.Date, UITypes.DateTime, UITypes.Time, UITypes.Year, UITypes.Duration, UITypes.Rating, UITypes.CreatedTime, UITypes.LastModifiedTime],
+ lte: [UITypes.Number, UITypes.Decimal, UITypes.Currency, UITypes.Percent, UITypes.Date, UITypes.DateTime, UITypes.Time, UITypes.Year, UITypes.Duration, UITypes.Rating, UITypes.CreatedTime, UITypes.LastModifiedTime],
+
+ // Multi-select operators
+ anyof: [UITypes.SingleSelect, UITypes.MultiSelect, UITypes.User, UITypes.CreatedBy, UITypes.LastModifiedBy],
+ nanyof: [UITypes.SingleSelect, UITypes.MultiSelect, UITypes.User, UITypes.CreatedBy, UITypes.LastModifiedBy],
+ allof: [UITypes.MultiSelect, UITypes.User, UITypes.CreatedBy, UITypes.LastModifiedBy],
+ nallof: [UITypes.MultiSelect, UITypes.User, UITypes.CreatedBy, UITypes.LastModifiedBy],
+
+ // Checkbox operators
+ checked: [UITypes.Checkbox],
+ notchecked: [UITypes.Checkbox],
+
+ // Null/empty operators - work with most types
+ empty: [UITypes.SingleLineText, UITypes.LongText, UITypes.Email, UITypes.PhoneNumber, UITypes.URL, UITypes.GeoData, UITypes.JSON],
+ notempty: [UITypes.SingleLineText, UITypes.LongText, UITypes.Email, UITypes.PhoneNumber, UITypes.URL, UITypes.GeoData, UITypes.JSON],
+ null: [UITypes.SingleLineText, UITypes.LongText, UITypes.Email, UITypes.PhoneNumber, UITypes.URL, UITypes.GeoData, UITypes.JSON, UITypes.Attachment, UITypes.LinkToAnotherRecord, UITypes.Links, UITypes.Lookup, UITypes.Rollup, UITypes.Date, UITypes.DateTime, UITypes.Time, UITypes.Collaborator],
+ notnull: [UITypes.SingleLineText, UITypes.LongText, UITypes.Email, UITypes.PhoneNumber, UITypes.URL, UITypes.GeoData, UITypes.JSON, UITypes.Attachment, UITypes.LinkToAnotherRecord, UITypes.Links, UITypes.Lookup, UITypes.Rollup, UITypes.Date, UITypes.DateTime, UITypes.Time, UITypes.Collaborator],
+
+ // Blank operators - work with most types
+ blank: [UITypes.SingleLineText, UITypes.LongText, UITypes.Number, UITypes.Decimal, UITypes.Currency, UITypes.Percent, UITypes.Date, UITypes.DateTime, UITypes.Time, UITypes.Year, UITypes.PhoneNumber, UITypes.Email, UITypes.URL, UITypes.GeoData, UITypes.JSON, UITypes.Rating, UITypes.Duration, UITypes.SingleSelect, UITypes.MultiSelect, UITypes.User, UITypes.CreatedBy, UITypes.LastModifiedBy, UITypes.Collaborator, UITypes.Attachment, UITypes.LinkToAnotherRecord, UITypes.Links, UITypes.Lookup, UITypes.Rollup, UITypes.QrCode, UITypes.Barcode, UITypes.Button, UITypes.Formula, UITypes.Geometry],
+ notblank: [UITypes.SingleLineText, UITypes.LongText, UITypes.Number, UITypes.Decimal, UITypes.Currency, UITypes.Percent, UITypes.Date, UITypes.DateTime, UITypes.Time, UITypes.Year, UITypes.PhoneNumber, UITypes.Email, UITypes.URL, UITypes.GeoData, UITypes.JSON, UITypes.Rating, UITypes.Duration, UITypes.SingleSelect, UITypes.MultiSelect, UITypes.User, UITypes.CreatedBy, UITypes.LastModifiedBy, UITypes.Collaborator, UITypes.Attachment, UITypes.LinkToAnotherRecord, UITypes.Links, UITypes.Lookup, UITypes.Rollup, UITypes.QrCode, UITypes.Barcode, UITypes.Button, UITypes.Formula, UITypes.Geometry],
+
+ // Date-specific operators
+ isWithin: [UITypes.Date, UITypes.DateTime, UITypes.CreatedTime, UITypes.LastModifiedTime]
+ };
+
+ const allowedTypes = compatibilityMatrix[operator];
+ return allowedTypes ? allowedTypes.includes(columnType) : false;
+ }
+
+ /**
+ * Get operator compatibility between two column types
+ */
+ getOperatorCompatibilityBetweenTypes(fromType: UITypes, toType: UITypes) {
+ // Get all operators that are compatible with both types
+ const allOperators = ['eq', 'neq', 'like', 'nlike', 'gt', 'gte', 'lt', 'lte', 'anyof', 'nanyof', 'allof', 'nallof', 'checked', 'notchecked', 'empty', 'notempty', 'null', 'notnull', 'blank', 'notblank', 'isWithin'];
+
+ return allOperators.filter(operator =>
+ this.isOperatorCompatible(operator, fromType) && this.isOperatorCompatible(operator, toType)
+ ).map(operator => ({
+ value: operator,
+ text: this.getOperatorDescription(operator)
+ }));
+ }
+
+ /**
+ * Get all operators that are compatible with a specific column type
+ */
+ getCompatibleOperators(columnType: UITypes): string[] {
+ const allOperators = ['eq', 'neq', 'like', 'nlike', 'gt', 'gte', 'lt', 'lte', 'anyof', 'nanyof', 'allof', 'nallof', 'checked', 'notchecked', 'empty', 'notempty', 'null', 'notnull', 'blank', 'notblank', 'isWithin'];
+
+ return allOperators.filter(operator => this.isOperatorCompatible(operator, columnType));
+ }
+
+ /**
+ * Get operator compatibility information for a specific operator
+ */
+ getOperatorCompatibility(operator: string) {
+ const description = this.getOperatorDescription(operator);
+ return { value: operator, text: description };
+ }
+
+ /**
+ * Validate if a filter is compatible with a column type change
+ */
+ validateFilterCompatibility(
+ filter: FilterType,
+ fromType: UITypes,
+ toType: UITypes,
+ ): FilterTransformationResult {
+ const operator = filter.comparison_op;
+ if (!operator) {
+ return {
+ shouldRemove: true,
+ reason: 'Filter has no comparison operator',
+ };
+ }
+
+ // Check if operator is compatible with target type
+ if (this.isOperatorCompatible(operator, toType)) {
+ return { shouldRemove: false, reason: 'Filter is compatible' };
+ }
+
+ // Operator is not compatible, filter must be removed
+ return {
+ shouldRemove: true,
+ reason: `Operator ${operator} is not compatible with column type ${toType}`,
+ };
+ }
+
+ /**
+ * Get all available operators
+ */
+ getAllOperators(): string[] {
+ return ['eq', 'neq', 'like', 'nlike', 'gt', 'gte', 'lt', 'lte', 'anyof', 'nanyof', 'allof', 'nallof', 'checked', 'notchecked', 'empty', 'notempty', 'null', 'notnull', 'blank', 'notblank', 'isWithin'];
+ }
+
+ /**
+ * Get operator descriptions
+ */
+ getOperatorDescriptions(): Record<string, string> {
+ const descriptions: Record<string, string> = {};
+ const allOperators = this.getAllOperators();
+
+ for (const operator of allOperators) {
+ descriptions[operator] = this.getOperatorDescription(operator);
+ }
+
+ return descriptions;
+ }
+
+ /**
+ * Get operator description
+ */
+ private getOperatorDescription(operator: string): string {
+ const descriptions: Record<string, string> = {
+ eq: 'Equals',
+ neq: 'Not equals',
+ like: 'Contains',
+ nlike: 'Does not contain',
+ gt: 'Greater than',
+ gte: 'Greater than or equal',
+ lt: 'Less than',
+ lte: 'Less than or equal',
+ anyof: 'Contains any of',
+ nanyof: 'Does not contain any of',
+ allof: 'Contains all of',
+ nallof: 'Does not contain all of',
+ checked: 'Is checked',
+ notchecked: 'Is not checked',
+ empty: 'Is empty',
+ notempty: 'Is not empty',
+ null: 'Is null',
+ notnull: 'Is not null',
+ blank: 'Is blank',
+ notblank: 'Is not blank',
+ isWithin: 'Is within time period',
+ };
+ return descriptions[operator] || operator;
+ }
+}
diff --git a/packages/nocodb/src/services/filters.service.ts b/packages/nocodb/src/services/filters.service.ts
index d153cc8352..dc08e6cfb1 100644
--- a/packages/nocodb/src/services/filters.service.ts
+++ b/packages/nocodb/src/services/filters.service.ts
@@ -1,20 +1,46 @@
import { Injectable } from '@nestjs/common';
-import { AppEvents, EventType } from 'nocodb-sdk';
import RowColorCondition from 'src/models/RowColorCondition';
-import type { FilterReqType, UserType } from 'nocodb-sdk';
+import { AppEvents, EventType, UITypes } from 'nocodb-sdk';
+import type { FilterReqType, FilterType, UserType, ViewType } from 'nocodb-sdk';
import type { NcContext, NcRequest } from '~/interface/config';
import type { ViewWebhookManager } from '~/utils/view-webhook-manager';
import type { MetaService } from 'src/meta/meta.service';
import { AppHooksService } from '~/services/app-hooks/app-hooks.service';
+import { FilterOperatorRegistryService } from '~/services/filter-operator-registry.service';
import { validatePayload } from '~/helpers';
import { NcError } from '~/helpers/catchError';
-import { Filter, Hook, View } from '~/models';
import NocoSocket from '~/socket/NocoSocket';
import { ViewWebhookManagerBuilder } from '~/utils/view-webhook-manager';
+import { Column, Filter, Hook, View } from '~/models';
+import Noco from '~/Noco';
+
+export interface FilterTransformationImpact {
+ viewId: string;
+ viewTitle: string;
+ originalFilters: FilterType;
+ transformedFilters: FilterType | null;
+ removedFilters: FilterType[];
+ modifiedFilters: FilterType[];
+ reason: string;
+}
+
+export interface ColumnTypeChangeImpact {
+ columnId: string;
+ columnTitle: string;
+ fromType: UITypes;
+ toType: UITypes;
+ impactedViews: FilterTransformationImpact[];
+ totalViewsImpacted: number;
+ totalFiltersRemoved: number;
+ totalFiltersModified: number;
+}
@Injectable()
export class FiltersService {
- constructor(protected readonly appHooksService: AppHooksService) {}
+ constructor(
+ protected readonly appHooksService: AppHooksService,
+ protected readonly filterOperatorRegistry: FilterOperatorRegistryService,
+ ) {}
async hookFilterCreate(
context: NcContext,
@@ -294,4 +320,682 @@ export class FiltersService {
// placeholder method
return null;
}
+
+ /**
+ * Analyze the impact of a column type change on all views and filters
+ */
+ async analyzeColumnTypeChangeImpact(
+ context: NcContext,
+ columnId: string,
+ fromType: UITypes,
+ toType: UITypes,
+ ncMeta = Noco.ncMeta,
+ ): Promise<ColumnTypeChangeImpact> {
+ const column = await Column.get(context, { colId: columnId }, ncMeta);
+ if (!column) {
+ throw new Error(`Column ${columnId} not found`);
+ }
+
+ // Get all views that reference this column
+ const views = await this.getViewsReferencingColumn(
+ context,
+ columnId,
+ ncMeta,
+ );
+
+ const impactedViews: FilterTransformationImpact[] = [];
+ let totalFiltersRemoved = 0;
+ let totalFiltersModified = 0;
+
+ for (const view of views) {
+ const impact = await this.analyzeViewFilterImpact(
+ context,
+ view,
+ columnId,
+ fromType,
+ toType,
+ ncMeta,
+ );
+
+ if (impact) {
+ impactedViews.push(impact);
+ totalFiltersRemoved += impact.removedFilters.length;
+ totalFiltersModified += impact.modifiedFilters.length;
+ }
+ }
+
+ return {
+ columnId,
+ columnTitle: column.title,
+ fromType,
+ toType,
+ impactedViews,
+ totalViewsImpacted: impactedViews.length,
+ totalFiltersRemoved,
+ totalFiltersModified,
+ };
+ }
+
+ /**
+ * Transform all filters for a column type change
+ */
+ async transformFiltersForColumnTypeChange(
+ context: NcContext,
+ columnId: string,
+ fromType: UITypes,
+ toType: UITypes,
+ ncMeta = Noco.ncMeta,
+ ): Promise<void> {
+ const impact = await this.analyzeColumnTypeChangeImpact(
+ context,
+ columnId,
+ fromType,
+ toType,
+ ncMeta,
+ );
+
+ // Apply transformations to each impacted view
+ for (const viewImpact of impact.impactedViews) {
+ await this.applyFilterTransformationToView(
+ context,
+ viewImpact.viewId,
+ viewImpact.transformedFilters,
+ ncMeta,
+ );
+ }
+
+ // Log the transformation
+ await this.logFilterTransformation(context, impact, ncMeta);
+ }
+
+ /**
+ * Get all views that reference a specific column
+ */
+ private async getViewsReferencingColumn(
+ context: NcContext,
+ columnId: string,
+ ncMeta = Noco.ncMeta,
+ ): Promise<ViewType[]> {
+ // Get the column to find its model ID
+ const column = await Column.get(context, { colId: columnId }, ncMeta);
+ if (!column) {
+ throw new Error(`Column ${columnId} not found`);
+ }
+
+ // Get all views in the model
+ const views = await View.list(context, column.fk_model_id, ncMeta);
+
+ const viewsWithFilters: ViewType[] = [];
+
+ for (const view of views) {
+ try {
+ const filters = await Filter.getFilterObject(
+ context,
+ {
+ viewId: view.id,
+ },
+ ncMeta,
+ );
+
+ // Check if this view has filters that reference the column
+ if (this.viewReferencesColumn(filters, columnId)) {
+ viewsWithFilters.push(view);
+ }
+ } catch (error) {
+ // Log warning but continue processing other views
+ console.warn(
+ `Failed to get filters for view ${view.id}: ${error.message}`,
+ );
+ }
+ }
+
+ return viewsWithFilters;
+ }
+
+ /**
+ * Check if a view's filters reference a specific column
+ */
+ private viewReferencesColumn(filters: FilterType, columnId: string): boolean {
+ if (!filters || !filters.children) {
+ return false;
+ }
+
+ return this.filterTreeReferencesColumn(filters.children, columnId);
+ }
+
+ /**
+ * Recursively check if a filter tree references a specific column
+ */
+ private filterTreeReferencesColumn(
+ filters: FilterType[],
+ columnId: string,
+ ): boolean {
+ for (const filter of filters) {
+ if (filter.fk_column_id === columnId) {
+ return true;
+ }
+
+ if (filter.children && filter.children.length > 0) {
+ if (this.filterTreeReferencesColumn(filter.children, columnId)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Analyze the impact of a column type change on a specific view
+ */
+ private async analyzeViewFilterImpact(
+ context: NcContext,
+ view: ViewType,
+ columnId: string,
+ fromType: UITypes,
+ toType: UITypes,
+ ncMeta = Noco.ncMeta,
+ ): Promise<FilterTransformationImpact | null> {
+ try {
+ const originalFilters = await Filter.getFilterObject(
+ context,
+ {
+ viewId: view.id,
+ },
+ ncMeta,
+ );
+
+ if (!originalFilters || !originalFilters.children) {
+ return null;
+ }
+
+ const transformedFilters = await this.transformFilterTree(
+ context,
+ originalFilters.children,
+ columnId,
+ fromType,
+ toType,
+ ncMeta,
+ );
+
+ const removedFilters = this.getRemovedFilters(
+ originalFilters.children,
+ transformedFilters,
+ columnId,
+ );
+
+ const modifiedFilters = this.getModifiedFilters(
+ originalFilters.children,
+ transformedFilters,
+ columnId,
+ );
+
+ // Only return impact if there are actual changes
+ if (removedFilters.length === 0 && modifiedFilters.length === 0) {
+ return null;
+ }
+
+ return {
+ viewId: view.id,
+ viewTitle: view.title,
+ originalFilters,
+ transformedFilters:
+ transformedFilters.length > 0
+ ? {
+ ...originalFilters,
+ children: transformedFilters,
+ }
+ : null,
+ removedFilters,
+ modifiedFilters,
+ reason: this.getTransformationReason(
+ fromType,
+ toType,
+ removedFilters,
+ modifiedFilters,
+ ),
+ };
+ } catch (error) {
+ console.warn(`Failed to analyze view ${view.id}: ${error.message}`);
+ return null;
+ }
+ }
+
+ /**
+ * Transform a filter tree for a column type change
+ */
+ private async transformFilterTree(
+ context: NcContext,
+ filters: FilterType[],
+ columnId: string,
+ fromType: UITypes,
+ toType: UITypes,
+ ncMeta = Noco.ncMeta,
+ ): Promise<FilterType[]> {
+ const transformedFilters: FilterType[] = [];
+
+ for (const filter of filters) {
+ if (filter.is_group && filter.children) {
+ // Recursively transform group filters
+ const transformedChildren = await this.transformFilterTree(
+ context,
+ filter.children,
+ columnId,
+ fromType,
+ toType,
+ ncMeta,
+ );
+
+ if (transformedChildren.length > 0) {
+ transformedFilters.push({
+ ...filter,
+ children: transformedChildren,
+ });
+ }
+ } else if (filter.fk_column_id === columnId) {
+ // Transform individual filter
+ const transformedFilter = this.transformIndividualFilter(
+ filter,
+ fromType,
+ toType,
+ );
+
+ if (transformedFilter) {
+ transformedFilters.push(transformedFilter);
+ }
+ } else {
+ // Keep filter unchanged
+ transformedFilters.push(filter);
+ }
+ }
+
+ return transformedFilters;
+ }
+
+ /**
+ * Transform an individual filter for a column type change
+ */
+ private transformIndividualFilter(
+ filter: FilterType,
+ fromType: UITypes,
+ toType: UITypes,
+ ): FilterType | null {
+ // Check if operator is still valid for the new type
+ if (
+ !this.filterOperatorRegistry.isOperatorCompatible(
+ filter.comparison_op!,
+ toType,
+ )
+ ) {
+ return null; // Remove filter if operator is not compatible
+ }
+
+ // For incompatible type changes (like number to string, string to number),
+ // we simply delete the filter instead of trying to convert it
+ if (this.isIncompatibleTypeChange(fromType, toType)) {
+ return null; // Remove filter for incompatible type changes
+ }
+
+ // Keep the filter unchanged if it's compatible
+ return filter;
+ }
+
+ /**
+ * Check if a type change is incompatible and should result in filter deletion
+ */
+ private isIncompatibleTypeChange(
+ fromType: UITypes,
+ toType: UITypes,
+ ): boolean {
+ // Number to String or String to Number - incompatible
+ if (
+ [
+ UITypes.Number,
+ UITypes.Decimal,
+ UITypes.Currency,
+ UITypes.Percent,
+ UITypes.Year,
+ UITypes.Duration,
+ UITypes.Rating,
+ ].includes(fromType) &&
+ [
+ UITypes.SingleLineText,
+ UITypes.LongText,
+ UITypes.Email,
+ UITypes.PhoneNumber,
+ UITypes.URL,
+ UITypes.GeoData,
+ UITypes.JSON,
+ ].includes(toType)
+ ) {
+ return true;
+ }
+
+ if (
+ [
+ UITypes.SingleLineText,
+ UITypes.LongText,
+ UITypes.Email,
+ UITypes.PhoneNumber,
+ UITypes.URL,
+ UITypes.GeoData,
+ UITypes.JSON,
+ ].includes(fromType) &&
+ [
+ UITypes.Number,
+ UITypes.Decimal,
+ UITypes.Currency,
+ UITypes.Percent,
+ UITypes.Year,
+ UITypes.Duration,
+ UITypes.Rating,
+ ].includes(toType)
+ ) {
+ return true;
+ }
+
+ // Select to LinkToAnotherRecord - incompatible
+ if (
+ [UITypes.SingleSelect, UITypes.MultiSelect].includes(fromType) &&
+ [UITypes.LinkToAnotherRecord, UITypes.Links].includes(toType)
+ ) {
+ return true;
+ }
+
+ // Date/Time to Text - incompatible
+ if (
+ [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.Time,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ ].includes(fromType) &&
+ [
+ UITypes.SingleLineText,
+ UITypes.LongText,
+ UITypes.Email,
+ UITypes.PhoneNumber,
+ UITypes.URL,
+ UITypes.GeoData,
+ UITypes.JSON,
+ ].includes(toType)
+ ) {
+ return true;
+ }
+
+ // Text to Date/Time - incompatible
+ if (
+ [
+ UITypes.SingleLineText,
+ UITypes.LongText,
+ UITypes.Email,
+ UITypes.PhoneNumber,
+ UITypes.URL,
+ UITypes.GeoData,
+ UITypes.JSON,
+ ].includes(fromType) &&
+ [
+ UITypes.Date,
+ UITypes.DateTime,
+ UITypes.Time,
+ UITypes.CreatedTime,
+ UITypes.LastModifiedTime,
+ ].includes(toType)
+ ) {
+ return true;
+ }
+
+ // Checkbox to Text - incompatible
+ if (
+ fromType === UITypes.Checkbox &&
+ [
+ UITypes.SingleLineText,
+ UITypes.LongText,
+ UITypes.Email,
+ UITypes.PhoneNumber,
+ UITypes.URL,
+ UITypes.GeoData,
+ UITypes.JSON,
+ ].includes(toType)
+ ) {
+ return true;
+ }
+
+ // Text to Checkbox - incompatible
+ if (
+ [
+ UITypes.SingleLineText,
+ UITypes.LongText,
+ UITypes.Email,
+ UITypes.PhoneNumber,
+ UITypes.URL,
+ UITypes.GeoData,
+ UITypes.JSON,
+ ].includes(fromType) &&
+ toType === UITypes.Checkbox
+ ) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Get filters that were removed during transformation
+ */
+ private getRemovedFilters(
+ originalFilters: FilterType[],
+ transformedFilters: FilterType[],
+ columnId: string,
+ ): FilterType[] {
+ const removed: FilterType[] = [];
+
+ for (const originalFilter of originalFilters) {
+ if (originalFilter.fk_column_id === columnId) {
+ const stillExists = transformedFilters.some(
+ (tf) => tf.id === originalFilter.id && tf.fk_column_id === columnId,
+ );
+
+ if (!stillExists) {
+ removed.push(originalFilter);
+ }
+ }
+ }
+
+ return removed;
+ }
+
+ /**
+ * Get filters that were modified during transformation
+ */
+ private getModifiedFilters(
+ originalFilters: FilterType[],
+ transformedFilters: FilterType[],
+ columnId: string,
+ ): FilterType[] {
+ const modified: FilterType[] = [];
+
+ for (const originalFilter of originalFilters) {
+ if (originalFilter.fk_column_id === columnId) {
+ const transformedFilter = transformedFilters.find(
+ (tf) => tf.id === originalFilter.id && tf.fk_column_id === columnId,
+ );
+
+ if (
+ transformedFilter &&
+ this.filtersAreDifferent(originalFilter, transformedFilter)
+ ) {
+ modified.push(originalFilter);
+ }
+ }
+ }
+
+ return modified;
+ }
+
+ /**
+ * Check if two filters are different
+ */
+ private filtersAreDifferent(
+ filter1: FilterType,
+ filter2: FilterType,
+ ): boolean {
+ return (
+ filter1.comparison_op !== filter2.comparison_op ||
+ filter1.comparison_sub_op !== filter2.comparison_sub_op ||
+ filter1.value !== filter2.value ||
+ filter1.logical_op !== filter2.logical_op
+ );
+ }
+
+ /**
+ * Get a human-readable reason for the transformation
+ */
+ private getTransformationReason(
+ fromType: UITypes,
+ toType: UITypes,
+ removedFilters: FilterType[],
+ modifiedFilters: FilterType[],
+ ): string {
+ if (removedFilters.length > 0 && modifiedFilters.length === 0) {
+ return `Column type changed from ${fromType} to ${toType}. ${removedFilters.length} filter(s) removed due to incompatibility.`;
+ } else if (removedFilters.length === 0 && modifiedFilters.length > 0) {
+ return `Column type changed from ${fromType} to ${toType}. ${modifiedFilters.length} filter(s) kept unchanged.`;
+ } else if (removedFilters.length > 0 && modifiedFilters.length > 0) {
+ return `Column type changed from ${fromType} to ${toType}. ${removedFilters.length} filter(s) removed due to incompatibility, ${modifiedFilters.length} filter(s) kept unchanged.`;
+ } else {
+ return `Column type changed from ${fromType} to ${toType}. No filters were affected.`;
+ }
+ }
+
+ /**
+ * Apply transformed filters to a view
+ */
+ private async applyFilterTransformationToView(
+ context: NcContext,
+ viewId: string,
+ transformedFilters: FilterType | null,
+ ncMeta = Noco.ncMeta,
+ ): Promise<void> {
+ try {
+ if (transformedFilters === null) {
+ // Remove all filters for this view
+ await Filter.deleteAll(context, viewId, ncMeta);
+ } else {
+ // Update filters for this view
+ await this.updateViewFilters(
+ context,
+ viewId,
+ transformedFilters,
+ ncMeta,
+ );
+ }
+ } catch (error) {
+ console.error(
+ `Failed to apply filter transformation to view ${viewId}: ${error.message}`,
+ );
+ throw error;
+ }
+ }
+
+ /**
+ * Update filters for a view
+ */
+ private async updateViewFilters(
+ context: NcContext,
+ viewId: string,
+ filters: FilterType,
+ ncMeta = Noco.ncMeta,
+ ): Promise<void> {
+ // First, remove all existing filters
+ await Filter.deleteAll(context, viewId, ncMeta);
+
+ // Then, insert the new transformed filters
+ if (filters.children && filters.children.length > 0) {
+ await this.insertFilterTree(
+ context,
+ viewId,
+ filters.children,
+ null,
+ ncMeta,
+ );
+ }
+ }
+
+ /**
+ * Recursively insert a filter tree
+ */
+ private async insertFilterTree(
+ context: NcContext,
+ viewId: string,
+ filters: FilterType[],
+ parentId: string | null,
+ ncMeta = Noco.ncMeta,
+ ): Promise<void> {
+ for (const filter of filters) {
+ const insertData = {
+ ...filter,
+ fk_view_id: viewId,
+ fk_parent_id: parentId,
+ };
+
+ const insertedFilter = await Filter.insert(context, insertData, ncMeta);
+
+ if (filter.children && filter.children.length > 0) {
+ await this.insertFilterTree(
+ context,
+ viewId,
+ filter.children,
+ insertedFilter.id,
+ ncMeta,
+ );
+ }
+ }
+ }
+
+ /**
+ * Log the filter transformation for audit purposes
+ */
+ private async logFilterTransformation(
+ context: NcContext,
+ impact: ColumnTypeChangeImpact,
+ ncMeta = Noco.ncMeta,
+ ): Promise<void> {
+ // This could be extended to write to an audit log table
+ console.log(
+ `Filter transformation completed for column ${impact.columnTitle}: ${impact.totalViewsImpacted} views impacted, ${impact.totalFiltersRemoved} filters removed, ${impact.totalFiltersModified} filters modified`,
+ );
+ }
+
+ /**
+ * Get a summary of the transformation impact for user display
+ */
+ getTransformationSummary(impact: ColumnTypeChangeImpact): string {
+ const { totalViewsImpacted, totalFiltersRemoved, totalFiltersModified } =
+ impact;
+
+ let summary = `Column type change will impact ${totalViewsImpacted} view(s). `;
+
+ if (totalFiltersRemoved > 0) {
+ summary += `${totalFiltersRemoved} filter(s) will be removed. `;
+ }
+
+ if (totalFiltersModified > 0) {
+ summary += `${totalFiltersModified} filter(s) will be modified. `;
+ }
+
+ if (totalFiltersRemoved === 0 && totalFiltersModified === 0) {
+ summary += 'No filters will be affected.';
+ }
+
+ return summary;
+ }
+
+ /**
+ * Check if a column type change requires user confirmation
+ */
+ requiresUserConfirmation(impact: ColumnTypeChangeImpact): boolean {
+ return impact.totalFiltersRemoved > 0 || impact.totalFiltersModified > 0;
+ }
}