1
import type { Relation, SchemaOverview } from '@directus/types';
2
import { InvalidQueryError } from '@directus/errors';
3
import { getRelationInfo } from './get-relation-info.js';
5
export type AliasMap = { [key: string]: { alias: string; collection: string } };
7
export type ColPathProps = {
11
relations: Relation[];
12
schema?: SchemaOverview;
15
export type ColPathResult = {
17
targetCollection: string;
18
addNestedPkField: string | undefined;
22
* Converts a Directus field list path to the correct SQL names based on the constructed alias map.
23
* For example: ['author', 'role', 'name'] -> 'ljnsv.name'
24
* Also returns the target collection of the column: 'directus_roles'
25
* If the last filter path is an alias field, a nested PK is appended to the path
27
export function getColumnPath({ path, collection, aliasMap, relations, schema }: ColPathProps) {
28
return followRelation(path);
30
function followRelation(
32
parentCollection: string = collection,
33
parentFields?: string,
34
addNestedPkField?: string,
37
* For A2M fields, the path can contain an optional collection scope <field>:<scope>
39
const pathRoot = pathParts[0]!.split(':')[0];
40
const { relation, relationType } = getRelationInfo(relations, parentCollection, pathRoot!);
43
throw new InvalidQueryError({ reason: `"${parentCollection}.${pathRoot}" is not a relational field` });
46
const alias = parentFields ? aliasMap[`${parentFields}.${pathParts[0]}`]?.alias : aliasMap[pathParts[0]!]?.alias;
47
const remainingParts = pathParts.slice(1);
51
if (relationType === 'a2o') {
52
const pathScope = pathParts[0]!.split(':')[1];
55
throw new InvalidQueryError({
56
reason: `You have to provide a collection scope when sorting on a many-to-any item`,
61
} else if (relationType === 'm2o') {
62
parent = relation.related_collection!;
64
parent = relation.collection;
67
// Top level alias field
68
if (schema && !((remainingParts[0] ?? parent).includes('(') && (remainingParts[0] ?? parent).includes(')'))) {
69
if (remainingParts.length === 0) {
70
remainingParts.push(schema.collections[parent]!.primary);
71
addNestedPkField = schema.collections[parent]!.primary;
73
// Nested level alias field
75
remainingParts.length === 1 &&
76
schema.collections[parent]!.fields[remainingParts[0]!]!.type === 'alias'
78
remainingParts.push(schema.collections[relation!.related_collection!]!.primary);
79
addNestedPkField = schema.collections[relation!.related_collection!]!.primary;
83
if (remainingParts.length === 1) {
85
columnPath: `${alias || parent}.${remainingParts[0]}`,
86
targetCollection: parent,
91
if (remainingParts.length) {
92
return followRelation(
95
`${parentFields ? parentFields + '.' : ''}${pathParts[0]}`,
100
return { columnPath: '', targetCollection: '', addNestedPkField };