Skip to content

The open alternative to Salesforce, designed for AI.

feat(server): add the ORM v2 mutation statement layer (update/delete/soft-delete/restore) (#24118)

Charles Bochetf5a39262605a
diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/README.md b/packages/twenty-server/src/engine/twenty-orm-v2/README.md
index 48224243e5c..fed6b26f65c 100644
--- a/packages/twenty-server/src/engine/twenty-orm-v2/README.md
+++ b/packages/twenty-server/src/engine/twenty-orm-v2/README.md
@@ -20,9 +20,11 @@ framing:
- **The pg driver, not TypeORM, dominates row handling.** In the profile behind #23980,
`parseRow` is 14.6% of slow-request event-loop time and TypeORM entity hydration is 3.0%.
The 14.6% survives removing the ORM, so this is not where the win is.
-- **Writes still need `EntityMetadata`.** Insert and update derive their column list,
- `RETURNING` mapping and `updatedAt` maintenance from it. Bypassing reads shrinks what
- the metadata cache is used for; it does not delete the cache.
+- **Insert and upsert still lean on `EntityMetadata`.** They derive column defaults and
+ the conflict target from it. Update, delete, soft-delete and restore turn out not to:
+ their column list is the caller's data, their `RETURNING` mapping is the same projection
+ the read path builds, and `updatedAt` is a single `CURRENT_TIMESTAMP` rule. Bypassing
+ reads shrinks what the metadata cache is used for; it does not delete the cache.
So v2 has no ORM metadata. `WorkspaceTableShape` is the whole model: table name, schema,
columns, relations, and the composite-column mapping, derived from the flat maps. It is
@@ -35,7 +37,7 @@ per object type rather than thousands, and it can be rebuilt or discarded freely
|---|---|
| `sql/` | named-parameter compiler: `:name` / `:...list` to `$1..$n` |
| `table-shape/` | `WorkspaceTableShape` and its builder from flat field metadata |
-| `query-builder/` | `WorkspaceSelectQueryBuilderV2`, the TypeORM-shaped builder |
+| `query-builder/` | `WorkspaceSelectQueryBuilderV2` and `WorkspaceMutationQueryBuilderV2`, the TypeORM-shaped builders |
| `repository/` | `WorkspaceRepositoryV2`, permissions and result formatting |
| `datasource/` | pool ownership and per-request data source |
| `executor/` | statement execution against a `pg` pool |
@@ -118,12 +120,38 @@ table-shape builder cannot represent. `GroupByWithRecordsV2Service` builds the i
subquery with the v2 builder and runs the composed outer query through
`repository.executeRaw`; the runner flag-branches between it and the v1 service.
+## Writes: the statement layer exists, nothing is wired
+
+`WorkspaceMutationQueryBuilderV2` generates `UPDATE` / `DELETE` / soft-delete / restore
+statements with `RETURNING`, reusing the same primitives as the select builder
+(`quoteColumn`, the shared where renderer, the `mapRowToEntity` decode) plus a `SET`
+generator. The select builder morphs into it: `.update()` / `.delete()` / `.softDelete()`
+/ `.restore()` carry the current where clauses and parameters into the mutation, matching
+the TypeORM surface the mutation runners already call.
+
+Deliberate choices, all asserted by exact-SQL unit tests:
+
+- Statements are alias-form (`UPDATE "schema"."table" AS "person" ... RETURNING
+ "person"."id" AS "person_id"`), so the where renderer and the `RETURNING` projection are
+ the select builder's, unchanged. `execute()` returns `{ generatedMaps, affected }` with
+ `generatedMaps` run through the shared `formatResult`, matching what the v1 mutation
+ builders hand back.
+- A mutation never adds the `deletedAt IS NULL` predicate the read path uses: it operates
+ on exactly the rows its filter matches, so restore reaches soft-deleted rows and delete
+ reaches any row. This mirrors TypeORM, which injects the soft-delete predicate for
+ SELECT only.
+- `updatedAt` is stamped `CURRENT_TIMESTAMP` on every update unless the caller set it;
+ soft-delete stamps `deletedAt` and `updatedAt`; restore clears `deletedAt` and stamps
+ `updatedAt`.
+
+Not wired to any runner yet: the mutation runners keep `repository` (v1) until the
+per-endpoint migrations route them through this builder. Permission enforcement, row-level
+predicates on writes and database event emission ride with that wiring, not this layer.
+
## Not covered yet
-- Writes. Insert, update, delete, soft delete and upsert still go through v1, which is
- where `EntityMetadata` is genuinely used (column list, `RETURNING` mapping, `updatedAt`
- maintenance). Removing it from reads shrinks what the metadata cache is used for; it
- does not delete the cache.
+- Insert and upsert. `INSERT` / `ON CONFLICT` still go through v1, which is where the
+ column defaults and conflict-target derivation live.
- `find` / `findOne` / `findBy` and the rest of the repository surface used by
`src/modules`.
- Transactions and DDL.
diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/exceptions/twenty-orm-v2.exception.ts b/packages/twenty-server/src/engine/twenty-orm-v2/exceptions/twenty-orm-v2.exception.ts
index a0c8c812753..fe3da44c65f 100644
--- a/packages/twenty-server/src/engine/twenty-orm-v2/exceptions/twenty-orm-v2.exception.ts
+++ b/packages/twenty-server/src/engine/twenty-orm-v2/exceptions/twenty-orm-v2.exception.ts
@@ -10,6 +10,7 @@ export enum TwentyOrmV2ExceptionCode {
UNKNOWN_RELATION = 'UNKNOWN_RELATION',
UNSUPPORTED_OPERATION = 'UNSUPPORTED_OPERATION',
MISSING_ALIAS = 'MISSING_ALIAS',
+ INVALID_QUERY = 'INVALID_QUERY',
}
export class TwentyOrmV2Exception extends CustomException<TwentyOrmV2ExceptionCode> {
diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/__tests__/workspace-mutation-query-builder-v2.spec.ts b/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/__tests__/workspace-mutation-query-builder-v2.spec.ts
new file mode 100644
index 00000000000..b071a5b40fa
--- /dev/null
+++ b/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/__tests__/workspace-mutation-query-builder-v2.spec.ts
@@ -0,0 +1,307 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+
+import { RelationType } from 'src/engine/metadata-modules/field-metadata/interfaces/relation-type.interface';
+import { TwentyOrmV2Exception } from 'src/engine/twenty-orm-v2/exceptions/twenty-orm-v2.exception';
+import { type CompiledStatement } from 'src/engine/twenty-orm-v2/sql/utils/compile-named-parameters.util';
+import { WorkspaceSelectQueryBuilderV2 } from 'src/engine/twenty-orm-v2/query-builder/workspace-select-query-builder-v2';
+import { type WorkspaceTableShape } from 'src/engine/twenty-orm-v2/table-shape/types/workspace-table-shape.type';
+
+const SCHEMA_NAME = 'workspace_1wgvd1injqtife6y4rvfbu3h5';
+
+const buildColumn = (
+ columnName: string,
+ compositeParentFieldName?: string,
+) => ({
+ columnName,
+ fieldMetadataId: `field-${columnName}`,
+ fieldName: compositeParentFieldName ?? columnName,
+ fieldMetadataType: FieldMetadataType.TEXT,
+ ...(compositeParentFieldName !== undefined
+ ? { compositeParentFieldName }
+ : {}),
+});
+
+const companyTableShape: WorkspaceTableShape = {
+ objectMetadataId: 'company-object-id',
+ nameSingular: 'company',
+ schemaName: SCHEMA_NAME,
+ tableName: 'company',
+ columnShapeByColumnName: {
+ id: buildColumn('id'),
+ deletedAt: buildColumn('deletedAt'),
+ },
+ columnNames: ['id', 'deletedAt'],
+ relationShapeByFieldName: {},
+ hasDeletedAtColumn: true,
+};
+
+const personTableShape: WorkspaceTableShape = {
+ objectMetadataId: 'person-object-id',
+ nameSingular: 'person',
+ schemaName: SCHEMA_NAME,
+ tableName: 'person',
+ columnShapeByColumnName: {
+ id: buildColumn('id'),
+ nameFirstName: buildColumn('nameFirstName', 'name'),
+ jobTitle: buildColumn('jobTitle'),
+ companyId: buildColumn('companyId'),
+ updatedAt: buildColumn('updatedAt'),
+ deletedAt: buildColumn('deletedAt'),
+ },
+ columnNames: [
+ 'id',
+ 'nameFirstName',
+ 'jobTitle',
+ 'companyId',
+ 'updatedAt',
+ 'deletedAt',
+ ],
+ relationShapeByFieldName: {
+ company: {
+ fieldName: 'company',
+ fieldMetadataId: 'field-company',
+ relationType: RelationType.MANY_TO_ONE,
+ targetObjectMetadataId: 'company-object-id',
+ targetFieldMetadataId: 'field-people',
+ joinColumnName: 'companyId',
+ },
+ },
+ hasDeletedAtColumn: true,
+};
+
+const buildBuilders = ({
+ rows = [],
+}: { rows?: Record<string, unknown>[] } = {}) => {
+ const executedStatements: CompiledStatement[] = [];
+
+ const selectQueryBuilder = new WorkspaceSelectQueryBuilderV2('person', {
+ tableShape: personTableShape,
+ executor: {
+ execute: async (statement) => {
+ executedStatements.push(statement);
+
+ return rows;
+ },
+ },
+ objectRecordsPermissions: {},
+ tableShapeByObjectMetadataId: () => companyTableShape,
+ onBeforeExecute: () => undefined,
+ formatResult: (records) => records as never,
+ });
+
+ return { selectQueryBuilder, executedStatements };
+};
+
+describe('WorkspaceMutationQueryBuilderV2', () => {
+ it('should build a soft delete that stamps deletedAt and updatedAt', () => {
+ const { selectQueryBuilder } = buildBuilders();
+
+ const mutationQueryBuilder = selectQueryBuilder
+ .where('"person"."id" IN (:...ids)', {
+ ids: ['id-1', 'id-2'],
+ })
+ .softDelete()
+ .returning(['id', 'nameFirstName']);
+
+ expect(mutationQueryBuilder.getQuery()).toBe(
+ `UPDATE "${SCHEMA_NAME}"."person" AS "person" ` +
+ 'SET "deletedAt" = CURRENT_TIMESTAMP, "updatedAt" = CURRENT_TIMESTAMP ' +
+ 'WHERE ("person"."id" IN (:...ids)) ' +
+ 'RETURNING "person"."id" AS "person_id", "person"."nameFirstName" AS "person_nameFirstName"',
+ );
+ });
+
+ it('should build a restore that clears deletedAt and stamps updatedAt', () => {
+ const { selectQueryBuilder } = buildBuilders();
+
+ const mutationQueryBuilder = selectQueryBuilder
+ .where('"person"."id" IN (:...ids)', { ids: ['id-1'] })
+ .restore()
+ .returning(['id']);
+
+ expect(mutationQueryBuilder.getQuery()).toBe(
+ `UPDATE "${SCHEMA_NAME}"."person" AS "person" ` +
+ 'SET "deletedAt" = NULL, "updatedAt" = CURRENT_TIMESTAMP ' +
+ 'WHERE ("person"."id" IN (:...ids)) ' +
+ 'RETURNING "person"."id" AS "person_id"',
+ );
+ });
+
+ it('should build a hard delete with no SET clause', () => {
+ const { selectQueryBuilder } = buildBuilders();
+
+ const mutationQueryBuilder = selectQueryBuilder
+ .where('"person"."id" IN (:...ids)', { ids: ['id-1'] })
+ .delete()
+ .returning(['id']);
+
+ expect(mutationQueryBuilder.getQuery()).toBe(
+ `DELETE FROM "${SCHEMA_NAME}"."person" AS "person" ` +
+ 'WHERE ("person"."id" IN (:...ids)) ' +
+ 'RETURNING "person"."id" AS "person_id"',
+ );
+ });
+
+ it('should build an update that binds set values and appends updatedAt maintenance', () => {
+ const { selectQueryBuilder } = buildBuilders();
+
+ const [sql, values] = selectQueryBuilder
+ .where('"person"."id" IN (:...ids)', { ids: ['id-1'] })
+ .update()
+ .set({ jobTitle: 'Tech Lead' })
+ .returning(['id', 'jobTitle'])
+ .getQueryAndParameters();
+
+ expect(sql).toBe(
+ `UPDATE "${SCHEMA_NAME}"."person" AS "person" ` +
+ 'SET "jobTitle" = $1, "updatedAt" = CURRENT_TIMESTAMP ' +
+ 'WHERE ("person"."id" IN ($2)) ' +
+ 'RETURNING "person"."id" AS "person_id", "person"."jobTitle" AS "person_jobTitle"',
+ );
+ expect(values).toEqual(['Tech Lead', 'id-1']);
+ });
+
+ it('should not append updatedAt maintenance when the caller sets updatedAt itself', () => {
+ const { selectQueryBuilder } = buildBuilders();
+
+ const [sql, values] = selectQueryBuilder
+ .where('"person"."id" = :id', { id: 'id-1' })
+ .update()
+ .set({ jobTitle: 'Tech Lead', updatedAt: null })
+ .returning(['id'])
+ .getQueryAndParameters();
+
+ expect(sql).toBe(
+ `UPDATE "${SCHEMA_NAME}"."person" AS "person" ` +
+ 'SET "jobTitle" = $1, "updatedAt" = $2 ' +
+ 'WHERE ("person"."id" = $3) ' +
+ 'RETURNING "person"."id" AS "person_id"',
+ );
+ expect(values).toEqual(['Tech Lead', null, 'id-1']);
+ });
+
+ it('should return formatted rows from execute', async () => {
+ const { selectQueryBuilder, executedStatements } = buildBuilders({
+ rows: [{ person_id: 'id-1' }, { person_id: 'id-2' }],
+ });
+
+ const result = await selectQueryBuilder
+ .where('"person"."id" IN (:...ids)', { ids: ['id-1', 'id-2'] })
+ .softDelete()
+ .returning(['id'])
+ .execute();
+
+ expect(result.generatedMaps).toEqual([{ id: 'id-1' }, { id: 'id-2' }]);
+ expect(executedStatements).toHaveLength(1);
+ expect(executedStatements[0].values).toEqual(['id-1', 'id-2']);
+ });
+
+ it('should not overwrite a where parameter that collides with a set parameter name', () => {
+ const { selectQueryBuilder } = buildBuilders();
+
+ const [, values] = selectQueryBuilder
+ .where('"person"."id" = :ormV2Set_0', { ormV2Set_0: 'id-1' })
+ .update()
+ .set({ jobTitle: 'Tech Lead' })
+ .returning(['id'])
+ .getQueryAndParameters();
+
+ expect(values).toContain('id-1');
+ expect(values).toContain('Tech Lead');
+ });
+
+ it('should reject a soft delete on a table without a deletedAt column', () => {
+ const shapeWithoutDeletedAt: WorkspaceTableShape = {
+ ...personTableShape,
+ columnShapeByColumnName: {
+ id: buildColumn('id'),
+ updatedAt: buildColumn('updatedAt'),
+ },
+ columnNames: ['id', 'updatedAt'],
+ hasDeletedAtColumn: false,
+ };
+
+ const selectQueryBuilder = new WorkspaceSelectQueryBuilderV2('person', {
+ tableShape: shapeWithoutDeletedAt,
+ executor: { execute: async () => [] },
+ objectRecordsPermissions: {},
+ tableShapeByObjectMetadataId: () => companyTableShape,
+ onBeforeExecute: () => undefined,
+ formatResult: (records) => records as never,
+ });
+
+ expect(() =>
+ selectQueryBuilder
+ .where('"person"."id" = :id', { id: 'id-1' })
+ .softDelete()
+ .returning(['id'])
+ .getQuery(),
+ ).toThrow(TwentyOrmV2Exception);
+ });
+
+ it('should reject setting a column that does not exist', () => {
+ const { selectQueryBuilder } = buildBuilders();
+
+ expect(() =>
+ selectQueryBuilder
+ .where('"person"."id" = :id', { id: 'id-1' })
+ .update()
+ .set({ missingColumn: 'x' })
+ .returning(['id'])
+ .getQuery(),
+ ).toThrow(TwentyOrmV2Exception);
+ });
+
+ it('should bump only updatedAt for an update carrying no columns', () => {
+ const { selectQueryBuilder } = buildBuilders();
+
+ expect(
+ selectQueryBuilder
+ .where('"person"."id" = :id', { id: 'id-1' })
+ .update()
+ .returning(['id'])
+ .getQuery(),
+ ).toBe(
+ `UPDATE "${SCHEMA_NAME}"."person" AS "person" ` +
+ 'SET "updatedAt" = CURRENT_TIMESTAMP ' +
+ 'WHERE ("person"."id" = :id) ' +
+ 'RETURNING "person"."id" AS "person_id"',
+ );
+ });
+
+ it('should reject an update that would emit no SET clause', () => {
+ const shapeWithoutUpdatedAt: WorkspaceTableShape = {
+ ...personTableShape,
+ columnShapeByColumnName: {
+ id: buildColumn('id'),
+ deletedAt: buildColumn('deletedAt'),
+ },
+ columnNames: ['id', 'deletedAt'],
+ };
+
+ const selectQueryBuilder = new WorkspaceSelectQueryBuilderV2('person', {
+ tableShape: shapeWithoutUpdatedAt,
+ executor: { execute: async () => [] },
+ objectRecordsPermissions: {},
+ tableShapeByObjectMetadataId: () => companyTableShape,
+ onBeforeExecute: () => undefined,
+ formatResult: (records) => records as never,
+ });
+
+ expect(() =>
+ selectQueryBuilder
+ .where('"person"."id" = :id', { id: 'id-1' })
+ .update()
+ .returning(['id'])
+ .getQuery(),
+ ).toThrow(TwentyOrmV2Exception);
+ });
+
+ it('should refuse to morph a query that carries a relation join', () => {
+ const { selectQueryBuilder } = buildBuilders();
+
+ selectQueryBuilder.leftJoin('person.company', 'company');
+
+ expect(() => selectQueryBuilder.softDelete()).toThrow(TwentyOrmV2Exception);
+ });
+});
diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-mutation-query-builder-v2.ts b/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-mutation-query-builder-v2.ts
new file mode 100644
index 00000000000..e441c9b2f26
--- /dev/null
+++ b/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-mutation-query-builder-v2.ts
@@ -0,0 +1,220 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ TwentyOrmV2Exception,
+ TwentyOrmV2ExceptionCode,
+} from 'src/engine/twenty-orm-v2/exceptions/twenty-orm-v2.exception';
+import { type QueryExecutorV2 } from 'src/engine/twenty-orm-v2/executor/types/query-executor-v2.type';
+import {
+ buildColumnNameByResultAlias,
+ mapRowToEntity,
+ type WhereClause,
+} from 'src/engine/twenty-orm-v2/sql/utils/build-select-statement.util';
+import { compileNamedParameters } from 'src/engine/twenty-orm-v2/sql/utils/compile-named-parameters.util';
+import {
+ buildMutationStatement,
+ type MutationKind,
+ type SetClause,
+} from 'src/engine/twenty-orm-v2/sql/utils/build-mutation-statement.util';
+import { type WorkspaceTableShape } from 'src/engine/twenty-orm-v2/table-shape/types/workspace-table-shape.type';
+
+let mutationSetParameterSequence = 0;
+
+const UPDATED_AT_COLUMN_NAME = 'updatedAt';
+const DELETED_AT_COLUMN_NAME = 'deletedAt';
+
+export type MutationQueryBuilderV2Context = {
+ tableShape: WorkspaceTableShape;
+ executor: QueryExecutorV2;
+ formatResult: <T>(records: unknown) => T;
+};
+
+export type MutationResultV2 = {
+ // oxlint-disable-next-line typescript/no-explicit-any
+ generatedMaps: any[];
+};
+
+export class WorkspaceMutationQueryBuilderV2 {
+ readonly alias: string;
+ readonly tableShape: WorkspaceTableShape;
+
+ private readonly context: MutationQueryBuilderV2Context;
+ private readonly kind: MutationKind;
+ private readonly whereClauses: WhereClause[];
+ private parameters: Record<string, unknown>;
+ private setRecord: Record<string, unknown> = {};
+ private returningColumns: string[] = [];
+
+ constructor({
+ alias,
+ kind,
+ context,
+ whereClauses,
+ parameters,
+ }: {
+ alias: string;
+ kind: MutationKind;
+ context: MutationQueryBuilderV2Context;
+ whereClauses: WhereClause[];
+ parameters: Record<string, unknown>;
+ }) {
+ this.alias = alias;
+ this.kind = kind;
+ this.context = context;
+ this.tableShape = context.tableShape;
+ this.whereClauses = [...whereClauses];
+ this.parameters = { ...parameters };
+ }
+
+ set(record: Record<string, unknown>): this {
+ this.setRecord = record;
+
+ return this;
+ }
+
+ returning(columns: string[]): this {
+ this.returningColumns = columns;
+
+ return this;
+ }
+
+ getQueryAndParameters(): [string, unknown[]] {
+ const { sql, parameters } = this.buildStatement();
+ const compiled = compileNamedParameters(sql, parameters);
+
+ return [compiled.text, compiled.values];
+ }
+
+ getQuery(): string {
+ return this.buildStatement().sql;
+ }
+
+ async execute(): Promise<MutationResultV2> {
+ const { sql, parameters } = this.buildStatement();
+ const compiled = compileNamedParameters(sql, parameters);
+ const rows = await this.context.executor.execute(compiled);
+
+ const columnNameByResultAlias = buildColumnNameByResultAlias(
+ this.alias,
+ this.returningColumns,
+ );
+ const entities = rows.map((row) =>
+ mapRowToEntity(row, columnNameByResultAlias),
+ );
+
+ return {
+ generatedMaps: this.context.formatResult(entities),
+ };
+ }
+
+ private buildStatement(): {
+ sql: string;
+ parameters: Record<string, unknown>;
+ } {
+ const parameters = { ...this.parameters };
+ const setClauses = this.buildSetClauses(parameters);
+
+ const sql = buildMutationStatement({
+ alias: this.alias,
+ tableShape: this.tableShape,
+ kind: this.kind,
+ setClauses,
+ whereClauses: this.whereClauses,
+ returningColumns: this.returningColumns,
+ });
+
+ return { sql, parameters };
+ }
+
+ private buildSetClauses(parameters: Record<string, unknown>): SetClause[] {
+ if (this.kind === 'delete') {
+ return [];
+ }
+
+ if (this.kind === 'soft-delete') {
+ this.assertDeletedAtColumnExists();
+
+ return this.withUpdatedAtMaintenance([
+ {
+ columnName: DELETED_AT_COLUMN_NAME,
+ valueExpression: 'CURRENT_TIMESTAMP',
+ },
+ ]);
+ }
+
+ if (this.kind === 'restore') {
+ this.assertDeletedAtColumnExists();
+
+ return this.withUpdatedAtMaintenance([
+ { columnName: DELETED_AT_COLUMN_NAME, valueExpression: 'NULL' },
+ ]);
+ }
+
+ const setClauses: SetClause[] = [];
+
+ for (const [columnName, value] of Object.entries(this.setRecord)) {
+ this.assertColumnExists(columnName);
+
+ if (typeof value === 'function') {
+ throw new TwentyOrmV2Exception(
+ `Function-valued updates are not supported on "${columnName}"`,
+ TwentyOrmV2ExceptionCode.UNSUPPORTED_OPERATION,
+ );
+ }
+
+ let parameterName = `ormV2Set_${mutationSetParameterSequence++}`;
+
+ while (parameterName in parameters) {
+ parameterName = `ormV2Set_${mutationSetParameterSequence++}`;
+ }
+
+ parameters[parameterName] = value;
+ setClauses.push({ columnName, valueExpression: `:${parameterName}` });
+ }
+
+ const callerSetUpdatedAt = Object.prototype.hasOwnProperty.call(
+ this.setRecord,
+ UPDATED_AT_COLUMN_NAME,
+ );
+
+ return callerSetUpdatedAt
+ ? setClauses
+ : this.withUpdatedAtMaintenance(setClauses);
+ }
+
+ private withUpdatedAtMaintenance(setClauses: SetClause[]): SetClause[] {
+ if (
+ !isDefined(
+ this.tableShape.columnShapeByColumnName[UPDATED_AT_COLUMN_NAME],
+ )
+ ) {
+ return setClauses;
+ }
+
+ return [
+ ...setClauses,
+ {
+ columnName: UPDATED_AT_COLUMN_NAME,
+ valueExpression: 'CURRENT_TIMESTAMP',
+ },
+ ];
+ }
+
+ private assertDeletedAtColumnExists(): void {
+ if (!this.tableShape.hasDeletedAtColumn) {
+ throw new TwentyOrmV2Exception(
+ `"${this.tableShape.nameSingular}" has no "${DELETED_AT_COLUMN_NAME}" column, so it cannot be soft-deleted or restored`,
+ TwentyOrmV2ExceptionCode.UNSUPPORTED_OPERATION,
+ );
+ }
+ }
+
+ private assertColumnExists(columnName: string): void {
+ if (!isDefined(this.tableShape.columnShapeByColumnName[columnName])) {
+ throw new TwentyOrmV2Exception(
+ `Column "${columnName}" does not exist on "${this.tableShape.nameSingular}"`,
+ TwentyOrmV2ExceptionCode.UNKNOWN_COLUMN,
+ );
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-select-query-builder-v2.ts b/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-select-query-builder-v2.ts
index 8fc3af3adcd..a437bbdfc26 100644
--- a/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-select-query-builder-v2.ts
+++ b/packages/twenty-server/src/engine/twenty-orm-v2/query-builder/workspace-select-query-builder-v2.ts
@@ -20,6 +20,8 @@ import {
isObjectWhereLike,
isWhereFactoryLike,
} from 'src/engine/twenty-orm-v2/query-builder/types/query-builder-v2.type';
+import { WorkspaceMutationQueryBuilderV2 } from 'src/engine/twenty-orm-v2/query-builder/workspace-mutation-query-builder-v2';
+import { type MutationKind } from 'src/engine/twenty-orm-v2/sql/utils/build-mutation-statement.util';
import { buildOrderByClauses } from 'src/engine/twenty-orm-v2/sql/utils/build-order-by-clauses.util';
import { collectReferencedColumnNames } from 'src/engine/twenty-orm-v2/sql/utils/collect-referenced-column-names.util';
import { compileNamedParameters } from 'src/engine/twenty-orm-v2/sql/utils/compile-named-parameters.util';
@@ -448,6 +450,45 @@ export class WorkspaceSelectQueryBuilderV2 implements WhereExpressionLike {
return this.getReferencedColumnNamesByAlias()[this.alias] ?? [];
}
+ update(): WorkspaceMutationQueryBuilderV2 {
+ return this.toMutationQueryBuilder('update');
+ }
+
+ delete(): WorkspaceMutationQueryBuilderV2 {
+ return this.toMutationQueryBuilder('delete');
+ }
+
+ softDelete(): WorkspaceMutationQueryBuilderV2 {
+ return this.toMutationQueryBuilder('soft-delete');
+ }
+
+ restore(): WorkspaceMutationQueryBuilderV2 {
+ return this.toMutationQueryBuilder('restore');
+ }
+
+ private toMutationQueryBuilder(
+ kind: MutationKind,
+ ): WorkspaceMutationQueryBuilderV2 {
+ if (this.joinClauses.length > 0) {
+ throw new TwentyOrmV2Exception(
+ `A mutation cannot carry a relation join; rewrite the filter as an "id IN (subquery)" predicate first`,
+ TwentyOrmV2ExceptionCode.UNSUPPORTED_OPERATION,
+ );
+ }
+
+ return new WorkspaceMutationQueryBuilderV2({
+ alias: this.alias,
+ kind,
+ context: {
+ tableShape: this.tableShape,
+ executor: this.context.executor,
+ formatResult: this.context.formatResult,
+ },
+ whereClauses: this.whereClauses,
+ parameters: this.parameters,
+ });
+ }
+
private appendWhere(
operator: 'and' | 'or',
condition: WhereConditionLike,
diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/__tests__/sql-injection-invariants.spec.ts b/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/__tests__/sql-injection-invariants.spec.ts
index ab532dd3a1a..eb018b227a3 100644
--- a/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/__tests__/sql-injection-invariants.spec.ts
+++ b/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/__tests__/sql-injection-invariants.spec.ts
@@ -102,6 +102,39 @@ describe('ORM v2 SQL injection invariants', () => {
});
});
+ describe('write values', () => {
+ it.each(HOSTILE_VALUES)(
+ 'should bind %j written through a SET clause instead of inlining it',
+ (hostileValue) => {
+ const queryBuilder = buildQueryBuilder(['id', 'name', 'deletedAt']);
+
+ const [text, values] = queryBuilder
+ .where('"person"."id" = :id', { id: 'id-1' })
+ .update()
+ .set({ name: hostileValue })
+ .returning(['id'])
+ .getQueryAndParameters();
+
+ expect(text).not.toContain(hostileValue);
+ expect(text).toContain('$1');
+ expect(values).toContain(hostileValue);
+ },
+ );
+
+ it('should reject a SET column whose name did not come from the table shape', () => {
+ const queryBuilder = buildQueryBuilder(['id', 'name', 'deletedAt']);
+
+ expect(() =>
+ queryBuilder
+ .where('"person"."id" = :id', { id: 'id-1' })
+ .update()
+ .set({ "name\" = ''); DROP TABLE person; --": 'x' })
+ .returning(['id'])
+ .getQuery(),
+ ).toThrow('does not exist on');
+ });
+ });
+
describe('identifiers', () => {
it.each(HOSTILE_IDENTIFIERS)(
'should keep %j inside one quoted identifier',
diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/build-mutation-statement.util.ts b/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/build-mutation-statement.util.ts
new file mode 100644
index 00000000000..3eeb23f26a7
--- /dev/null
+++ b/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/build-mutation-statement.util.ts
@@ -0,0 +1,89 @@
+import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';
+import {
+ TwentyOrmV2Exception,
+ TwentyOrmV2ExceptionCode,
+} from 'src/engine/twenty-orm-v2/exceptions/twenty-orm-v2.exception';
+import { buildColumnResultAlias } from 'src/engine/twenty-orm-v2/sql/utils/build-column-result-alias.util';
+import {
+ quoteColumn,
+ renderUserWhereExpression,
+ type WhereClause,
+} from 'src/engine/twenty-orm-v2/sql/utils/build-select-statement.util';
+import { type WorkspaceTableShape } from 'src/engine/twenty-orm-v2/table-shape/types/workspace-table-shape.type';
+
+export type MutationKind = 'update' | 'delete' | 'soft-delete' | 'restore';
+
+export type SetClause = {
+ columnName: string;
+ valueExpression: string;
+};
+
+export type MutationStatementState = {
+ alias: string;
+ tableShape: WorkspaceTableShape;
+ kind: MutationKind;
+ setClauses: SetClause[];
+ whereClauses: WhereClause[];
+ returningColumns: string[];
+};
+
+const buildReturningClause = (state: MutationStatementState): string => {
+ if (state.returningColumns.length === 0) {
+ return '';
+ }
+
+ const expressions = state.returningColumns.map(
+ (columnName) =>
+ `${quoteColumn(state.alias, columnName)} AS ${escapeIdentifier(
+ buildColumnResultAlias(state.alias, columnName),
+ )}`,
+ );
+
+ return `RETURNING ${expressions.join(', ')}`;
+};
+
+const buildTableReference = (state: MutationStatementState): string =>
+ `${escapeIdentifier(state.tableShape.schemaName)}.${escapeIdentifier(
+ state.tableShape.tableName,
+ )} AS ${escapeIdentifier(state.alias)}`;
+
+const buildSetClause = (state: MutationStatementState): string =>
+ `SET ${state.setClauses
+ .map(
+ (setClause) =>
+ `${escapeIdentifier(setClause.columnName)} = ${setClause.valueExpression}`,
+ )
+ .join(', ')}`;
+
+export const buildMutationStatement = (
+ state: MutationStatementState,
+): string => {
+ const whereExpression = renderUserWhereExpression(state.whereClauses);
+ const returningClause = buildReturningClause(state);
+
+ if (state.kind === 'delete') {
+ return [
+ `DELETE FROM ${buildTableReference(state)}`,
+ whereExpression.length > 0 ? `WHERE ${whereExpression}` : '',
+ returningClause,
+ ]
+ .filter((part) => part.length > 0)
+ .join(' ');
+ }
+
+ if (state.setClauses.length === 0) {
+ throw new TwentyOrmV2Exception(
+ `An UPDATE on "${state.tableShape.nameSingular}" needs at least one column to set`,
+ TwentyOrmV2ExceptionCode.INVALID_QUERY,
+ );
+ }
+
+ return [
+ `UPDATE ${buildTableReference(state)}`,
+ buildSetClause(state),
+ whereExpression.length > 0 ? `WHERE ${whereExpression}` : '',
+ returningClause,
+ ]
+ .filter((part) => part.length > 0)
+ .join(' ');
+};
diff --git a/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/build-select-statement.util.ts b/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/build-select-statement.util.ts
index 4198ae0718d..af66061ec73 100644
--- a/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/build-select-statement.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm-v2/sql/utils/build-select-statement.util.ts
@@ -108,13 +108,10 @@ export const buildProjection = (
return { expressions, mainAliasColumnNames };
};
-export const buildWhereExpression = (
- state: SelectStatementState,
- {
- includeSoftDeletePredicate = true,
- }: { includeSoftDeletePredicate?: boolean } = {},
-): string => {
- const userExpression = state.whereClauses
+export const renderUserWhereExpression = (
+ whereClauses: WhereClause[],
+): string =>
+ whereClauses
.map((clause, index) =>
index === 0
? clause.sql
@@ -122,6 +119,14 @@ export const buildWhereExpression = (
)
.join(' ');
+export const buildWhereExpression = (
+ state: SelectStatementState,
+ {
+ includeSoftDeletePredicate = true,
+ }: { includeSoftDeletePredicate?: boolean } = {},
+): string => {
+ const userExpression = renderUserWhereExpression(state.whereClauses);
+
const shouldAddSoftDeletePredicate =
includeSoftDeletePredicate &&
!state.includeDeleted &&