1
import { useEnv } from '@directus/env';
2
import type { SchemaInspector } from '@directus/schema';
3
import { createInspector } from '@directus/schema';
4
import { systemCollectionRows } from '@directus/system-data';
5
import type { Filter, SchemaOverview } from '@directus/types';
6
import { parseJSON, toArray } from '@directus/utils';
7
import type { Knex } from 'knex';
8
import { mapValues } from 'lodash-es';
9
import { useBus } from '../bus/index.js';
10
import { getSchemaCache, setSchemaCache } from '../cache.js';
11
import { ALIAS_TYPES } from '../constants.js';
12
import getDatabase from '../database/index.js';
13
import { useLock } from '../lock/index.js';
14
import { useLogger } from '../logger.js';
15
import { RelationsService } from '../services/relations.js';
16
import getDefaultValue from './get-default-value.js';
17
import { getSystemFieldRowsWithAuthProviders } from './get-field-system-rows.js';
18
import getLocalType from './get-local-type.js';
20
const logger = useLogger();
22
export async function getSchema(
27
* To bypass any cached schema if bypassCache is enabled.
28
* Used to ensure schema snapshot/apply is not using outdated schema
30
bypassCache?: boolean;
33
): Promise<SchemaOverview> {
34
const MAX_ATTEMPTS = 3;
38
if (attempt >= MAX_ATTEMPTS) {
39
throw new Error(`Failed to get Schema information: hit infinite loop`);
42
if (options?.bypassCache || env['CACHE_SCHEMA'] === false) {
43
const database = options?.database || getDatabase();
44
const schemaInspector = createInspector(database);
46
return await getDatabaseSchema(database, schemaInspector);
49
const cached = await getSchemaCache();
55
const lock = useLock();
58
const lockKey = 'schemaCache--preparing';
59
const messageKey = 'schemaCache--done';
60
const processId = await lock.increment(lockKey);
62
if (processId >= (env['CACHE_SCHEMA_MAX_ITERATIONS'] as number)) {
63
await lock.delete(lockKey);
66
const currentProcessShouldHandleOperation = processId === 1;
68
if (currentProcessShouldHandleOperation === false) {
69
logger.trace('Schema cache is prepared in another process, waiting for result.');
71
return new Promise((resolve, reject) => {
72
const TIMEOUT = 10000;
74
const timeout: NodeJS.Timeout = setTimeout(() => {
75
logger.trace('Did not receive schema callback message in time. Pulling schema...');
76
callback().catch(reject);
79
bus.subscribe(messageKey, callback);
81
async function callback() {
83
if (timeout) clearTimeout(timeout);
85
const schema = await getSchema(options, attempt + 1);
90
bus.unsubscribe(messageKey, callback);
97
const database = options?.database || getDatabase();
98
const schemaInspector = createInspector(database);
100
const schema = await getDatabaseSchema(database, schemaInspector);
101
await setSchemaCache(schema);
104
await lock.delete(lockKey);
105
bus.publish(messageKey, { ready: true });
109
async function getDatabaseSchema(database: Knex, schemaInspector: SchemaInspector): Promise<SchemaOverview> {
110
const env = useEnv();
112
const result: SchemaOverview = {
117
const systemFieldRows = getSystemFieldRowsWithAuthProviders();
119
const schemaOverview = await schemaInspector.overview();
121
const collections = [
123
.select('collection', 'singleton', 'note', 'sort_field', 'accountability')
124
.from('directus_collections')),
125
...systemCollectionRows,
128
for (const [collection, info] of Object.entries(schemaOverview)) {
129
if (toArray(env['DB_EXCLUDE_TABLES']).includes(collection)) {
130
logger.trace(`Collection "${collection}" is configured to be excluded and will be ignored`);
135
logger.warn(`Collection "${collection}" doesn't have a primary key column and will be ignored`);
139
if (collection.includes(' ')) {
140
logger.warn(`Collection "${collection}" has a space in the name and will be ignored`);
144
const collectionMeta = collections.find((collectionMeta) => collectionMeta.collection === collection);
146
result.collections[collection] = {
148
primary: info.primary,
150
collectionMeta?.singleton === true || collectionMeta?.singleton === 'true' || collectionMeta?.singleton === 1,
151
note: collectionMeta?.note || null,
152
sortField: collectionMeta?.sort_field || null,
153
accountability: collectionMeta ? collectionMeta.accountability : 'all',
154
fields: mapValues(schemaOverview[collection]?.columns, (column) => {
156
field: column.column_name,
157
defaultValue: getDefaultValue(column) ?? null,
158
nullable: column.is_nullable ?? true,
159
generated: column.is_generated ?? false,
160
type: getLocalType(column),
161
dbType: column.data_type,
162
precision: column.numeric_precision || null,
163
scale: column.numeric_scale || null,
182
validation: string | Record<string, any> | null;
184
>('id', 'collection', 'field', 'special', 'note', 'validation')
185
.from('directus_fields')),
187
].filter((field) => (field.special ? toArray(field.special) : []).includes('no-data') === false);
189
for (const field of fields) {
190
if (!result.collections[field.collection]) continue;
192
const existing = result.collections[field.collection]?.fields[field.field];
193
const column = schemaOverview[field.collection]?.columns[field.field];
194
const special = field.special ? toArray(field.special) : [];
196
if (ALIAS_TYPES.some((type) => special.includes(type)) === false && !existing) continue;
198
const type = (existing && getLocalType(column, { special })) || 'alias';
199
let validation = field.validation ?? null;
201
if (validation && typeof validation === 'string') validation = parseJSON(validation);
203
result.collections[field.collection]!.fields[field.field] = {
205
defaultValue: existing?.defaultValue ?? null,
206
nullable: existing?.nullable ?? true,
207
generated: existing?.generated ?? false,
209
dbType: existing?.dbType || null,
210
precision: existing?.precision || null,
211
scale: existing?.scale || null,
214
alias: existing?.alias ?? true,
215
validation: (validation as Filter) ?? null,
219
const relationsService = new RelationsService({ knex: database, schema: result });
220
result.relations = await relationsService.readAll();