-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
fields.ts
580 lines (489 loc) · 16.2 KB
/
fields.ts
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
import SchemaInspector from '@directus/schema';
import { Knex } from 'knex';
import { Column } from 'knex-schema-inspector/dist/types/column';
import { getCache } from '../cache';
import { ALIAS_TYPES } from '../constants';
import getDatabase, { getSchemaInspector } from '../database';
import { systemFieldRows } from '../database/system-data/fields/';
import emitter from '../emitter';
import env from '../env';
import { ForbiddenException, InvalidPayloadException } from '../exceptions';
import { translateDatabaseError } from '../exceptions/database/translate';
import { ItemsService } from '../services/items';
import { PayloadService } from '../services/payload';
import { AbstractServiceOptions } from '../types';
import { Field, FieldMeta, RawField, Type, Accountability, SchemaOverview } from '@directus/shared/types';
import getDefaultValue from '../utils/get-default-value';
import getLocalType from '../utils/get-local-type';
import { toArray } from '@directus/shared/utils';
import { isEqual, isNil } from 'lodash';
import { RelationsService } from './relations';
import { getHelpers, Helpers } from '../database/helpers';
import Keyv from 'keyv';
export class FieldsService {
knex: Knex;
helpers: Helpers;
accountability: Accountability | null;
itemsService: ItemsService;
payloadService: PayloadService;
schemaInspector: ReturnType<typeof SchemaInspector>;
schema: SchemaOverview;
cache: Keyv<any> | null;
systemCache: Keyv<any>;
constructor(options: AbstractServiceOptions) {
this.knex = options.knex || getDatabase();
this.helpers = getHelpers(this.knex);
this.schemaInspector = options.knex ? SchemaInspector(options.knex) : getSchemaInspector();
this.accountability = options.accountability || null;
this.itemsService = new ItemsService('directus_fields', options);
this.payloadService = new PayloadService('directus_fields', options);
this.schema = options.schema;
const { cache, systemCache } = getCache();
this.cache = cache;
this.systemCache = systemCache;
}
private get hasReadAccess() {
return !!this.accountability?.permissions?.find((permission) => {
return permission.collection === 'directus_fields' && permission.action === 'read';
});
}
async readAll(collection?: string): Promise<Field[]> {
let fields: FieldMeta[];
if (this.accountability && this.accountability.admin !== true && this.hasReadAccess === false) {
throw new ForbiddenException();
}
const nonAuthorizedItemsService = new ItemsService('directus_fields', {
knex: this.knex,
schema: this.schema,
});
if (collection) {
fields = (await nonAuthorizedItemsService.readByQuery({
filter: { collection: { _eq: collection } },
limit: -1,
})) as FieldMeta[];
fields.push(...systemFieldRows.filter((fieldMeta) => fieldMeta.collection === collection));
} else {
fields = (await nonAuthorizedItemsService.readByQuery({ limit: -1 })) as FieldMeta[];
fields.push(...systemFieldRows);
}
const columns = (await this.schemaInspector.columnInfo(collection)).map((column) => ({
...column,
default_value: getDefaultValue(column),
}));
const columnsWithSystem = columns.map((column) => {
const field = fields.find((field) => {
return field.field === column.name && field.collection === column.table;
});
const type = getLocalType(column, field);
const data = {
collection: column.table,
field: column.name,
type: type,
schema: column,
meta: field || null,
};
return data as Field;
});
const aliasQuery = this.knex.select<any[]>('*').from('directus_fields');
if (collection) {
aliasQuery.andWhere('collection', collection);
}
let aliasFields = [...((await this.payloadService.processValues('read', await aliasQuery)) as FieldMeta[])];
if (collection) {
aliasFields.push(...systemFieldRows.filter((fieldMeta) => fieldMeta.collection === collection));
} else {
aliasFields.push(...systemFieldRows);
}
aliasFields = aliasFields.filter((field) => {
const specials = toArray(field.special);
for (const type of ALIAS_TYPES) {
if (specials.includes(type)) return true;
}
return false;
});
const aliasFieldsAsField = aliasFields.map((field) => {
const type = getLocalType(undefined, field);
const data = {
collection: field.collection,
field: field.field,
type,
schema: null,
meta: field,
};
return data;
}) as Field[];
const knownCollections = Object.keys(this.schema.collections);
const result = [...columnsWithSystem, ...aliasFieldsAsField].filter((field) =>
knownCollections.includes(field.collection)
);
// Filter the result so we only return the fields you have read access to
if (this.accountability && this.accountability.admin !== true) {
const permissions = this.accountability.permissions!.filter((permission) => {
return permission.action === 'read';
});
const allowedFieldsInCollection: Record<string, string[]> = {};
permissions.forEach((permission) => {
allowedFieldsInCollection[permission.collection] = permission.fields ?? [];
});
if (collection && collection in allowedFieldsInCollection === false) {
throw new ForbiddenException();
}
return result.filter((field) => {
if (field.collection in allowedFieldsInCollection === false) return false;
const allowedFields = allowedFieldsInCollection[field.collection];
if (allowedFields[0] === '*') return true;
return allowedFields.includes(field.field);
});
}
return result;
}
async readOne(collection: string, field: string): Promise<Record<string, any>> {
if (this.accountability && this.accountability.admin !== true) {
if (this.hasReadAccess === false) {
throw new ForbiddenException();
}
const permissions = this.accountability.permissions!.find((permission) => {
return permission.action === 'read' && permission.collection === collection;
});
if (!permissions || !permissions.fields) throw new ForbiddenException();
if (permissions.fields.includes('*') === false) {
const allowedFields = permissions.fields;
if (allowedFields.includes(field) === false) throw new ForbiddenException();
}
}
let column = undefined;
let fieldInfo = await this.knex.select('*').from('directus_fields').where({ collection, field }).first();
if (fieldInfo) {
fieldInfo = (await this.payloadService.processValues('read', fieldInfo)) as FieldMeta[];
}
fieldInfo =
fieldInfo ||
systemFieldRows.find((fieldMeta) => fieldMeta.collection === collection && fieldMeta.field === field);
try {
column = await this.schemaInspector.columnInfo(collection, field);
column.default_value = getDefaultValue(column);
} catch {
// Do nothing
}
const type = getLocalType(column, fieldInfo);
const data = {
collection,
field,
type,
meta: fieldInfo || null,
schema: type === 'alias' ? null : column,
};
return data;
}
async createField(
collection: string,
field: Partial<Field> & { field: string; type: Type | null },
table?: Knex.CreateTableBuilder // allows collection creation to
): Promise<void> {
if (this.accountability && this.accountability.admin !== true) {
throw new ForbiddenException();
}
const exists =
field.field in this.schema.collections[collection].fields ||
isNil(await this.knex.select('id').from('directus_fields').where({ collection, field: field.field }).first()) ===
false;
// Check if field already exists, either as a column, or as a row in directus_fields
if (exists) {
throw new InvalidPayloadException(`Field "${field.field}" already exists in collection "${collection}"`);
}
await this.knex.transaction(async (trx) => {
const itemsService = new ItemsService('directus_fields', {
knex: trx,
accountability: this.accountability,
schema: this.schema,
});
const hookAdjustedField = await emitter.emitFilter(
`fields.create`,
field,
{
collection: collection,
},
{
database: trx,
schema: this.schema,
accountability: this.accountability,
}
);
if (hookAdjustedField.type && ALIAS_TYPES.includes(hookAdjustedField.type) === false) {
if (table) {
this.addColumnToTable(table, hookAdjustedField as Field);
} else {
await trx.schema.alterTable(collection, (table) => {
this.addColumnToTable(table, hookAdjustedField as Field);
});
}
}
if (hookAdjustedField.meta) {
await itemsService.createOne(
{
...hookAdjustedField.meta,
collection: collection,
field: hookAdjustedField.field,
},
{ emitEvents: false }
);
}
emitter.emitAction(
`fields.create`,
{
payload: hookAdjustedField,
key: hookAdjustedField.field,
collection: collection,
},
{
database: getDatabase(),
schema: this.schema,
accountability: this.accountability,
}
);
});
if (this.cache && env.CACHE_AUTO_PURGE) {
await this.cache.clear();
}
await this.systemCache.clear();
}
async updateField(collection: string, field: RawField): Promise<string> {
if (this.accountability && this.accountability.admin !== true) {
throw new ForbiddenException();
}
const hookAdjustedField = await emitter.emitFilter(
`fields.update`,
field,
{
keys: [field.field],
collection: collection,
},
{
database: this.knex,
schema: this.schema,
accountability: this.accountability,
}
);
const record = field.meta
? await this.knex.select('id').from('directus_fields').where({ collection, field: field.field }).first()
: null;
if (hookAdjustedField.schema) {
const existingColumn = await this.schemaInspector.columnInfo(collection, hookAdjustedField.field);
if (!isEqual(existingColumn, hookAdjustedField.schema)) {
try {
await this.knex.schema.alterTable(collection, (table) => {
if (!hookAdjustedField.schema) return;
this.addColumnToTable(table, field, existingColumn);
});
} catch (err: any) {
throw await translateDatabaseError(err);
}
}
}
if (hookAdjustedField.meta) {
if (record) {
await this.itemsService.updateOne(
record.id,
{
...hookAdjustedField.meta,
collection: collection,
field: hookAdjustedField.field,
},
{ emitEvents: false }
);
} else {
await this.itemsService.createOne(
{
...hookAdjustedField.meta,
collection: collection,
field: hookAdjustedField.field,
},
{ emitEvents: false }
);
}
}
if (this.cache && env.CACHE_AUTO_PURGE) {
await this.cache.clear();
}
await this.systemCache.clear();
emitter.emitAction(
`fields.update`,
{
payload: hookAdjustedField,
keys: [hookAdjustedField.field],
collection: collection,
},
{
database: getDatabase(),
schema: this.schema,
accountability: this.accountability,
}
);
return field.field;
}
async deleteField(collection: string, field: string): Promise<void> {
if (this.accountability && this.accountability.admin !== true) {
throw new ForbiddenException();
}
await emitter.emitFilter(
'fields.delete',
[field],
{
collection: collection,
},
{
database: this.knex,
schema: this.schema,
accountability: this.accountability,
}
);
await this.knex.transaction(async (trx) => {
if (
this.schema.collections[collection] &&
field in this.schema.collections[collection].fields &&
this.schema.collections[collection].fields[field].alias === false
) {
await trx.schema.table(collection, (table) => {
table.dropColumn(field);
});
}
const relations = this.schema.relations.filter((relation) => {
return (
(relation.collection === collection && relation.field === field) ||
(relation.related_collection === collection && relation.meta?.one_field === field)
);
});
const relationsService = new RelationsService({
knex: trx,
accountability: this.accountability,
schema: this.schema,
});
const fieldsService = new FieldsService({
knex: trx,
accountability: this.accountability,
schema: this.schema,
});
for (const relation of relations) {
const isM2O = relation.collection === collection && relation.field === field;
// If the current field is a m2o, delete the related o2m if it exists and remove the relationship
if (isM2O) {
await relationsService.deleteOne(collection, field);
if (relation.related_collection && relation.meta?.one_field) {
await fieldsService.deleteField(relation.related_collection, relation.meta.one_field);
}
}
// If the current field is a o2m, just delete the one field config from the relation
if (!isM2O && relation.meta?.one_field) {
await trx('directus_relations')
.update({ one_field: null })
.where({ many_collection: relation.collection, many_field: relation.field });
}
}
const collectionMeta = await trx
.select('archive_field', 'sort_field')
.from('directus_collections')
.where({ collection })
.first();
const collectionMetaUpdates: Record<string, null> = {};
if (collectionMeta?.archive_field === field) {
collectionMetaUpdates.archive_field = null;
}
if (collectionMeta?.sort_field === field) {
collectionMetaUpdates.sort_field = null;
}
if (Object.keys(collectionMetaUpdates).length > 0) {
await trx('directus_collections').update(collectionMetaUpdates).where({ collection });
}
// Cleanup directus_fields
const metaRow = await trx
.select('collection', 'field')
.from('directus_fields')
.where({ collection, field })
.first();
if (metaRow) {
// Handle recursive FK constraints
await trx('directus_fields')
.update({ group: null })
.where({ group: metaRow.field, collection: metaRow.collection });
}
await trx('directus_fields').delete().where({ collection, field });
});
if (this.cache && env.CACHE_AUTO_PURGE) {
await this.cache.clear();
}
await this.systemCache.clear();
emitter.emitAction(
'fields.delete',
{
payload: [field],
collection: collection,
},
{
database: this.knex,
schema: this.schema,
accountability: this.accountability,
}
);
}
public addColumnToTable(table: Knex.CreateTableBuilder, field: RawField | Field, alter: Column | null = null): void {
let column: Knex.ColumnBuilder;
// Don't attempt to add a DB column for alias / corrupt fields
if (field.type === 'alias' || field.type === 'unknown') return;
if (field.schema?.has_auto_increment) {
column = table.increments(field.field);
} else if (field.type === 'string') {
column = table.string(field.field, field.schema?.max_length ?? undefined);
} else if (['float', 'decimal'].includes(field.type)) {
const type = field.type as 'float' | 'decimal';
column = table[type](field.field, field.schema?.numeric_precision || 10, field.schema?.numeric_scale || 5);
} else if (field.type === 'csv') {
column = table.string(field.field);
} else if (field.type === 'hash') {
column = table.string(field.field, 255);
} else if (field.type === 'dateTime') {
column = table.dateTime(field.field, { useTz: false });
} else if (field.type === 'timestamp') {
column = table.timestamp(field.field, { useTz: true });
} else if (field.type.startsWith('geometry')) {
column = this.helpers.st.createColumn(table, field);
} else {
// @ts-ignore
column = table[field.type](field.field);
}
if (field.schema?.default_value !== undefined) {
if (typeof field.schema.default_value === 'string' && field.schema.default_value.toLowerCase() === 'now()') {
column.defaultTo(this.knex.fn.now());
} else if (
typeof field.schema.default_value === 'string' &&
['"null"', 'null'].includes(field.schema.default_value.toLowerCase())
) {
column.defaultTo(null);
} else {
column.defaultTo(field.schema.default_value);
}
}
if (field.schema?.is_nullable === false) {
if (!alter || alter.is_nullable === true) {
column.notNullable();
}
} else {
if (!alter || alter.is_nullable === false) {
column.nullable();
}
}
if (field.schema?.is_primary_key) {
column.primary().notNullable();
} else if (field.schema?.is_unique === true) {
if (!alter || alter.is_unique === false) {
column.unique();
}
} else if (field.schema?.is_unique === false) {
if (alter && alter.is_unique === true) {
table.dropUnique([field.field]);
}
}
if (alter) {
column.alter();
}
}
}