Skip to content

The open alternative to Salesforce, designed for AI.

Remove dead code left behind by the v1 workspace ORM (#24737)

Charles Bochetb8125d2bc7fa
diff --git a/packages/twenty-server/src/engine/twenty-orm/entity-manager/types/deep-partial-entity-with-nested-relation-fields.type.ts b/packages/twenty-server/src/engine/twenty-orm/entity-manager/types/deep-partial-entity-with-nested-relation-fields.type.ts
deleted file mode 100644
index 8a60e857440..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/entity-manager/types/deep-partial-entity-with-nested-relation-fields.type.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { type DeepPartial } from 'typeorm/common/DeepPartial';
-
-import { type BaseWorkspaceEntity } from 'src/engine/twenty-orm/base.workspace-entity';
-import {
- type ConnectObject,
- type DisconnectObject,
- type EntityRelationFields,
-} from 'src/engine/twenty-orm/entity-manager/types/query-deep-partial-entity-with-nested-relation-fields.type';
-
-export type DeepPartialWithNestedRelationFields<T> = Omit<
- DeepPartial<T>,
- EntityRelationFields<T>
-> & {
- [K in keyof T]?: T[K] extends BaseWorkspaceEntity | null
- ? DeepPartial<T[K]> | ConnectObject | DisconnectObject
- : DeepPartial<T[K]>;
-};
diff --git a/packages/twenty-server/src/engine/twenty-orm/exceptions/relation.exception.ts b/packages/twenty-server/src/engine/twenty-orm/exceptions/relation.exception.ts
deleted file mode 100644
index e865629668a..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/exceptions/relation.exception.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { type MessageDescriptor } from '@lingui/core';
-import { assertUnreachable } from 'twenty-shared/utils';
-
-import { STANDARD_ERROR_MESSAGE } from 'src/engine/api/common/common-query-runners/errors/standard-error-message.constant';
-import { CustomException } from 'src/utils/custom-exception';
-
-export enum RelationExceptionCode {
- RELATION_OBJECT_METADATA_NOT_FOUND = 'RELATION_OBJECT_METADATA_NOT_FOUND',
- RELATION_TARGET_FIELD_METADATA_ID_NOT_FOUND = 'RELATION_TARGET_FIELD_METADATA_ID_NOT_FOUND',
- RELATION_JOIN_COLUMN_ON_BOTH_SIDES = 'RELATION_JOIN_COLUMN_ON_BOTH_SIDES',
- MISSING_RELATION_JOIN_COLUMN = 'MISSING_RELATION_JOIN_COLUMN',
- MULTIPLE_JOIN_COLUMNS_FOUND = 'MULTIPLE_JOIN_COLUMNS_FOUND',
-}
-
-const getRelationExceptionUserFriendlyMessage = (
- code: RelationExceptionCode,
-) => {
- switch (code) {
- case RelationExceptionCode.RELATION_OBJECT_METADATA_NOT_FOUND:
- case RelationExceptionCode.RELATION_TARGET_FIELD_METADATA_ID_NOT_FOUND:
- case RelationExceptionCode.RELATION_JOIN_COLUMN_ON_BOTH_SIDES:
- case RelationExceptionCode.MISSING_RELATION_JOIN_COLUMN:
- case RelationExceptionCode.MULTIPLE_JOIN_COLUMNS_FOUND:
- return STANDARD_ERROR_MESSAGE;
- default:
- assertUnreachable(code);
- }
-};
-
-export class RelationException extends CustomException<RelationExceptionCode> {
- constructor(
- message: string,
- code: RelationExceptionCode,
- { userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
- ) {
- super(message, code, {
- userFriendlyMessage:
- userFriendlyMessage ?? getRelationExceptionUserFriendlyMessage(code),
- });
- }
-}
diff --git a/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager.ts b/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager.ts
index 00e82ad910a..5948b2b4f04 100644
--- a/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/global-workspace-datasource/global-workspace-orm.manager.ts
@@ -141,7 +141,6 @@ export class GlobalWorkspaceOrmManager {
objectIdByNameSingular,
featureFlagsMap,
permissionsPerRoleId,
- entityMetadatas: [],
userWorkspaceRoleMap,
apiKeyRoleMap,
};
@@ -183,7 +182,6 @@ export class GlobalWorkspaceOrmManager {
objectIdByNameSingular,
featureFlagsMap: {} as ORMWorkspaceContext['featureFlagsMap'],
permissionsPerRoleId: {},
- entityMetadatas: [],
userWorkspaceRoleMap: {},
apiKeyRoleMap: {},
};
diff --git a/packages/twenty-server/src/engine/twenty-orm/interfaces/gate.interface.ts b/packages/twenty-server/src/engine/twenty-orm/interfaces/gate.interface.ts
deleted file mode 100644
index 9485e4aa59b..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/interfaces/gate.interface.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export interface Gate {
- featureFlag: string;
- excludeFromDatabase?: boolean;
- excludeFromWorkspaceApi?: boolean;
-}
diff --git a/packages/twenty-server/src/engine/twenty-orm/repository/permissions.utils.ts b/packages/twenty-server/src/engine/twenty-orm/repository/permissions.utils.ts
index 13d07a73d24..7a7caf33d53 100644
--- a/packages/twenty-server/src/engine/twenty-orm/repository/permissions.utils.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/repository/permissions.utils.ts
@@ -6,10 +6,8 @@ import {
type RestrictedFieldsPermissions,
} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-import { type QueryExpressionMap } from 'typeorm/query-builder/QueryExpressionMap';
import { InternalServerError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-import { extractColumnNamesFromAggregateExpression } from 'src/utils/extract-column-names-from-aggregate-expression.util';
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
@@ -26,43 +24,6 @@ import { getColumnNameToFieldMetadataIdMap } from 'src/engine/twenty-orm/utils/g
const WORKSPACE_MEMBER_OBJECT_UNIVERSAL_IDENTIFIER =
STANDARD_OBJECTS.workspaceMember.universalIdentifier;
-const getTargetEntityAndOperationType = (
- expressionMap: QueryExpressionMap,
-):
- | {
- isSubQuery: true;
- mainEntity?: undefined;
- operationType?: undefined;
- }
- | {
- isSubQuery?: undefined;
- mainEntity: string;
- operationType:
- | 'select'
- | 'insert'
- | 'update'
- | 'delete'
- | 'restore'
- | 'soft-delete'
- | 'relation';
- } => {
- const isSubQuery = expressionMap.aliases[0].subQuery;
-
- if (isSubQuery) {
- return {
- isSubQuery: true, // will bypass permission checks because subQuery permissions will be evaluated when it is executed. This is valid for groupBy with records usecase. If your usecase is different, make sure permission checks are run.
- };
- }
-
- const mainEntity = expressionMap.aliases[0].metadata.name;
- const operationType = expressionMap.queryType;
-
- return {
- mainEntity,
- operationType,
- };
-};
-
export type OperationType =
| 'select'
| 'insert'
@@ -271,227 +232,6 @@ export const validateOperationIsPermittedOrThrow = ({
}
};
-type ValidateQueryIsPermittedOrThrowArgs = {
- expressionMap: QueryExpressionMap;
- objectsPermissions: ObjectsPermissions;
- flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
- flatFieldMetadataMaps: FlatEntityMaps<FlatFieldMetadata>;
- objectIdByNameSingular: Record<string, string>;
- shouldBypassPermissionChecks: boolean;
- authContext?: WorkspaceAuthContext;
-};
-
-export const validateQueryIsPermittedOrThrow = ({
- expressionMap,
- objectsPermissions,
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- objectIdByNameSingular,
- shouldBypassPermissionChecks,
- authContext,
-}: ValidateQueryIsPermittedOrThrowArgs) => {
- if (shouldBypassPermissionChecks) {
- return;
- }
-
- const { mainEntity, operationType, isSubQuery } =
- getTargetEntityAndOperationType(expressionMap);
-
- if (isSubQuery) {
- return;
- }
-
- let expressionMapSelectsOnMainEntity = expressionMap.selects;
-
- if (!isEmpty(expressionMap.joinAttributes)) {
- const { selectsWithoutJoinedAliases } =
- validatePermissionsForJoinsAndReturnSelectsWithoutJoins({
- expressionMap,
- objectsPermissions,
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- objectIdByNameSingular,
- });
-
- expressionMapSelectsOnMainEntity = selectsWithoutJoinedAliases;
-
- validateJoinedOrderByColumnsArePermittedOrThrow({
- expressionMap,
- objectsPermissions,
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- objectIdByNameSingular,
- });
- }
-
- const allFieldsSelected = expressionMapSelectsOnMainEntity.some(
- (select) => select.selection === mainEntity,
- );
-
- let selectedColumns: string[] | '*' = [];
- let updatedColumns: string[] = [];
-
- selectedColumns = getSelectedColumnsFromExpressionMap({
- operationType,
- expressionMapReturning: expressionMap.returning,
- expressionMapSelects: expressionMapSelectsOnMainEntity,
- allFieldsSelected,
- });
-
- if (operationType !== 'select') {
- const valuesSet = expressionMap.valuesSet;
-
- if (Array.isArray(valuesSet)) {
- updatedColumns = valuesSet.reduce((acc, value) => {
- const keys = Object.keys(value);
-
- keys.forEach((key) => {
- if (!acc.includes(key)) {
- acc.push(key);
- }
- });
-
- return acc;
- }, []);
- } else {
- updatedColumns = Object.keys(valuesSet ?? {});
- }
- }
-
- validateOperationIsPermittedOrThrow({
- entityName: mainEntity,
- operationType: operationType as OperationType,
- objectsPermissions,
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- objectIdByNameSingular,
- selectedColumns,
- allFieldsSelected,
- updatedColumns,
- authContext,
- });
-};
-
-const validatePermissionsForJoinsAndReturnSelectsWithoutJoins = ({
- expressionMap,
- objectsPermissions,
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- objectIdByNameSingular,
-}: {
- expressionMap: QueryExpressionMap;
- objectsPermissions: ObjectsPermissions;
- flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
- flatFieldMetadataMaps: FlatEntityMaps<FlatFieldMetadata>;
- objectIdByNameSingular: Record<string, string>;
-}) => {
- const joinAttributesAliases = new Set(
- expressionMap.joinAttributes.map((join) => join.alias.name),
- );
-
- const indexesOfSelectsForJoinedAlias: number[] = [];
-
- for (const [_index, joinedAlias] of joinAttributesAliases.entries()) {
- const entity = expressionMap.aliases.find(
- (alias) => alias.type === 'join' && alias.name === joinedAlias,
- )?.metadata;
-
- if (isDefined(entity)) {
- for (const [index, select] of expressionMap.selects.entries()) {
- const regex = /"(\w+)"\."(\w+)"/;
- const extractedAlias = select.selection.match(regex)?.[1]; // "person"."name" -> "person"
-
- if (isDefined(extractedAlias) && extractedAlias === joinedAlias) {
- indexesOfSelectsForJoinedAlias.push(index);
-
- const selectedColumns = getSelectedColumnsFromExpressionMap({
- operationType: 'select',
- expressionMapSelects: expressionMap.selects.filter(
- (_select, indexOfSelect) => indexOfSelect === index,
- ),
- allFieldsSelected: false,
- });
-
- validateOperationIsPermittedOrThrow({
- entityName: entity.name,
- operationType: 'select' as OperationType,
- objectsPermissions,
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- objectIdByNameSingular,
- selectedColumns,
- allFieldsSelected: false,
- updatedColumns: [],
- });
- }
- }
- }
- }
-
- const selectsWithoutJoinedAliases = expressionMap.selects.filter(
- (_select, index) => !indexesOfSelectsForJoinedAlias.includes(index),
- );
-
- return { selectsWithoutJoinedAliases };
-};
-
-const validateJoinedOrderByColumnsArePermittedOrThrow = ({
- expressionMap,
- objectsPermissions,
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- objectIdByNameSingular,
-}: {
- expressionMap: QueryExpressionMap;
- objectsPermissions: ObjectsPermissions;
- flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
- flatFieldMetadataMaps: FlatEntityMaps<FlatFieldMetadata>;
- objectIdByNameSingular: Record<string, string>;
-}) => {
- const columnsByJoinedAlias = new Map<string, Set<string>>();
- const columnReferenceRegex = /"(\w+)"\."(\w+)"/g;
-
- for (const orderByExpression of Object.keys(expressionMap.orderBys)) {
- for (const [, alias, column] of orderByExpression.matchAll(
- columnReferenceRegex,
- )) {
- const columnsForAlias = columnsByJoinedAlias.get(alias) ?? new Set();
-
- columnsForAlias.add(column);
- columnsByJoinedAlias.set(alias, columnsForAlias);
- }
- }
-
- for (const joinAttribute of expressionMap.joinAttributes) {
- const joinedAlias = joinAttribute.alias.name;
- const referencedColumns = columnsByJoinedAlias.get(joinedAlias);
-
- if (!isDefined(referencedColumns)) {
- continue;
- }
-
- const entity = expressionMap.aliases.find(
- (alias) => alias.type === 'join' && alias.name === joinedAlias,
- )?.metadata;
-
- if (!isDefined(entity)) {
- continue;
- }
-
- validateOperationIsPermittedOrThrow({
- entityName: entity.name,
- operationType: 'select',
- objectsPermissions,
- flatObjectMetadataMaps,
- flatFieldMetadataMaps,
- objectIdByNameSingular,
- selectedColumns: [...referencedColumns],
- allFieldsSelected: false,
- updatedColumns: [],
- });
- }
-};
-
const buildFieldPermissionDeniedMessage = ({
action,
column,
@@ -608,55 +348,3 @@ const validateUpdateFieldPermissionOrThrow = ({
}
}
};
-
-const getSelectedColumnsFromExpressionMap = ({
- operationType,
- expressionMapReturning,
- expressionMapSelects,
- allFieldsSelected,
-}: {
- operationType: string;
- expressionMapSelects: { selection: string }[];
- allFieldsSelected: boolean;
- expressionMapReturning?: string | string[];
-}) => {
- let selectedColumns: string[] | '*' = [];
-
- if (
- ['update', 'insert', 'delete', 'soft-delete', 'restore'].includes(
- operationType,
- )
- ) {
- if (!isDefined(expressionMapReturning)) {
- throw new InternalServerError(
- 'Returning columns are not set for update query',
- );
- }
- selectedColumns =
- expressionMapReturning === '*' ? '*' : [expressionMapReturning].flat();
- } else if (!allFieldsSelected) {
- selectedColumns =
- getSelectedColumnsFromExpressionMapSelects(expressionMapSelects);
- }
-
- return selectedColumns;
-};
-
-const getSelectedColumnsFromExpressionMapSelects = (
- selects: { selection: string }[],
-) => {
- return selects
- ?.map((select) => {
- const columnsFromAggregateExpression =
- extractColumnNamesFromAggregateExpression(select.selection);
-
- if (columnsFromAggregateExpression) {
- return columnsFromAggregateExpression;
- }
-
- const parts = select.selection.split('.');
-
- return parts[parts.length - 1];
- })
- .flat();
-};
diff --git a/packages/twenty-server/src/engine/twenty-orm/storage/orm-workspace-context.storage.ts b/packages/twenty-server/src/engine/twenty-orm/storage/orm-workspace-context.storage.ts
index f133700731f..d7504dbc381 100644
--- a/packages/twenty-server/src/engine/twenty-orm/storage/orm-workspace-context.storage.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/storage/orm-workspace-context.storage.ts
@@ -4,7 +4,6 @@ import {
type ObjectsPermissionsByRoleId,
type FeatureFlagKey,
} from 'twenty-shared/types';
-import { type EntityMetadata } from 'typeorm';
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
@@ -23,7 +22,6 @@ export type ORMWorkspaceContext = {
objectIdByNameSingular: Record<string, string>;
featureFlagsMap: Record<FeatureFlagKey, boolean>;
permissionsPerRoleId: ObjectsPermissionsByRoleId;
- entityMetadatas: EntityMetadata[];
userWorkspaceRoleMap: UserWorkspaceRoleMap;
apiKeyRoleMap: Record<string, string>;
flatRowLevelPermissionPredicateMaps: FlatRowLevelPermissionPredicateMaps;
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/apply-table-alias-on-where-condition.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/apply-table-alias-on-where-condition.util.spec.ts
deleted file mode 100644
index 4c30ffb2c06..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/apply-table-alias-on-where-condition.util.spec.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import { type WhereClauseCondition } from 'typeorm/query-builder/WhereClause';
-
-import { applyTableAliasOnWhereCondition } from 'src/engine/twenty-orm/utils/apply-table-alias-on-where-condition';
-
-describe('applyTableAliasOnWhereCondition', () => {
- const tableName = '_listing';
- const aliasName = 'listing';
-
- describe('when processing simple where conditions with string conditions', () => {
- it('should replace alias name with table name in string condition', () => {
- const condition: WhereClauseCondition = [
- {
- type: 'simple',
- condition: `${aliasName}.id = :id`,
- },
- ];
-
- const result = applyTableAliasOnWhereCondition({
- condition,
- tableName,
- aliasName,
- });
-
- expect(result).toEqual([
- {
- type: 'simple',
- condition: `${tableName}.id = :id`,
- },
- ]);
- });
-
- it('should replace alias name with table name in array condition and wrapping operator condition', () => {
- const condition: WhereClauseCondition = [
- {
- type: 'simple',
- condition: {
- operator: 'brackets',
- condition: [
- {
- type: 'simple',
- condition: `"${aliasName}"."id" IN (:...id8oi6y)`,
- },
- ],
- },
- },
- ];
-
- const result = applyTableAliasOnWhereCondition({
- condition,
- tableName,
- aliasName,
- });
-
- expect(result).toEqual([
- {
- type: 'simple',
- condition: {
- operator: 'brackets',
- condition: [
- {
- type: 'simple',
- condition: `"${tableName}"."id" IN (:...id8oi6y)`,
- },
- ],
- },
- },
- ]);
- });
-
- it('should replace alias name with table name in object condition', () => {
- const condition: WhereClauseCondition = {
- parameters: ['id'],
- operator: 'equal',
- };
-
- const result = applyTableAliasOnWhereCondition({
- condition,
- tableName,
- aliasName,
- });
-
- expect(result).toEqual({
- operator: 'equal',
- parameters: ['id'],
- });
- });
-
- it('should replace alias name with table name in string condition without alias name', () => {
- const condition: WhereClauseCondition = [
- {
- type: 'simple',
- condition: `id = :id`,
- },
- ];
-
- const result = applyTableAliasOnWhereCondition({
- condition,
- tableName,
- aliasName,
- });
-
- expect(result).toEqual([
- {
- type: 'simple',
- condition: `id = :id`,
- },
- ]);
- });
-
- it('should replace alias name with table name in string condition without quotes', () => {
- const condition: WhereClauseCondition = [
- {
- type: 'simple',
- condition: `${aliasName}."id" = :id`,
- },
- ];
-
- const result = applyTableAliasOnWhereCondition({
- condition,
- tableName,
- aliasName,
- });
-
- expect(result).toEqual([
- {
- type: 'simple',
- condition: `${tableName}."id" = :id`,
- },
- ]);
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/get-default-columns-for-index.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/get-default-columns-for-index.util.spec.ts
deleted file mode 100644
index 9526ba5a3a9..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/get-default-columns-for-index.util.spec.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { IndexType } from 'src/engine/metadata-modules/index-metadata/types/indexType.types';
-import { getColumnsForIndex } from 'src/engine/twenty-orm/utils/get-default-columns-for-index.util';
-
-describe('getColumnsForIndex', () => {
- it('should return ["deletedAt"] when indexType is undefined', () => {
- const result = getColumnsForIndex();
-
- expect(result).toEqual(['deletedAt']);
- });
-
- it('should return an empty array when indexType is IndexType.GIN', () => {
- const result = getColumnsForIndex(IndexType.GIN);
-
- expect(result).toEqual([]);
- });
-
- it('should return ["deletedAt"] when indexType is IndexType.BTREE', () => {
- const result = getColumnsForIndex(IndexType.BTREE);
-
- expect(result).toEqual(['deletedAt']);
- });
-});
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/apply-table-alias-on-where-condition.ts b/packages/twenty-server/src/engine/twenty-orm/utils/apply-table-alias-on-where-condition.ts
deleted file mode 100644
index 29c04407d19..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/utils/apply-table-alias-on-where-condition.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { isArray, isObject, isString } from '@sniptt/guards';
-import {
- type WhereClause,
- type WhereClauseCondition,
-} from 'typeorm/query-builder/WhereClause';
-
-type ApplyTableAliasOnWhereConditionParams = {
- condition: WhereClauseCondition;
- tableName: string;
- aliasName: string;
-};
-
-export const applyTableAliasOnWhereCondition = ({
- condition,
- tableName,
- aliasName,
-}: ApplyTableAliasOnWhereConditionParams): WhereClauseCondition => {
- if (isString(condition)) {
- const conditionParts = condition.split('.');
-
- if (conditionParts.length === 1) {
- return condition;
- }
-
- const [tableNamePart, ...rest] = conditionParts;
-
- return `${tableNamePart.replace(aliasName, tableName)}.${rest.join('.')}`;
- }
-
- if (isArray(condition)) {
- return condition.map((where: WhereClause) => {
- return {
- ...where,
- condition: applyTableAliasOnWhereCondition({
- condition: where.condition,
- tableName,
- aliasName,
- }),
- };
- });
- }
-
- if (isObject(condition)) {
- if ('condition' in condition) {
- return {
- ...condition,
- condition: applyTableAliasOnWhereCondition({
- condition: condition.condition,
- tableName,
- aliasName,
- }),
- };
- }
-
- if ('operator' in condition) {
- return condition;
- }
- }
-
- return condition;
-};
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/convert-relation-type-to-typeorm-relation-type.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/convert-relation-type-to-typeorm-relation-type.util.ts
deleted file mode 100644
index cc052ad2598..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/utils/convert-relation-type-to-typeorm-relation-type.util.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';
-
-export const converRelationTypeToTypeORMRelationType = (type: RelationType) => {
- switch (type) {
- case RelationType.ONE_TO_MANY:
- return 'one-to-many';
- case RelationType.MANY_TO_ONE:
- return 'many-to-one';
- default:
- throw new Error(`Invalid relation type: ${type}`);
- }
-};
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/get-default-columns-for-index.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/get-default-columns-for-index.util.ts
deleted file mode 100644
index a2644c07434..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/utils/get-default-columns-for-index.util.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { IndexType } from 'src/engine/metadata-modules/index-metadata/types/indexType.types';
-
-export const getColumnsForIndex = (indexType?: IndexType) => {
- switch (indexType) {
- case IndexType.GIN:
- return [];
- default:
- return ['deletedAt'];
- }
-};
diff --git a/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/utils/__tests__/sanitize-default-value.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/utils/__tests__/sanitize-default-value.util.spec.ts
deleted file mode 100644
index 8af489552f5..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/utils/__tests__/sanitize-default-value.util.spec.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-import { sanitizeDefaultValue } from 'src/engine/twenty-orm/workspace-schema-manager/utils/sanitize-default-value.util';
-
-describe('sanitizeDefaultValue', () => {
- describe('allowed functions', () => {
- it('should allow uuid_generate_v4() function', () => {
- const input = 'public.uuid_generate_v4()';
- const result = sanitizeDefaultValue(input);
-
- expect(result).toBe('public.uuid_generate_v4()');
- });
-
- it('should allow now() function', () => {
- const input = 'now()';
- const result = sanitizeDefaultValue(input);
-
- expect(result).toBe('now()');
- });
-
- it('should be case insensitive for allowed functions', () => {
- expect(sanitizeDefaultValue('NOW()')).toBe('NOW()');
- });
- });
-
- describe('SQL injection prevention via escapeLiteral', () => {
- it('should escape single quotes to prevent SQL injection', () => {
- const maliciousInput = "'; DROP TABLE users; --";
- const result = sanitizeDefaultValue(maliciousInput);
-
- // Single quotes are doubled, making injection impossible
- expect(result).toBe("'''; DROP TABLE users; --'");
- });
-
- it('should preserve double quotes inside string literals (safe in SQL strings)', () => {
- const inputWithQuotes = 'test"value';
- const result = sanitizeDefaultValue(inputWithQuotes);
-
- expect(result).toBe("'test\"value'");
- });
-
- it('should preserve parentheses inside string literals (safe in SQL strings)', () => {
- const inputWithParens = 'test(value)';
- const result = sanitizeDefaultValue(inputWithParens);
-
- expect(result).toBe("'test(value)'");
- });
-
- it('should escape backslashes with E-string syntax', () => {
- const inputWithBackslash = 'test\\value';
- const result = sanitizeDefaultValue(inputWithBackslash);
-
- expect(result).toBe("E'test\\\\value'");
- });
-
- it('should preserve comment-like patterns inside string literals (safe in SQL strings)', () => {
- const inputWithComments = 'value/*comment*/test';
- const result = sanitizeDefaultValue(inputWithComments);
-
- expect(result).toBe("'value/*comment*/test'");
- });
- });
-
- describe('regular values', () => {
- it('should preserve simple string values', () => {
- const input = 'simple_value';
- const result = sanitizeDefaultValue(input);
-
- expect(result).toBe("'simple_value'");
- });
-
- it('should preserve numeric values', () => {
- expect(sanitizeDefaultValue(12345)).toBe(12345);
- });
-
- it('should preserve boolean values', () => {
- expect(sanitizeDefaultValue(true)).toBe(true);
- expect(sanitizeDefaultValue(false)).toBe(false);
- });
-
- it('should handle empty string', () => {
- expect(sanitizeDefaultValue('')).toBe("''");
- });
-
- it('should preserve whitespace in string values', () => {
- const input = ' test ';
- const result = sanitizeDefaultValue(input);
-
- expect(result).toBe("' test '");
- });
-
- it('should preserve alphanumeric values with underscores', () => {
- const input = 'test_value_123';
- const result = sanitizeDefaultValue(input);
-
- expect(result).toBe("'test_value_123'");
- });
- });
-
- describe('mixed cases', () => {
- it('should distinguish between allowed functions and similar strings', () => {
- expect(sanitizeDefaultValue('now()')).toBe('now()');
- expect(sanitizeDefaultValue('now_test')).toBe("'now_test'");
- expect(sanitizeDefaultValue('not_now()')).toBe("'not_now()'");
- });
-
- it('should handle functions with different casing but escape non-functions', () => {
- expect(sanitizeDefaultValue('NOW()')).toBe('NOW()');
- expect(sanitizeDefaultValue('now_function')).toBe("'now_function'");
- });
-
- it('should properly escape complex mixed input', () => {
- const complexInput = 'test"value; DROP TABLE users; /* comment */ now()';
- const result = sanitizeDefaultValue(complexInput);
-
- expect(result).toBe(
- "'test\"value; DROP TABLE users; /* comment */ now()'",
- );
- });
- });
-
- describe('edge cases', () => {
- it('should handle null', () => {
- expect(sanitizeDefaultValue(null)).toBe('NULL');
- });
-
- it('should handle strings that start with allowed function names', () => {
- expect(sanitizeDefaultValue('now_extended')).toBe("'now_extended'");
- expect(sanitizeDefaultValue('gen_random_uuid_custom')).toBe(
- "'gen_random_uuid_custom'",
- );
- });
-
- it('should escape all special characters properly', () => {
- const specialChars = '!@#$%^&*()+=[]{}|\\:";\'<>?,.';
- const result = sanitizeDefaultValue(specialChars);
-
- // Backslash triggers E-string, single quotes are doubled
- expect(result).toContain('E');
- expect(result).toContain("''");
- });
-
- it('should handle very long strings with injection attempts', () => {
- const longString = 'a'.repeat(1000) + "'; DROP TABLE users;";
- const result = sanitizeDefaultValue(longString);
-
- // The single quote in the injection attempt is properly escaped
- expect(result).toBe(`'${'a'.repeat(1000)}''; DROP TABLE users;'`);
- });
- });
-});
diff --git a/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/utils/sanitize-default-value.util.ts b/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/utils/sanitize-default-value.util.ts
deleted file mode 100644
index 607a3972745..00000000000
--- a/packages/twenty-server/src/engine/twenty-orm/workspace-schema-manager/utils/sanitize-default-value.util.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { escapeLiteral } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';
-
-const ALLOWED_DEFAULT_FUNCTIONS = new Set([
- 'public.uuid_generate_v4()',
- 'now()',
-]);
-
-export const sanitizeDefaultValue = (
- defaultValue: string | number | boolean | null,
-): string | number | boolean => {
- if (defaultValue === null) {
- return 'NULL';
- }
-
- if (typeof defaultValue === 'string') {
- if (ALLOWED_DEFAULT_FUNCTIONS.has(defaultValue.toLowerCase())) {
- return defaultValue;
- }
-
- return escapeLiteral(defaultValue);
- }
-
- return defaultValue;
-};
diff --git a/packages/twenty-server/src/utils/typed-reflect.ts b/packages/twenty-server/src/utils/typed-reflect.ts
index 390aed5fc08..b9132d7d8cb 100644
--- a/packages/twenty-server/src/utils/typed-reflect.ts
+++ b/packages/twenty-server/src/utils/typed-reflect.ts
@@ -1,24 +1,10 @@
import 'reflect-metadata';
import { type FeatureFlagKey } from 'twenty-shared/types';
-import { type Gate } from 'src/engine/twenty-orm/interfaces/gate.interface';
-
-import { type WorkspaceEntityDuplicateCriteria } from 'src/engine/api/graphql/workspace-query-builder/types/workspace-entity-duplicate-criteria.type';
import { type ConfigVariablesMetadataMap } from 'src/engine/core-modules/twenty-config/decorators/config-variables-metadata.decorator';
export interface ReflectMetadataTypeMap {
- ['workspace:is-nullable-metadata-args']: true;
- ['workspace:gate-metadata-args']: Gate;
- ['workspace:is-system-metadata-args']: true;
- ['workspace:is-field-ui-readonly-metadata-args']: true;
- ['workspace:is-object-ui-readonly-metadata-args']: true;
- ['workspace:is-audit-logged-metadata-args']: false;
- ['workspace:is-primary-field-metadata-args']: true;
- ['workspace:is-deprecated-field-metadata-args']: true;
- ['workspace:is-unique-metadata-args']: true;
- ['workspace:duplicate-criteria-metadata-args']: WorkspaceEntityDuplicateCriteria[];
['config-variables']: ConfigVariablesMetadataMap;
- ['workspace:is-searchable-metadata-args']: boolean;
['feature-flag-metadata-args']: FeatureFlagKey;
}