-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathfield-open-api.service.ts
More file actions
1710 lines (1500 loc) · 56.7 KB
/
field-open-api.service.ts
File metadata and controls
1710 lines (1500 loc) · 56.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable sonarjs/cognitive-complexity */
/* eslint-disable @typescript-eslint/naming-convention */
import { BadRequestException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import {
CellValueType,
FieldKeyType,
FieldOpBuilder,
FieldType,
generateFieldId,
generateOperationId,
IFieldRo,
StatisticsFunc,
isRollupFunctionSupportedForCellValueType,
isLinkLookupOptions,
isFieldReferenceValue,
isFieldReferenceComparable,
extractFieldIdsFromFilter,
} from '@teable/core';
import type {
IColumn,
IFieldVo,
IConvertFieldRo,
IUpdateFieldRo,
IOtOperation,
IColumnMeta,
ILinkFieldOptions,
IConditionalRollupFieldOptions,
IConditionalLookupOptions,
IRollupFieldOptions,
IGetFieldsQuery,
IFilter,
IFilterItem,
IFieldReferenceValue,
} from '@teable/core';
import { PrismaService } from '@teable/db-main-prisma';
import type { IDuplicateFieldRo } from '@teable/openapi';
import { instanceToPlain } from 'class-transformer';
import { Knex } from 'knex';
import { groupBy, isEqual, omit, pick } from 'lodash';
import { InjectModel } from 'nest-knexjs';
import { ClsService } from 'nestjs-cls';
import { ThresholdConfig, IThresholdConfig } from '../../../configs/threshold.config';
import { FieldReferenceCompatibilityException } from '../../../db-provider/filter-query/cell-value-filter.abstract';
import { EventEmitterService } from '../../../event-emitter/event-emitter.service';
import { Events } from '../../../event-emitter/events';
import type { IClsStore } from '../../../types/cls';
import { Timing } from '../../../utils/timing';
import { FieldCalculationService } from '../../calculation/field-calculation.service';
import type { IOpsMap } from '../../calculation/utils/compose-maps';
import { GraphService } from '../../graph/graph.service';
import { ComputedOrchestratorService } from '../../record/computed/services/computed-orchestrator.service';
import { RecordOpenApiService } from '../../record/open-api/record-open-api.service';
import { InjectRecordQueryBuilder, IRecordQueryBuilder } from '../../record/query-builder';
import { RecordService } from '../../record/record.service';
import { TableIndexService } from '../../table/table-index.service';
import { ViewOpenApiService } from '../../view/open-api/view-open-api.service';
import { ViewService } from '../../view/view.service';
import { FieldConvertingService } from '../field-calculate/field-converting.service';
import { FieldCreatingService } from '../field-calculate/field-creating.service';
import { FieldDeletingService } from '../field-calculate/field-deleting.service';
import { FieldSupplementService } from '../field-calculate/field-supplement.service';
import { FieldViewSyncService } from '../field-calculate/field-view-sync.service';
import { FieldService } from '../field.service';
import type { IFieldInstance } from '../model/factory';
import {
convertFieldInstanceToFieldVo,
createFieldInstanceByRaw,
createFieldInstanceByVo,
rawField2FieldObj,
} from '../model/factory';
@Injectable()
export class FieldOpenApiService {
private logger = new Logger(FieldOpenApiService.name);
constructor(
private readonly graphService: GraphService,
private readonly prismaService: PrismaService,
private readonly fieldService: FieldService,
private readonly viewService: ViewService,
private readonly viewOpenApiService: ViewOpenApiService,
private readonly fieldCreatingService: FieldCreatingService,
private readonly fieldDeletingService: FieldDeletingService,
private readonly fieldConvertingService: FieldConvertingService,
private readonly fieldSupplementService: FieldSupplementService,
private readonly fieldCalculationService: FieldCalculationService,
private readonly fieldViewSyncService: FieldViewSyncService,
private readonly recordService: RecordService,
private readonly eventEmitterService: EventEmitterService,
private readonly cls: ClsService<IClsStore>,
private readonly tableIndexService: TableIndexService,
private readonly recordOpenApiService: RecordOpenApiService,
@InjectModel('CUSTOM_KNEX') private readonly knex: Knex,
@ThresholdConfig() private readonly thresholdConfig: IThresholdConfig,
@InjectRecordQueryBuilder() private readonly recordQueryBuilder: IRecordQueryBuilder,
private readonly computedOrchestrator: ComputedOrchestratorService
) {}
async planField(tableId: string, fieldId: string) {
return await this.graphService.planField(tableId, fieldId);
}
private isFieldReferenceCompatibilityError(
error: unknown
): error is FieldReferenceCompatibilityException {
return error instanceof FieldReferenceCompatibilityException;
}
async planFieldCreate(tableId: string, fieldRo: IFieldRo) {
return await this.graphService.planFieldCreate(tableId, fieldRo);
}
// need add delete relative check
async planFieldConvert(tableId: string, fieldId: string, updateFieldRo: IConvertFieldRo) {
return await this.graphService.planFieldConvert(tableId, fieldId, updateFieldRo);
}
async planDeleteField(tableId: string, fieldId: string) {
return await this.graphService.planDeleteField(tableId, fieldId);
}
async getFields(tableId: string, query: IGetFieldsQuery) {
return await this.fieldService.getFieldsByQuery(tableId, {
...query,
filterHidden: query.filterHidden == null ? true : query.filterHidden,
});
}
private async validateLookupField(field: IFieldInstance) {
if (field.lookupOptions && isLinkLookupOptions(field.lookupOptions)) {
const { foreignTableId, lookupFieldId, linkFieldId } = field.lookupOptions;
const foreignField = await this.prismaService.txClient().field.findFirst({
where: { tableId: foreignTableId, id: lookupFieldId, deletedTime: null },
select: { id: true },
});
if (!foreignField) {
return false;
}
const linkField = await this.prismaService.txClient().field.findFirst({
where: { id: linkFieldId, deletedTime: null },
select: { id: true, options: true, type: true, isLookup: true },
});
if (!linkField || linkField.type !== FieldType.Link || linkField.isLookup) {
return false;
}
const linkOptions = JSON.parse(linkField?.options as string) as ILinkFieldOptions;
return linkOptions.foreignTableId === foreignTableId;
}
return true;
}
private normalizeCellValueType(rawCellType: unknown): CellValueType {
if (
typeof rawCellType === 'string' &&
Object.values(CellValueType).includes(rawCellType as CellValueType)
) {
return rawCellType as CellValueType;
}
return CellValueType.String;
}
private async isRollupAggregationSupported(params: {
expression?: IRollupFieldOptions['expression'];
lookupFieldId?: string;
foreignTableId?: string;
}): Promise<boolean> {
const { expression, lookupFieldId, foreignTableId } = params;
if (!expression || !lookupFieldId || !foreignTableId) {
return false;
}
const foreignField = await this.prismaService.txClient().field.findFirst({
where: { id: lookupFieldId, tableId: foreignTableId, deletedTime: null },
select: { cellValueType: true },
});
if (!foreignField?.cellValueType) {
return false;
}
const cellValueType = this.normalizeCellValueType(foreignField.cellValueType);
return isRollupFunctionSupportedForCellValueType(expression, cellValueType);
}
private async validateRollupAggregation(field: IFieldInstance): Promise<boolean> {
if (!field.lookupOptions || !isLinkLookupOptions(field.lookupOptions)) {
return false;
}
const options = field.options as IRollupFieldOptions | undefined;
return this.isRollupAggregationSupported({
expression: options?.expression,
lookupFieldId: field.lookupOptions.lookupFieldId,
foreignTableId: field.lookupOptions.foreignTableId,
});
}
private async validateConditionalRollupAggregation(hostTableId: string, field: IFieldInstance) {
const options = field.options as IConditionalRollupFieldOptions | undefined;
const expression = options?.expression;
const lookupFieldId = options?.lookupFieldId;
const foreignTableId = options?.foreignTableId;
const aggregationSupported = await this.isRollupAggregationSupported({
expression,
lookupFieldId,
foreignTableId,
});
if (!aggregationSupported) {
return false;
}
if (!foreignTableId) {
return false;
}
return await this.validateFilterFieldReferences(hostTableId, foreignTableId, options?.filter);
}
private async validateConditionalLookup(tableId: string, field: IFieldInstance) {
const meta = field.getConditionalLookupOptions?.();
const lookupFieldId = meta?.lookupFieldId;
const foreignTableId = meta?.foreignTableId;
if (!lookupFieldId || !foreignTableId) {
return false;
}
const foreignField = await this.prismaService.txClient().field.findFirst({
where: { id: lookupFieldId, tableId: foreignTableId, deletedTime: null },
select: { id: true, type: true },
});
if (!foreignField) {
return false;
}
if (foreignField.type !== field.type) {
return false;
}
return await this.validateFilterFieldReferences(tableId, foreignTableId, meta?.filter);
}
private async isFieldConfigurationValid(
tableId: string,
field: IFieldInstance
): Promise<boolean> {
if (
field.lookupOptions &&
field.type !== FieldType.ConditionalRollup &&
!field.isConditionalLookup
) {
const lookupValid = await this.validateLookupField(field);
if (!lookupValid) {
return false;
}
if (field.type === FieldType.Rollup) {
return await this.validateRollupAggregation(field);
}
return true;
}
if (field.isConditionalLookup) {
return await this.validateConditionalLookup(tableId, field);
}
if (field.type === FieldType.ConditionalRollup) {
return await this.validateConditionalRollupAggregation(tableId, field);
}
return true;
}
private async findConditionalFilterDependentFields(startFieldIds: readonly string[]): Promise<
Array<{
id: string;
tableId: string;
type: string;
options: string | null;
lookupOptions: string | null;
isConditionalLookup: boolean;
}>
> {
if (!startFieldIds.length) {
return [];
}
const nonRecursive = this.knex
.select('from_field_id', 'to_field_id')
.from('reference')
.whereIn('from_field_id', startFieldIds);
const recursive = this.knex
.select({ from_field_id: 'r.from_field_id', to_field_id: 'r.to_field_id' })
.from({ r: 'reference' })
.join({ d: 'dep' }, 'r.from_field_id', 'd.to_field_id');
const query = this.knex
.withRecursive('dep', ['from_field_id', 'to_field_id'], nonRecursive.union(recursive))
.select({
id: 'f.id',
table_id: 'f.table_id',
type: 'f.type',
options: 'f.options',
lookup_options: 'f.lookup_options',
is_conditional_lookup: 'f.is_conditional_lookup',
})
.from({ dep: 'dep' })
.join({ f: 'field' }, 'dep.to_field_id', 'f.id')
.whereNull('f.deleted_time')
.andWhere((qb) =>
qb.where('f.type', FieldType.ConditionalRollup).orWhere('f.is_conditional_lookup', true)
)
.distinct();
const rows = await this.prismaService.txClient().$queryRawUnsafe<
Array<{
id: string;
table_id: string;
type: string;
options: string | null;
lookup_options: string | null;
is_conditional_lookup: number | boolean | null;
}>
>(query.toQuery());
return rows.map((row) => ({
id: row.id,
tableId: row.table_id,
type: row.type,
options: row.options,
lookupOptions: row.lookup_options,
isConditionalLookup: Boolean(row.is_conditional_lookup),
}));
}
// eslint-disable-next-line sonarjs/cognitive-complexity
private async syncConditionalFiltersByFieldChanges(
newField: IFieldInstance,
oldField: IFieldInstance
) {
const fieldId = newField.id;
if (!fieldId) {
return;
}
const selectTypes = new Set([FieldType.SingleSelect, FieldType.MultipleSelect]);
if (newField.type !== oldField.type || !selectTypes.has(newField.type)) {
return;
}
const dependents = await this.findConditionalFilterDependentFields([fieldId]);
if (!dependents.length) {
return;
}
const pendingOps: Record<string, { fieldId: string; ops: IOtOperation[] }[]> = {};
const enqueueFieldOps = (tableId: string, fieldId: string, ops: IOtOperation[]) => {
if (!ops.length) return;
(pendingOps[tableId] ||= []).push({ fieldId, ops });
};
const normalizeFilter = (filter: IFilter | null | undefined) =>
filter && filter.filterSet?.length ? filter : null;
for (const field of dependents) {
if (field.type === FieldType.ConditionalRollup) {
if (!field.options) continue;
let options: IConditionalRollupFieldOptions;
try {
options = JSON.parse(field.options) as IConditionalRollupFieldOptions;
} catch {
continue;
}
const originalFilter = options.filter;
if (!originalFilter) continue;
const filterRefs = extractFieldIdsFromFilter(originalFilter, true);
if (!filterRefs.includes(fieldId)) continue;
const updatedFilter = this.fieldViewSyncService.getNewFilterByFieldChanges(
originalFilter,
newField,
oldField
);
const normalizedOriginal = normalizeFilter(originalFilter);
const normalizedUpdated = normalizeFilter(updatedFilter);
if (isEqual(normalizedOriginal, normalizedUpdated)) continue;
const ops = [
FieldOpBuilder.editor.setFieldProperty.build({
key: 'options',
oldValue: options,
newValue: { ...options, filter: normalizedUpdated },
}),
];
enqueueFieldOps(field.tableId, field.id, ops);
continue;
}
if (!field.isConditionalLookup) continue;
if (!field.lookupOptions) continue;
let lookupOptions: IConditionalLookupOptions;
try {
lookupOptions = JSON.parse(field.lookupOptions) as IConditionalLookupOptions;
} catch {
continue;
}
const originalFilter = lookupOptions.filter;
if (!originalFilter) continue;
const filterRefs = extractFieldIdsFromFilter(originalFilter, true);
if (!filterRefs.includes(fieldId)) continue;
const updatedFilter = this.fieldViewSyncService.getNewFilterByFieldChanges(
originalFilter,
newField,
oldField
);
const normalizedOriginal = normalizeFilter(originalFilter);
const normalizedUpdated = normalizeFilter(updatedFilter);
if (isEqual(normalizedOriginal, normalizedUpdated)) continue;
const ops = [
FieldOpBuilder.editor.setFieldProperty.build({
key: 'lookupOptions',
oldValue: lookupOptions,
newValue: { ...lookupOptions, filter: normalizedUpdated },
}),
];
enqueueFieldOps(field.tableId, field.id, ops);
}
for (const [targetTableId, ops] of Object.entries(pendingOps)) {
await this.fieldService.batchUpdateFields(targetTableId, ops);
}
}
private async validateFilterFieldReferences(
hostTableId: string,
foreignTableId: string,
filter?: IFilter | null
): Promise<boolean> {
if (!filter) {
return true;
}
const foreignFieldIds = new Set<string>();
const referenceFieldIds = new Set<string>();
const collectFieldIds = (node: IFilter | IFilterItem) => {
if (!node) {
return;
}
if ('fieldId' in node) {
foreignFieldIds.add(node.fieldId);
const { value } = node;
if (isFieldReferenceValue(value)) {
referenceFieldIds.add(value.fieldId);
} else if (Array.isArray(value)) {
for (const entry of value) {
if (isFieldReferenceValue(entry)) {
referenceFieldIds.add(entry.fieldId);
}
}
}
} else if ('filterSet' in node) {
node.filterSet.forEach((child) => collectFieldIds(child));
}
};
collectFieldIds(filter);
if (!referenceFieldIds.size) {
return true;
}
const fieldIdsToFetch = Array.from(new Set([...foreignFieldIds, ...referenceFieldIds]));
if (!fieldIdsToFetch.length) {
return true;
}
const rawFields = await this.prismaService.txClient().field.findMany({
where: { id: { in: fieldIdsToFetch }, deletedTime: null },
});
const instanceMap = new Map<string, IFieldInstance>();
const hostFields = new Map<string, IFieldInstance>();
const foreignFields = new Map<string, IFieldInstance>();
for (const raw of rawFields) {
const instance = createFieldInstanceByRaw(raw);
instanceMap.set(raw.id, instance);
if (raw.tableId === hostTableId) {
hostFields.set(raw.id, instance);
}
if (raw.tableId === foreignTableId) {
foreignFields.set(raw.id, instance);
}
}
const resolveReferenceField = (reference: IFieldReferenceValue): IFieldInstance | undefined => {
if (reference.tableId) {
if (reference.tableId === hostTableId) {
return hostFields.get(reference.fieldId);
}
if (reference.tableId === foreignTableId) {
return foreignFields.get(reference.fieldId);
}
}
return (
hostFields.get(reference.fieldId) ??
foreignFields.get(reference.fieldId) ??
instanceMap.get(reference.fieldId)
);
};
// eslint-disable-next-line sonarjs/cognitive-complexity
const validateNode = (node: IFilter | IFilterItem): boolean => {
if (!node) {
return true;
}
if ('fieldId' in node) {
const baseField = foreignFields.get(node.fieldId) ?? instanceMap.get(node.fieldId);
if (!baseField) {
return false;
}
const references: IFieldReferenceValue[] = [];
const { value } = node;
if (isFieldReferenceValue(value)) {
references.push(value);
} else if (Array.isArray(value)) {
for (const entry of value) {
if (isFieldReferenceValue(entry)) {
references.push(entry);
}
}
}
return references.every((reference) => {
const referenceField = resolveReferenceField(reference);
if (!referenceField) {
return false;
}
return isFieldReferenceComparable(baseField, referenceField);
});
}
if ('filterSet' in node) {
return node.filterSet.every((child) => validateNode(child));
}
return true;
};
return validateNode(filter);
}
private async markError(tableId: string, field: IFieldInstance, hasError: boolean) {
if (hasError) {
if (!field.hasError) {
await this.fieldService.markError(tableId, [field.id], true);
}
} else {
if (field.hasError) {
await this.fieldService.markError(tableId, [field.id], false);
}
}
}
private async checkAndUpdateError(tableId: string, field: IFieldInstance) {
const fieldReferenceIds = this.fieldSupplementService.getFieldReferenceIds(field);
// Deduplicate field IDs since the same field can appear multiple times
// (e.g., as lookupFieldId and in filter)
const uniqueFieldReferenceIds = [...new Set(fieldReferenceIds)];
const refFields = await this.prismaService.txClient().field.findMany({
where: { id: { in: uniqueFieldReferenceIds }, deletedTime: null },
select: { id: true },
});
if (refFields.length !== uniqueFieldReferenceIds.length) {
await this.markError(tableId, field, true);
return;
}
const curReference = await this.prismaService.txClient().reference.findMany({
where: {
toFieldId: field.id,
},
});
const missingReferenceIds = uniqueFieldReferenceIds.filter(
(refId) => !curReference.find((ref) => ref.fromFieldId === refId)
);
if (missingReferenceIds.length) {
await this.prismaService.txClient().reference.createMany({
data: missingReferenceIds.map((fromFieldId) => ({
fromFieldId,
toFieldId: field.id,
})),
skipDuplicates: true,
});
}
const isValid = await this.isFieldConfigurationValid(tableId, field);
await this.markError(tableId, field, !isValid);
}
async restoreReference(references: string[]) {
const fieldRaws = await this.prismaService.txClient().field.findMany({
where: { id: { in: references }, deletedTime: null },
});
for (const refFieldRaw of fieldRaws) {
const refField = createFieldInstanceByRaw(refFieldRaw);
await this.checkAndUpdateError(refFieldRaw.tableId, refField);
}
}
private sortCreateFieldsByDependencies<
T extends IFieldVo & { columnMeta?: IColumnMeta; references?: string[] },
>(tableId: string, fields: T[]): T[] {
if (!fields.length) return fields;
const idSet = new Set(fields.map((f) => f.id));
const originalIndex = fields.reduce<Record<string, number>>((acc, field, index) => {
acc[field.id] = index;
return acc;
}, {});
const depsByFieldId = new Map<string, string[]>();
for (const field of fields) {
const { columnMeta: _columnMeta, references: _references, ...fieldVo } = field;
try {
const instance = createFieldInstanceByVo(fieldVo);
const deps = this.fieldSupplementService
.getFieldReferenceIds(instance)
.filter((id): id is string => typeof id === 'string' && idSet.has(id) && id !== field.id);
depsByFieldId.set(field.id, deps);
} catch (e) {
this.logger.warn(
`createFields: failed to resolve dependencies for ${field.id} in ${tableId}: ${String(e)}`
);
return fields;
}
}
const indegree = new Map<string, number>();
const outgoing = new Map<string, string[]>();
for (const field of fields) {
indegree.set(field.id, 0);
outgoing.set(field.id, []);
}
for (const field of fields) {
const deps = depsByFieldId.get(field.id) ?? [];
for (const depId of deps) {
outgoing.get(depId)?.push(field.id);
indegree.set(field.id, (indegree.get(field.id) ?? 0) + 1);
}
}
const ready: string[] = [];
for (const field of fields) {
if ((indegree.get(field.id) ?? 0) === 0) ready.push(field.id);
}
ready.sort((a, b) => (originalIndex[a] ?? 0) - (originalIndex[b] ?? 0));
const orderedIds: string[] = [];
while (ready.length) {
const current = ready.shift()!;
orderedIds.push(current);
for (const next of outgoing.get(current) ?? []) {
const nextDegree = (indegree.get(next) ?? 0) - 1;
indegree.set(next, nextDegree);
if (nextDegree === 0) {
ready.push(next);
ready.sort((a, b) => (originalIndex[a] ?? 0) - (originalIndex[b] ?? 0));
}
}
}
if (orderedIds.length !== fields.length) {
this.logger.warn(
`createFields: detected a dependency cycle in ${tableId}; falling back to input order`
);
return fields;
}
const byId = new Map(fields.map((f) => [f.id, f] as const));
return orderedIds.map((id) => byId.get(id)!).filter(Boolean);
}
@Timing()
async createFields(
tableId: string,
fields: (IFieldVo & { columnMeta?: IColumnMeta; references?: string[] })[]
) {
if (!fields.length) return;
const orderedFields = this.sortCreateFieldsByDependencies(tableId, fields);
// Create fields and compute/publish record changes within the same transaction
const createdFields = await this.prismaService.$tx(
async () => {
const created: { tableId: string; field: IFieldInstance }[] = [];
const sourceEntries: Array<{ tableId: string; fieldIds: string[] }> = [];
const referencesToRestore = new Set<string>();
const pendingByTable = new Map<string, Set<string>>();
const addSourceField = (tid: string, fieldId: string) => {
let entry = sourceEntries.find((s) => s.tableId === tid);
if (!entry) {
entry = { tableId: tid, fieldIds: [] };
sourceEntries.push(entry);
}
if (!entry.fieldIds.includes(fieldId)) {
entry.fieldIds.push(fieldId);
}
};
const markPending = (tid: string, fieldId: string) => {
let set = pendingByTable.get(tid);
if (!set) {
set = new Set<string>();
pendingByTable.set(tid, set);
}
set.add(fieldId);
};
const createPayload = orderedFields.map((field) => {
const { columnMeta, references, ...fieldVo } = field;
if (references?.length) {
references.forEach((refId) => referencesToRestore.add(refId));
}
return {
field: createFieldInstanceByVo(fieldVo),
columnMeta: columnMeta as unknown as Record<string, IColumn>,
};
});
await this.computedOrchestrator.computeCellChangesForFieldsAfterCreate(
sourceEntries,
async () => {
const createResult = await this.fieldCreatingService.alterCreateFieldsInExistingTable(
tableId,
createPayload
);
created.push(...createResult);
for (const { tableId: tid, field } of createResult) {
addSourceField(tid, field.id);
if (field.isComputed) {
markPending(tid, field.id);
}
}
if (referencesToRestore.size) {
await this.restoreReference(Array.from(referencesToRestore));
}
// Ensure dependent formula generated columns are recreated BEFORE
// evaluating and returning values in the computed pipeline.
// This avoids UPDATE ... RETURNING selecting non-existent generated columns
// right after restoring base fields.
const createdFieldIds = created
.filter((nf) => nf.tableId === tableId)
.map((nf) => nf.field.id);
if (createdFieldIds.length) {
try {
await this.fieldService.recreateDependentFormulaColumns(tableId, createdFieldIds);
} catch (e) {
this.logger.warn(
`createFields: failed to recreate dependent formulas for ${tableId}: ${String(e)}`
);
}
}
// Resolve pending computed fields in batches per table
for (const [tid, ids] of pendingByTable.entries()) {
const list = Array.from(ids);
if (list.length) {
await this.fieldService.resolvePending(tid, list);
}
}
}
);
return created;
},
{ timeout: this.thresholdConfig.bigTransactionTimeout }
);
// Recreate search indexes after schema changes (outside tx boundaries)
for (const { tableId: tid, field } of createdFields) {
await this.tableIndexService.createSearchFieldSingleIndex(tid, field);
}
}
@Timing()
async createFieldsByRo(tableId: string, fieldRos: IFieldRo[]): Promise<IFieldVo[]> {
if (!fieldRos.length) return [];
const fieldVos = await this.fieldSupplementService.prepareCreateFields(tableId, fieldRos);
await this.createFields(tableId, fieldVos);
return fieldVos;
}
private async getFieldReferenceMap(fieldIds: string[]) {
const referencesRaw = await this.prismaService.reference.findMany({
where: {
fromFieldId: { in: fieldIds },
},
select: {
fromFieldId: true,
toFieldId: true,
},
});
return groupBy(referencesRaw, 'fromFieldId');
}
@Timing()
async createField(tableId: string, fieldRo: IFieldRo, windowId?: string) {
const fieldVo = await this.fieldSupplementService.prepareCreateField(tableId, fieldRo);
const fieldInstance = createFieldInstanceByVo(fieldVo);
const columnMeta = fieldRo.order && {
[fieldRo.order.viewId]: { order: fieldRo.order.orderIndex },
};
// Create field and compute/publish record changes within the same transaction
const newFields = await this.prismaService.$tx(
async () => {
let created: { tableId: string; field: IFieldInstance }[] = [];
const sourceEntries = [{ tableId, fieldIds: [fieldInstance.id] }];
await this.computedOrchestrator.computeCellChangesForFieldsAfterCreate(
sourceEntries,
async () => {
created = await this.fieldCreatingService.alterCreateField(
tableId,
fieldInstance,
columnMeta
);
for (const { tableId: tid, field } of created) {
let entry = sourceEntries.find((s) => s.tableId === tid);
if (!entry) {
entry = { tableId: tid, fieldIds: [] };
sourceEntries.push(entry);
}
if (!entry.fieldIds.includes(field.id)) {
entry.fieldIds.push(field.id);
}
if (field.isComputed) {
await this.fieldService.resolvePending(tid, [field.id]);
}
}
}
);
return created;
},
{ timeout: this.thresholdConfig.bigTransactionTimeout }
);
for (const { tableId: tid, field } of newFields) {
await this.tableIndexService.createSearchFieldSingleIndex(tid, field);
}
const referenceMap = await this.getFieldReferenceMap([fieldVo.id]);
// Prefer emitting a VO converted from the created instance so computed props (e.g. recordRead)
// are included consistently with snapshots.
const createdMain = newFields.find(
(nf) => nf.tableId === tableId && nf.field.id === fieldVo.id
);
const emitFieldVo = createdMain ? convertFieldInstanceToFieldVo(createdMain.field) : fieldVo;
this.eventEmitterService.emitAsync(Events.OPERATION_FIELDS_CREATE, {
windowId,
tableId,
userId: this.cls.get('user.id'),
fields: [
{
...emitFieldVo,
columnMeta,
references: referenceMap[fieldVo.id]?.map((ref) => ref.toFieldId),
},
],
});
return fieldVo;
}
@Timing()
async deleteFields(tableId: string, fieldIds: string[], windowId?: string) {
const { fields, fieldVos, columnsMeta, referenceMap, records } = await this.prismaService.$tx(
async () => {
const fieldRaws = await this.prismaService.txClient().field.findMany({
where: { tableId, id: { in: fieldIds }, deletedTime: null },
});
const fieldRawMap = new Map(fieldRaws.map((raw) => [raw.id, raw]));
if (fieldRawMap.size !== fieldIds.length) {
const notExistFieldId = fieldIds.find((id) => !fieldRawMap.has(id));
throw new NotFoundException(`Field ${notExistFieldId} not found`);
}
const fieldVoList = fieldIds.map((id) => rawField2FieldObj(fieldRawMap.get(id)!));
const fieldInstances = fieldVoList.map(createFieldInstanceByVo);
const nonComputedFields = fieldInstances.filter((field) => !field.isComputed);
const projection = nonComputedFields.map((field) => field.id);
const recordSnapshot =
projection.length === 0
? undefined
: await this.recordService.getRecordsFields(
tableId,
{
projection,
fieldKeyType: FieldKeyType.Id,
take: -1,
},
true
);
const columnMetaMap = await this.viewService.getColumnsMetaMap(tableId, fieldIds);
const refMap = await this.getFieldReferenceMap(fieldIds);
// Drop per-field search indexes inside the same transaction boundary
for (const field of fieldInstances) {
try {
await this.tableIndexService.deleteSearchFieldIndex(tableId, field);
} catch (e) {
this.logger.warn(`deleteFields: drop search index failed for ${field.id}: ${e}`);
}
}
const sources = [{ tableId, fieldIds: fieldInstances.map((f) => f.id) }];
await this.computedOrchestrator.computeCellChangesForFieldsBeforeDelete(
sources,
async () => {
await this.fieldViewSyncService.deleteDependenciesByFieldIds(
tableId,
fieldInstances.map((f) => f.id)
);
for (const field of fieldInstances) {
await this.fieldDeletingService.alterDeleteField(tableId, field);
}
}
);
return {
fields: fieldInstances,
fieldVos: fieldVoList,
columnsMeta: columnMetaMap,
referenceMap: refMap,
records: recordSnapshot,
};
},
{ timeout: this.thresholdConfig.bigTransactionTimeout }
);
this.eventEmitterService.emitAsync(Events.OPERATION_FIELDS_DELETE, {
operationId: generateOperationId(),
windowId,
tableId,
userId: this.cls.get('user.id'),
fields: fieldVos.map((field, i) => ({
...field,
columnMeta: columnsMeta[i],
references: fieldIds.concat(referenceMap[field.id]?.map((ref) => ref.toFieldId) || []),
})),
records,
});
return fields;
}
async deleteField(tableId: string, fieldId: string, windowId?: string) {
await this.deleteFields(tableId, [fieldId], windowId);
}
private async updateUniqProperty(
tableId: string,
fieldId: string,
key: 'name' | 'dbFieldName',
value: string
) {
const result = await this.prismaService.field