@payloadcms/drizzle 4.0.0-canary.20261125 → 4.0.0-canary.20261127
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/find/buildPolymorphicJoinQuery.d.ts +7 -4
- package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -1
- package/dist/find/buildPolymorphicJoinQuery.js +126 -23
- package/dist/find/buildPolymorphicJoinQuery.js.map +1 -1
- package/dist/find/buildPolymorphicJoinWhere.d.ts +2 -1
- package/dist/find/buildPolymorphicJoinWhere.d.ts.map +1 -1
- package/dist/find/buildPolymorphicJoinWhere.js +18 -5
- package/dist/find/buildPolymorphicJoinWhere.js.map +1 -1
- package/dist/find/traverseFields.d.ts.map +1 -1
- package/dist/find/traverseFields.js +3 -0
- package/dist/find/traverseFields.js.map +1 -1
- package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.js +25 -5
- package/dist/queries/getTableColumnFromPath.js.map +1 -1
- package/dist/queries/resolveRelationshipPath.d.ts +1 -0
- package/dist/queries/resolveRelationshipPath.d.ts.map +1 -1
- package/dist/queries/resolveRelationshipPath.js +5 -0
- package/dist/queries/resolveRelationshipPath.js.map +1 -1
- package/dist/queryDrafts.d.ts.map +1 -1
- package/dist/queryDrafts.js +5 -1
- package/dist/queryDrafts.js.map +1 -1
- package/package.json +3 -3
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
import type { SQL } from 'drizzle-orm';
|
|
2
|
-
import {
|
|
2
|
+
import type { FlattenedJoinField, Where } from 'payload';
|
|
3
3
|
import type { DrizzleAdapter } from '../types.js';
|
|
4
4
|
type BuildPolymorphicJoinQueryArgs = {
|
|
5
5
|
adapter: DrizzleAdapter;
|
|
6
6
|
currentTableName: string;
|
|
7
|
+
draftsEnabled?: boolean;
|
|
7
8
|
field: FlattenedJoinField;
|
|
8
9
|
limit: number;
|
|
9
10
|
locale?: string;
|
|
10
11
|
page?: number;
|
|
11
12
|
pageSize?: number;
|
|
13
|
+
parentCollectionSlug?: string;
|
|
12
14
|
path: string;
|
|
13
15
|
shouldCount: boolean;
|
|
14
16
|
sort?: string | string[];
|
|
17
|
+
versions?: boolean;
|
|
15
18
|
where?: Where;
|
|
16
19
|
};
|
|
17
20
|
type PolymorphicJoinQuery = {
|
|
@@ -26,14 +29,14 @@ type PolymorphicJoinQuery = {
|
|
|
26
29
|
* with different schemas can still share one ordered union.
|
|
27
30
|
*
|
|
28
31
|
* `field.collection` must contain at least one configured collection. Each mapped table must have
|
|
29
|
-
* an `id` column and
|
|
30
|
-
* include
|
|
32
|
+
* an `id` column and either a direct relationship column or a matching relationship table. The
|
|
33
|
+
* supplied `limit` can include a look-ahead row. `pageSize` controls the offset.
|
|
31
34
|
*
|
|
32
35
|
* @returns The stable projection name, the document projection, and the count projection when
|
|
33
36
|
* `shouldCount` is true.
|
|
34
37
|
* @throws If the join definition, target collection, mapped table, required columns, or sort shape
|
|
35
38
|
* cannot be represented by the polymorphic query.
|
|
36
39
|
*/
|
|
37
|
-
export declare const buildPolymorphicJoinQuery: ({ adapter, currentTableName, field, limit, locale, page, pageSize, path, shouldCount, sort, where, }: BuildPolymorphicJoinQueryArgs) => PolymorphicJoinQuery;
|
|
40
|
+
export declare const buildPolymorphicJoinQuery: ({ adapter, currentTableName, draftsEnabled, field, limit, locale, page, pageSize, parentCollectionSlug, path, shouldCount, sort, versions, where, }: BuildPolymorphicJoinQueryArgs) => PolymorphicJoinQuery;
|
|
38
41
|
export {};
|
|
39
42
|
//# sourceMappingURL=buildPolymorphicJoinQuery.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildPolymorphicJoinQuery.d.ts","sourceRoot":"","sources":["../../src/find/buildPolymorphicJoinQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"buildPolymorphicJoinQuery.d.ts","sourceRoot":"","sources":["../../src/find/buildPolymorphicJoinQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;AAGtC,OAAO,KAAK,EAAE,kBAAkB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAQxD,OAAO,KAAK,EAAE,cAAc,EAAgB,MAAM,aAAa,CAAA;AAS/D,KAAK,6BAA6B,GAAG;IACnC,OAAO,EAAE,cAAc,CAAA;IACvB,gBAAgB,EAAE,MAAM,CAAA;IACxB,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,KAAK,EAAE,kBAAkB,CAAA;IACzB,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,oBAAoB,CAAC,EAAE,MAAM,CAAA;IAC7B,IAAI,EAAE,MAAM,CAAA;IACZ,WAAW,EAAE,OAAO,CAAA;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IACxB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,KAAK,CAAC,EAAE,KAAK,CAAA;CACd,CAAA;AAED,KAAK,oBAAoB,GAAG;IAC1B,UAAU,EAAE,MAAM,CAAA;IAClB,KAAK,CAAC,EAAE,GAAG,CAAC,OAAO,CAAA;IACnB,SAAS,EAAE,GAAG,CAAC,OAAO,CAAA;CACvB,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,yBAAyB,wJAenC,6BAA6B,KAAG,oBA0SlC,CAAA"}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { and, asc, count, desc, eq, getTableName, sql } from 'drizzle-orm';
|
|
2
|
+
import { buildVersionCollectionFields, getFieldByPath } from 'payload';
|
|
3
|
+
import { hasDraftsEnabled } from 'payload/shared';
|
|
2
4
|
import toSnakeCase from 'to-snake-case';
|
|
5
|
+
import { getTableColumnFromPath } from '../queries/getTableColumnFromPath.js';
|
|
6
|
+
import { resolveRelationshipPath } from '../queries/resolveRelationshipPath.js';
|
|
3
7
|
import { jsonAggBuildObject } from '../utilities/json.js';
|
|
4
8
|
import { buildPolymorphicJoinWhere } from './buildPolymorphicJoinWhere.js';
|
|
5
9
|
import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan.js';
|
|
@@ -10,14 +14,14 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
|
|
|
10
14
|
* with different schemas can still share one ordered union.
|
|
11
15
|
*
|
|
12
16
|
* `field.collection` must contain at least one configured collection. Each mapped table must have
|
|
13
|
-
* an `id` column and
|
|
14
|
-
* include
|
|
17
|
+
* an `id` column and either a direct relationship column or a matching relationship table. The
|
|
18
|
+
* supplied `limit` can include a look-ahead row. `pageSize` controls the offset.
|
|
15
19
|
*
|
|
16
20
|
* @returns The stable projection name, the document projection, and the count projection when
|
|
17
21
|
* `shouldCount` is true.
|
|
18
22
|
* @throws If the join definition, target collection, mapped table, required columns, or sort shape
|
|
19
23
|
* cannot be represented by the polymorphic query.
|
|
20
|
-
*/ export const buildPolymorphicJoinQuery = ({ adapter, currentTableName, field, limit, locale, page, pageSize = limit, path, shouldCount, sort, where })=>{
|
|
24
|
+
*/ export const buildPolymorphicJoinQuery = ({ adapter, currentTableName, draftsEnabled, field, limit, locale, page, pageSize = limit, parentCollectionSlug, path, shouldCount, sort, versions, where })=>{
|
|
21
25
|
if (!Array.isArray(field.collection)) {
|
|
22
26
|
throw new Error('A polymorphic join requires a collection array');
|
|
23
27
|
}
|
|
@@ -30,12 +34,14 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
|
|
|
30
34
|
const collections = field.collection;
|
|
31
35
|
const columnName = `${path.replaceAll('.', '_')}${field.name}`;
|
|
32
36
|
const db = adapter.drizzle;
|
|
33
|
-
const onPath = field.on.split('.').join('_');
|
|
34
37
|
const collectionTables = collections.map((collection)=>{
|
|
35
|
-
|
|
38
|
+
const target = adapter.payload.collections[collection];
|
|
39
|
+
if (!target) {
|
|
36
40
|
throw new Error(`Unknown polymorphic join collection "${collection}"`);
|
|
37
41
|
}
|
|
38
|
-
|
|
42
|
+
// A join can mix draft-enabled targets with targets that only have live rows.
|
|
43
|
+
const shouldUseVersionTable = Boolean((versions || draftsEnabled) && hasDraftsEnabled(target.config));
|
|
44
|
+
const tableName = adapter.tableNameMap.get(shouldUseVersionTable ? `_${toSnakeCase(collection)}${adapter.versionsSuffix}` : toSnakeCase(collection));
|
|
39
45
|
const table = tableName ? adapter.tables[tableName] : undefined;
|
|
40
46
|
if (!table) {
|
|
41
47
|
throw new Error(`Polymorphic join collection "${collection}" has no database table`);
|
|
@@ -43,13 +49,93 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
|
|
|
43
49
|
if (!table['id']) {
|
|
44
50
|
throw new Error(`Polymorphic join collection "${collection}" has no "id" column`);
|
|
45
51
|
}
|
|
46
|
-
|
|
47
|
-
|
|
52
|
+
const fields = shouldUseVersionTable ? buildVersionCollectionFields(adapter.payload.config, target.config, true) : target.config.flattenedFields;
|
|
53
|
+
// Version rows nest configured fields under `version`, including relationship and upload fields.
|
|
54
|
+
const relationshipFieldPath = shouldUseVersionTable ? `version.${field.on}` : field.on;
|
|
55
|
+
const relationshipField = getFieldByPath({
|
|
56
|
+
fields,
|
|
57
|
+
path: relationshipFieldPath
|
|
58
|
+
})?.field;
|
|
59
|
+
const isRelationshipOrUpload = relationshipField?.type === 'relationship' || relationshipField?.type === 'upload';
|
|
60
|
+
if (isRelationshipOrUpload && Array.isArray(relationshipField.relationTo)) {
|
|
61
|
+
throw new Error(`Polymorphic join collection "${collection}" does not support relationTo arrays at "${field.on}"`);
|
|
62
|
+
}
|
|
63
|
+
const relationshipPath = isRelationshipOrUpload ? resolveRelationshipPath({
|
|
64
|
+
adapter,
|
|
65
|
+
fields,
|
|
66
|
+
locale,
|
|
67
|
+
parentIsLocalized: false,
|
|
68
|
+
path: relationshipFieldPath
|
|
69
|
+
}) : null;
|
|
70
|
+
if (isRelationshipOrUpload && relationshipField.hasMany) {
|
|
71
|
+
const relationshipTable = adapter.tables[`${tableName}${adapter.relationshipsSuffix}`];
|
|
72
|
+
const parentColumn = relationshipTable?.[`${relationshipField.relationTo}ID`];
|
|
73
|
+
if (!relationshipTable || !relationshipPath || !parentColumn || parentCollectionSlug && relationshipField.relationTo !== parentCollectionSlug) {
|
|
74
|
+
throw new Error(`Polymorphic join collection "${collection}" has no supported relationship at "${field.on}"`);
|
|
75
|
+
}
|
|
76
|
+
const relationshipLocale = relationshipPath.locale;
|
|
77
|
+
const pathSegments = relationshipPath.path.split('.');
|
|
78
|
+
const isPostgres = adapter.name === 'postgres';
|
|
79
|
+
// Array markers are tracked separately so a literal `%` in a field name stays literal.
|
|
80
|
+
const relationshipPathPattern = pathSegments.map((segment, index)=>{
|
|
81
|
+
if (relationshipPath.arrayPositionIndices.includes(index)) {
|
|
82
|
+
return isPostgres ? '%' : '*';
|
|
83
|
+
}
|
|
84
|
+
return isPostgres ? segment.replace(/[\\%_]/g, '\\$&') : segment.replace(/[[*?]/g, '[$&]');
|
|
85
|
+
}).join('.');
|
|
86
|
+
const expectedDotCount = pathSegments.length - 1;
|
|
87
|
+
// SQLite GLOB compares field names case-sensitively; the dot count keeps wildcards in one segment.
|
|
88
|
+
const relationshipPathCondition = relationshipPath.arrayPositionIndices.length ? and(isPostgres ? sql`${relationshipTable.path} like ${relationshipPathPattern} escape '\\'` : sql`${relationshipTable.path} glob ${relationshipPathPattern}`, sql`length(${relationshipTable.path}) - length(replace(${relationshipTable.path}, '.', '')) = ${expectedDotCount}`) : eq(relationshipTable.path, relationshipPath.path);
|
|
89
|
+
// The relationship row belongs to the target row's ID, which is a version ID for drafts.
|
|
90
|
+
const relationshipRowCondition = and(eq(table['id'], relationshipTable.parent), relationshipPathCondition, relationshipPath.isLocalized && relationshipLocale && relationshipLocale !== 'all' ? eq(relationshipTable.locale, relationshipLocale) : undefined);
|
|
91
|
+
return {
|
|
92
|
+
collection,
|
|
93
|
+
parentColumn,
|
|
94
|
+
relationshipRowCondition,
|
|
95
|
+
relationshipTable,
|
|
96
|
+
shouldUseVersionTable,
|
|
97
|
+
table
|
|
98
|
+
};
|
|
99
|
+
} else {
|
|
100
|
+
if (relationshipPath?.arrayPositionIndices.length) {
|
|
101
|
+
// A singular reference inside an array is a column on the array table.
|
|
102
|
+
const arrayJoins = [];
|
|
103
|
+
const resolvedColumn = getTableColumnFromPath({
|
|
104
|
+
adapter,
|
|
105
|
+
collectionPath: relationshipFieldPath,
|
|
106
|
+
fields,
|
|
107
|
+
joins: arrayJoins,
|
|
108
|
+
locale,
|
|
109
|
+
parentIsLocalized: false,
|
|
110
|
+
pathSegments: relationshipFieldPath.split('.'),
|
|
111
|
+
selectFields: {},
|
|
112
|
+
tableName,
|
|
113
|
+
value: undefined
|
|
114
|
+
});
|
|
115
|
+
const parentColumn = resolvedColumn.columnName ? resolvedColumn.table[resolvedColumn.columnName] : undefined;
|
|
116
|
+
if (!parentColumn) {
|
|
117
|
+
throw new Error(`Polymorphic join collection "${collection}" has no supported relationship at "${field.on}"`);
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
arrayJoins,
|
|
121
|
+
collection,
|
|
122
|
+
parentColumn,
|
|
123
|
+
shouldUseVersionTable,
|
|
124
|
+
table
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
const relationshipColumnName = relationshipFieldPath.replaceAll('.', '_');
|
|
128
|
+
const parentColumn = table[relationshipColumnName];
|
|
129
|
+
if (!parentColumn) {
|
|
130
|
+
throw new Error(`Polymorphic join collection "${collection}" has no "${relationshipColumnName}" column`);
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
collection,
|
|
134
|
+
parentColumn,
|
|
135
|
+
shouldUseVersionTable,
|
|
136
|
+
table
|
|
137
|
+
};
|
|
48
138
|
}
|
|
49
|
-
return {
|
|
50
|
-
collection,
|
|
51
|
-
table
|
|
52
|
-
};
|
|
53
139
|
});
|
|
54
140
|
const sortField = getSortField({
|
|
55
141
|
adapter,
|
|
@@ -64,11 +150,15 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
|
|
|
64
150
|
where
|
|
65
151
|
}) : new Map();
|
|
66
152
|
let unionQuery = null;
|
|
67
|
-
for (const
|
|
68
|
-
const
|
|
153
|
+
for (const collectionTable of collectionTables){
|
|
154
|
+
const { arrayJoins, collection, parentColumn, relationshipRowCondition, relationshipTable, shouldUseVersionTable, table } = collectionTable;
|
|
155
|
+
const versionSortColumnName = sortPath === 'id' ? 'parent' : `version_${sortPath}`;
|
|
156
|
+
const sortColumnName = shouldUseVersionTable ? versionSortColumnName : sortPath;
|
|
157
|
+
const sortColumn = table[sortColumnName];
|
|
158
|
+
// Return the document ID so the join resolver can load a versioned target by its parent.
|
|
69
159
|
const selectFields = {
|
|
70
|
-
id: table['id'],
|
|
71
|
-
parent: sql`${
|
|
160
|
+
id: sql`${shouldUseVersionTable ? table['parent'] : table['id']}`.as('id'),
|
|
161
|
+
parent: sql`${parentColumn}`.as('parent'),
|
|
72
162
|
relationTo: sql`${collection}`.as('relationTo'),
|
|
73
163
|
sortPath: sql`${sortColumn ?? null}`.as('sortPath')
|
|
74
164
|
};
|
|
@@ -76,6 +166,7 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
|
|
|
76
166
|
adapter,
|
|
77
167
|
collection,
|
|
78
168
|
locale,
|
|
169
|
+
shouldUseVersionTable,
|
|
79
170
|
table,
|
|
80
171
|
where,
|
|
81
172
|
wherePlan
|
|
@@ -86,14 +177,22 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
|
|
|
86
177
|
const collectionField = pathPlan.fieldsByCollection.get(collection);
|
|
87
178
|
return collectionField?.type === 'scalar' && collectionField.isLocalized;
|
|
88
179
|
});
|
|
89
|
-
|
|
180
|
+
// Multiple relationship rows can match one target; count and page the document once.
|
|
181
|
+
const shouldDeduplicate = Boolean(relationshipTable || arrayJoins?.length) || hasLocalizedWhere && (!locale || locale === 'all');
|
|
90
182
|
let collectionQuery = (shouldDeduplicate ? db.selectDistinct(selectFields) : db.select(selectFields)).from(table).$dynamic();
|
|
183
|
+
if (relationshipTable) {
|
|
184
|
+
collectionQuery = collectionQuery.innerJoin(relationshipTable, relationshipRowCondition);
|
|
185
|
+
}
|
|
186
|
+
for (const { condition, table: arrayTable } of arrayJoins ?? []){
|
|
187
|
+
collectionQuery = collectionQuery.innerJoin(arrayTable, condition);
|
|
188
|
+
}
|
|
91
189
|
if (hasLocalizedWhere) {
|
|
92
190
|
const localesTable = adapter.tables[`${getTableName(table)}${adapter.localesSuffix}`];
|
|
93
191
|
collectionQuery = collectionQuery.leftJoin(localesTable, and(eq(table['id'], localesTable._parentID), locale && locale !== 'all' ? eq(localesTable._locale, locale) : undefined));
|
|
94
192
|
}
|
|
95
|
-
|
|
96
|
-
|
|
193
|
+
// Older versions may contain the same relationship; exclude them before counting and paging.
|
|
194
|
+
if (collectionWhere || shouldUseVersionTable) {
|
|
195
|
+
collectionQuery = collectionQuery.where(and(collectionWhere, shouldUseVersionTable ? eq(table['latest'], true) : undefined));
|
|
97
196
|
}
|
|
98
197
|
if (unionQuery === null) {
|
|
99
198
|
unionQuery = collectionQuery;
|
|
@@ -102,11 +201,13 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
|
|
|
102
201
|
}
|
|
103
202
|
}
|
|
104
203
|
const subQueryAlias = `${columnName}_subquery`;
|
|
105
|
-
|
|
204
|
+
// A versioned parent has a separate version ID; relationships point at its document ID.
|
|
205
|
+
const parentIDColumn = adapter.tables[currentTableName][versions ? 'parent' : 'id'];
|
|
206
|
+
const parentID = sql`${sql.identifier(currentTableName)}.${sql.identifier(parentIDColumn.name)}`;
|
|
207
|
+
const parentConstraint = eq(parentID, sql`${sql.identifier(subQueryAlias)}."parent"`);
|
|
106
208
|
const countExpression = shouldCount ? sql`${db.select({
|
|
107
209
|
count: count()
|
|
108
210
|
}).from(sql`${unionQuery.as(subQueryAlias)}`).where(parentConstraint)}`.as(`${columnName}_count`) : undefined;
|
|
109
|
-
unionQuery = unionQuery.orderBy(sortOrder(sql`"sortPath"`));
|
|
110
211
|
const sortedUnionAlias = `${columnName}_sorted`;
|
|
111
212
|
let limitOffsetSQL = sql.empty();
|
|
112
213
|
if (limit) {
|
|
@@ -118,7 +219,8 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
|
|
|
118
219
|
limitOffsetSQL = sql`${limitOffsetSQL} OFFSET ${offset}`;
|
|
119
220
|
}
|
|
120
221
|
}
|
|
121
|
-
const parentWhere = sql.
|
|
222
|
+
const parentWhere = eq(sql`${sql.identifier(sortedUnionAlias)}."parent"`, parentID);
|
|
223
|
+
// Sort each parent's rows before limiting; relationTo and ID keep equal sort values stable.
|
|
122
224
|
const documents = sql`(
|
|
123
225
|
SELECT ${jsonAggBuildObject(adapter, {
|
|
124
226
|
id: sql.raw(`"${subQueryAlias}"."id"`),
|
|
@@ -126,7 +228,8 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
|
|
|
126
228
|
})}
|
|
127
229
|
FROM (
|
|
128
230
|
SELECT * FROM ${sql`${unionQuery.as(sortedUnionAlias)}`}
|
|
129
|
-
WHERE ${parentWhere}
|
|
231
|
+
WHERE ${parentWhere}
|
|
232
|
+
order by ${sortOrder(sql`"sortPath"`)}, ${asc(sql`"relationTo"`)}, ${asc(sql`"id"`)}${limitOffsetSQL}
|
|
130
233
|
) AS ${sql.raw(`"${subQueryAlias}"`)}
|
|
131
234
|
)`.as(columnName);
|
|
132
235
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/find/buildPolymorphicJoinQuery.ts"],"sourcesContent":["import type { SQL } from 'drizzle-orm'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { SQLiteSelect } from 'drizzle-orm/sqlite-core'\n\nimport { and, asc, count, desc, eq, getTableName, sql } from 'drizzle-orm'\nimport { type FlattenedJoinField, type Where } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter, GenericTable } from '../types.js'\nimport type { PolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan.js'\n\nimport { jsonAggBuildObject } from '../utilities/json.js'\nimport { buildPolymorphicJoinWhere } from './buildPolymorphicJoinWhere.js'\nimport { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan.js'\n\ntype BuildPolymorphicJoinQueryArgs = {\n adapter: DrizzleAdapter\n currentTableName: string\n field: FlattenedJoinField\n limit: number\n locale?: string\n page?: number\n pageSize?: number\n path: string\n shouldCount: boolean\n sort?: string | string[]\n where?: Where\n}\n\ntype PolymorphicJoinQuery = {\n columnName: string\n count?: SQL.Aliased\n documents: SQL.Aliased\n}\n\n/**\n * Builds the correlated document and optional count projections for a join that targets multiple\n * collections. Every collection branch exposes the same `id`, parent, `relationTo`, and sort\n * columns before the branches are combined. A missing sort field resolves to SQL NULL so targets\n * with different schemas can still share one ordered union.\n *\n * `field.collection` must contain at least one configured collection. Each mapped table must have\n * an `id` column and the column named by `field.on`. The supplied `limit` is used as-is; callers can\n * include an extra look-ahead row and supply the original `pageSize` for offset calculation.\n *\n * @returns The stable projection name, the document projection, and the count projection when\n * `shouldCount` is true.\n * @throws If the join definition, target collection, mapped table, required columns, or sort shape\n * cannot be represented by the polymorphic query.\n */\nexport const buildPolymorphicJoinQuery = ({\n adapter,\n currentTableName,\n field,\n limit,\n locale,\n page,\n pageSize = limit,\n path,\n shouldCount,\n sort,\n where,\n}: BuildPolymorphicJoinQueryArgs): PolymorphicJoinQuery => {\n if (!Array.isArray(field.collection)) {\n throw new Error('A polymorphic join requires a collection array')\n }\n\n if (field.collection.length === 0) {\n throw new Error('A polymorphic join requires at least one collection')\n }\n\n if (Array.isArray(sort)) {\n throw new Error('Polymorphic joins do not support multiple sort fields')\n }\n\n const collections = field.collection\n const columnName = `${path.replaceAll('.', '_')}${field.name}`\n const db = adapter.drizzle as LibSQLDatabase\n const onPath = field.on.split('.').join('_')\n const collectionTables = collections.map((collection) => {\n if (!adapter.payload.collections[collection]) {\n throw new Error(`Unknown polymorphic join collection \"${collection}\"`)\n }\n\n const tableName = adapter.tableNameMap.get(toSnakeCase(collection))\n const table = tableName ? (adapter.tables[tableName] as GenericTable | undefined) : undefined\n\n if (!table) {\n throw new Error(`Polymorphic join collection \"${collection}\" has no database table`)\n }\n\n if (!table['id']) {\n throw new Error(`Polymorphic join collection \"${collection}\" has no \"id\" column`)\n }\n\n if (!table[onPath]) {\n throw new Error(`Polymorphic join collection \"${collection}\" has no \"${onPath}\" column`)\n }\n\n return { collection, table }\n })\n const sortField = getSortField({ adapter, collections, sort })\n const sortOrder = sortField.startsWith('-') ? desc : asc\n const sortPath = sortField.replace('-', '').split('.').join('_')\n const wherePlan: PolymorphicJoinWherePlan = where\n ? createPolymorphicJoinWherePlan({ adapter, collections, where })\n : new Map()\n let unionQuery: null | SQLiteSelect = null\n\n for (const { collection, table } of collectionTables) {\n const sortColumn = table[sortPath]\n const selectFields = {\n id: table['id'],\n parent: sql`${table[onPath]}`.as(onPath),\n relationTo: sql`${collection}`.as('relationTo'),\n sortPath: sql`${sortColumn ?? null}`.as('sortPath'),\n }\n const collectionWhere =\n where && Object.keys(where).length > 0\n ? buildPolymorphicJoinWhere({\n adapter,\n collection,\n locale,\n table,\n where,\n wherePlan,\n })\n : undefined\n const hasLocalizedWhere = [...wherePlan.values()].some((pathPlan) => {\n const collectionField = pathPlan.fieldsByCollection.get(collection)\n\n return collectionField?.type === 'scalar' && collectionField.isLocalized\n })\n const shouldDeduplicate = hasLocalizedWhere && (!locale || locale === 'all')\n let collectionQuery = (\n shouldDeduplicate ? db.selectDistinct(selectFields) : db.select(selectFields)\n )\n .from(table)\n .$dynamic()\n\n if (hasLocalizedWhere) {\n const localesTable = adapter.tables[`${getTableName(table)}${adapter.localesSuffix}`]\n\n collectionQuery = collectionQuery.leftJoin(\n localesTable,\n and(\n eq(table['id'], localesTable._parentID),\n locale && locale !== 'all' ? eq(localesTable._locale, locale) : undefined,\n ),\n )\n }\n\n if (collectionWhere) {\n collectionQuery = collectionQuery.where(collectionWhere)\n }\n\n if (unionQuery === null) {\n unionQuery = collectionQuery\n } else {\n unionQuery = unionQuery.unionAll(collectionQuery)\n }\n }\n\n const subQueryAlias = `${columnName}_subquery`\n const parentConstraint = eq(\n sql.raw(`\"${currentTableName}\".\"id\"`),\n sql.raw(`\"${subQueryAlias}\".\"${onPath}\"`),\n )\n const countExpression = shouldCount\n ? sql`${db\n .select({ count: count() })\n .from(sql`${unionQuery.as(subQueryAlias)}`)\n .where(parentConstraint)}`.as(`${columnName}_count`)\n : undefined\n\n unionQuery = unionQuery.orderBy(sortOrder(sql`\"sortPath\"`))\n\n const sortedUnionAlias = `${columnName}_sorted`\n let limitOffsetSQL = sql.empty()\n\n if (limit) {\n limitOffsetSQL = sql` LIMIT ${limit}`\n }\n\n if (page && limit !== 0) {\n const offset = (page - 1) * pageSize\n\n if (offset > 0) {\n limitOffsetSQL = sql`${limitOffsetSQL} OFFSET ${offset}`\n }\n }\n\n const parentWhere = sql.raw(`\"${sortedUnionAlias}\".\"${onPath}\" = \"${currentTableName}\".\"id\"`)\n const documents = sql`(\n SELECT ${jsonAggBuildObject(adapter, {\n id: sql.raw(`\"${subQueryAlias}\".\"id\"`),\n relationTo: sql.raw(`\"${subQueryAlias}\".\"relationTo\"`),\n })}\n FROM (\n SELECT * FROM ${sql`${unionQuery.as(sortedUnionAlias)}`}\n WHERE ${parentWhere}${limitOffsetSQL}\n ) AS ${sql.raw(`\"${subQueryAlias}\"`)}\n )`.as(columnName)\n\n return {\n columnName,\n count: countExpression,\n documents,\n }\n}\n\nconst getSortField = ({\n adapter,\n collections,\n sort,\n}: {\n adapter: DrizzleAdapter\n collections: string[]\n sort?: string\n}): string => {\n if (sort) {\n return sort\n }\n\n const hasCreatedAt = collections.some((collection) =>\n adapter.payload.collections[collection].config.fields.some(\n (field) => field.type === 'date' && field.name === 'createdAt',\n ),\n )\n\n return hasCreatedAt ? '-createdAt' : 'id'\n}\n"],"names":["and","asc","count","desc","eq","getTableName","sql","toSnakeCase","jsonAggBuildObject","buildPolymorphicJoinWhere","createPolymorphicJoinWherePlan","buildPolymorphicJoinQuery","adapter","currentTableName","field","limit","locale","page","pageSize","path","shouldCount","sort","where","Array","isArray","collection","Error","length","collections","columnName","replaceAll","name","db","drizzle","onPath","on","split","join","collectionTables","map","payload","tableName","tableNameMap","get","table","tables","undefined","sortField","getSortField","sortOrder","startsWith","sortPath","replace","wherePlan","Map","unionQuery","sortColumn","selectFields","id","parent","as","relationTo","collectionWhere","Object","keys","hasLocalizedWhere","values","some","pathPlan","collectionField","fieldsByCollection","type","isLocalized","shouldDeduplicate","collectionQuery","selectDistinct","select","from","$dynamic","localesTable","localesSuffix","leftJoin","_parentID","_locale","unionAll","subQueryAlias","parentConstraint","raw","countExpression","orderBy","sortedUnionAlias","limitOffsetSQL","empty","offset","parentWhere","documents","hasCreatedAt","config","fields"],"mappings":"AAIA,SAASA,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAEC,EAAE,EAAEC,YAAY,EAAEC,GAAG,QAAQ,cAAa;AAE1E,OAAOC,iBAAiB,gBAAe;AAKvC,SAASC,kBAAkB,QAAQ,uBAAsB;AACzD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,8BAA8B,QAAQ,sCAAqC;AAsBpF;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMC,4BAA4B,CAAC,EACxCC,OAAO,EACPC,gBAAgB,EAChBC,KAAK,EACLC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,WAAWH,KAAK,EAChBI,IAAI,EACJC,WAAW,EACXC,IAAI,EACJC,KAAK,EACyB;IAC9B,IAAI,CAACC,MAAMC,OAAO,CAACV,MAAMW,UAAU,G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AAe,QAAQ,EAAEE,OAAO,CAAC;QAC1D;IACF;IAEA,MAAMC,cAAcxF,IAAIiF,GAAG,CAAC,CAAC,CAAC,EAAEG,iBAAiB,GAAG,EAAExD,OAAO,KAAK,EAAErB,iBAAiB,MAAM,CAAC;IAC5F,MAAMkF,YAAYzF,GAAG,CAAC;WACb,EAAEE,mBAAmBI,SAAS;QACnC8C,IAAIpD,IAAIiF,GAAG,CAAC,CAAC,CAAC,EAAEF,cAAc,MAAM,CAAC;QACrCxB,YAAYvD,IAAIiF,GAAG,CAAC,CAAC,CAAC,EAAEF,cAAc,cAAc,CAAC;IACvD,GAAG;;oBAEa,EAAE/E,GAAG,CAAC,EAAEiD,WAAWK,EAAE,CAAC8B,kBAAkB,CAAC,CAAC;YAClD,EAAEI,YAAY,EAAEH,eAAe;SAClC,EAAErF,IAAIiF,GAAG,CAAC,CAAC,CAAC,EAAEF,cAAc,CAAC,CAAC,EAAE;GACtC,CAAC,CAACzB,EAAE,CAAC/B;IAEN,OAAO;QACLA;QACA3B,OAAOsF;QACPO;IACF;AACF,EAAC;AAED,MAAM/C,eAAe,CAAC,EACpBpC,OAAO,EACPgB,WAAW,EACXP,IAAI,EAKL;IACC,IAAIA,MAAM;QACR,OAAOA;IACT;IAEA,MAAM2E,eAAepE,YAAYuC,IAAI,CAAC,CAAC1C,aACrCb,QAAQ4B,OAAO,CAACZ,WAAW,CAACH,WAAW,CAACwE,MAAM,CAACC,MAAM,CAAC/B,IAAI,CACxD,CAACrD,QAAUA,MAAMyD,IAAI,KAAK,UAAUzD,MAAMiB,IAAI,KAAK;IAIvD,OAAOiE,eAAe,eAAe;AACvC"}
|
|
1
|
+
{"version":3,"sources":["../../src/find/buildPolymorphicJoinQuery.ts"],"sourcesContent":["import type { SQL } from 'drizzle-orm'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { SQLiteSelect } from 'drizzle-orm/sqlite-core'\nimport type { FlattenedJoinField, Where } from 'payload'\n\nimport { and, asc, count, desc, eq, getTableName, sql } from 'drizzle-orm'\nimport { buildVersionCollectionFields, getFieldByPath } from 'payload'\nimport { hasDraftsEnabled } from 'payload/shared'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { BuildQueryJoinAliases } from '../queries/buildQuery.js'\nimport type { DrizzleAdapter, GenericTable } from '../types.js'\nimport type { PolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan.js'\n\nimport { getTableColumnFromPath } from '../queries/getTableColumnFromPath.js'\nimport { resolveRelationshipPath } from '../queries/resolveRelationshipPath.js'\nimport { jsonAggBuildObject } from '../utilities/json.js'\nimport { buildPolymorphicJoinWhere } from './buildPolymorphicJoinWhere.js'\nimport { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan.js'\n\ntype BuildPolymorphicJoinQueryArgs = {\n adapter: DrizzleAdapter\n currentTableName: string\n draftsEnabled?: boolean\n field: FlattenedJoinField\n limit: number\n locale?: string\n page?: number\n pageSize?: number\n parentCollectionSlug?: string\n path: string\n shouldCount: boolean\n sort?: string | string[]\n versions?: boolean\n where?: Where\n}\n\ntype PolymorphicJoinQuery = {\n columnName: string\n count?: SQL.Aliased\n documents: SQL.Aliased\n}\n\n/**\n * Builds the correlated document and optional count projections for a join that targets multiple\n * collections. Every collection branch exposes the same `id`, parent, `relationTo`, and sort\n * columns before the branches are combined. A missing sort field resolves to SQL NULL so targets\n * with different schemas can still share one ordered union.\n *\n * `field.collection` must contain at least one configured collection. Each mapped table must have\n * an `id` column and either a direct relationship column or a matching relationship table. The\n * supplied `limit` can include a look-ahead row. `pageSize` controls the offset.\n *\n * @returns The stable projection name, the document projection, and the count projection when\n * `shouldCount` is true.\n * @throws If the join definition, target collection, mapped table, required columns, or sort shape\n * cannot be represented by the polymorphic query.\n */\nexport const buildPolymorphicJoinQuery = ({\n adapter,\n currentTableName,\n draftsEnabled,\n field,\n limit,\n locale,\n page,\n pageSize = limit,\n parentCollectionSlug,\n path,\n shouldCount,\n sort,\n versions,\n where,\n}: BuildPolymorphicJoinQueryArgs): PolymorphicJoinQuery => {\n if (!Array.isArray(field.collection)) {\n throw new Error('A polymorphic join requires a collection array')\n }\n\n if (field.collection.length === 0) {\n throw new Error('A polymorphic join requires at least one collection')\n }\n\n if (Array.isArray(sort)) {\n throw new Error('Polymorphic joins do not support multiple sort fields')\n }\n\n const collections = field.collection\n const columnName = `${path.replaceAll('.', '_')}${field.name}`\n const db = adapter.drizzle as LibSQLDatabase\n const collectionTables = collections.map((collection) => {\n const target = adapter.payload.collections[collection]\n\n if (!target) {\n throw new Error(`Unknown polymorphic join collection \"${collection}\"`)\n }\n\n // A join can mix draft-enabled targets with targets that only have live rows.\n const shouldUseVersionTable = Boolean(\n (versions || draftsEnabled) && hasDraftsEnabled(target.config),\n )\n const tableName = adapter.tableNameMap.get(\n shouldUseVersionTable\n ? `_${toSnakeCase(collection)}${adapter.versionsSuffix}`\n : toSnakeCase(collection),\n )\n const table = tableName ? (adapter.tables[tableName] as GenericTable | undefined) : undefined\n\n if (!table) {\n throw new Error(`Polymorphic join collection \"${collection}\" has no database table`)\n }\n\n if (!table['id']) {\n throw new Error(`Polymorphic join collection \"${collection}\" has no \"id\" column`)\n }\n\n const fields = shouldUseVersionTable\n ? buildVersionCollectionFields(adapter.payload.config, target.config, true)\n : target.config.flattenedFields\n // Version rows nest configured fields under `version`, including relationship and upload fields.\n const relationshipFieldPath = shouldUseVersionTable ? `version.${field.on}` : field.on\n const relationshipField = getFieldByPath({ fields, path: relationshipFieldPath })?.field\n const isRelationshipOrUpload =\n relationshipField?.type === 'relationship' || relationshipField?.type === 'upload'\n\n if (isRelationshipOrUpload && Array.isArray(relationshipField.relationTo)) {\n throw new Error(\n `Polymorphic join collection \"${collection}\" does not support relationTo arrays at \"${field.on}\"`,\n )\n }\n\n const relationshipPath = isRelationshipOrUpload\n ? resolveRelationshipPath({\n adapter,\n fields,\n locale,\n parentIsLocalized: false,\n path: relationshipFieldPath,\n })\n : null\n\n if (isRelationshipOrUpload && relationshipField.hasMany) {\n const relationshipTable = adapter.tables[`${tableName}${adapter.relationshipsSuffix}`]\n const parentColumn = relationshipTable?.[`${relationshipField.relationTo}ID`]\n\n if (\n !relationshipTable ||\n !relationshipPath ||\n !parentColumn ||\n (parentCollectionSlug && relationshipField.relationTo !== parentCollectionSlug)\n ) {\n throw new Error(\n `Polymorphic join collection \"${collection}\" has no supported relationship at \"${field.on}\"`,\n )\n }\n\n const relationshipLocale = relationshipPath.locale\n const pathSegments = relationshipPath.path.split('.')\n const isPostgres = adapter.name === 'postgres'\n // Array markers are tracked separately so a literal `%` in a field name stays literal.\n const relationshipPathPattern = pathSegments\n .map((segment, index) => {\n if (relationshipPath.arrayPositionIndices.includes(index)) {\n return isPostgres ? '%' : '*'\n }\n\n return isPostgres ? segment.replace(/[\\\\%_]/g, '\\\\$&') : segment.replace(/[[*?]/g, '[$&]')\n })\n .join('.')\n const expectedDotCount = pathSegments.length - 1\n // SQLite GLOB compares field names case-sensitively; the dot count keeps wildcards in one segment.\n const relationshipPathCondition = relationshipPath.arrayPositionIndices.length\n ? and(\n isPostgres\n ? sql`${relationshipTable.path} like ${relationshipPathPattern} escape '\\\\'`\n : sql`${relationshipTable.path} glob ${relationshipPathPattern}`,\n sql`length(${relationshipTable.path}) - length(replace(${relationshipTable.path}, '.', '')) = ${expectedDotCount}`,\n )\n : eq(relationshipTable.path, relationshipPath.path)\n // The relationship row belongs to the target row's ID, which is a version ID for drafts.\n const relationshipRowCondition = and(\n eq(table['id'], relationshipTable.parent),\n relationshipPathCondition,\n relationshipPath.isLocalized && relationshipLocale && relationshipLocale !== 'all'\n ? eq(relationshipTable.locale, relationshipLocale)\n : undefined,\n )\n\n return {\n collection,\n parentColumn,\n relationshipRowCondition,\n relationshipTable,\n shouldUseVersionTable,\n table,\n }\n } else {\n if (relationshipPath?.arrayPositionIndices.length) {\n // A singular reference inside an array is a column on the array table.\n const arrayJoins: BuildQueryJoinAliases = []\n const resolvedColumn = getTableColumnFromPath({\n adapter,\n collectionPath: relationshipFieldPath,\n fields,\n joins: arrayJoins,\n locale,\n parentIsLocalized: false,\n pathSegments: relationshipFieldPath.split('.'),\n selectFields: {},\n tableName,\n value: undefined,\n })\n const parentColumn = resolvedColumn.columnName\n ? resolvedColumn.table[resolvedColumn.columnName]\n : undefined\n\n if (!parentColumn) {\n throw new Error(\n `Polymorphic join collection \"${collection}\" has no supported relationship at \"${field.on}\"`,\n )\n }\n\n return { arrayJoins, collection, parentColumn, shouldUseVersionTable, table }\n }\n\n const relationshipColumnName = relationshipFieldPath.replaceAll('.', '_')\n const parentColumn = table[relationshipColumnName]\n if (!parentColumn) {\n throw new Error(\n `Polymorphic join collection \"${collection}\" has no \"${relationshipColumnName}\" column`,\n )\n }\n\n return { collection, parentColumn, shouldUseVersionTable, table }\n }\n })\n const sortField = getSortField({ adapter, collections, sort })\n const sortOrder = sortField.startsWith('-') ? desc : asc\n const sortPath = sortField.replace('-', '').split('.').join('_')\n const wherePlan: PolymorphicJoinWherePlan = where\n ? createPolymorphicJoinWherePlan({ adapter, collections, where })\n : new Map()\n let unionQuery: null | SQLiteSelect = null\n\n for (const collectionTable of collectionTables) {\n const {\n arrayJoins,\n collection,\n parentColumn,\n relationshipRowCondition,\n relationshipTable,\n shouldUseVersionTable,\n table,\n } = collectionTable\n\n const versionSortColumnName = sortPath === 'id' ? 'parent' : `version_${sortPath}`\n const sortColumnName = shouldUseVersionTable ? versionSortColumnName : sortPath\n const sortColumn = table[sortColumnName]\n // Return the document ID so the join resolver can load a versioned target by its parent.\n const selectFields = {\n id: sql`${shouldUseVersionTable ? table['parent'] : table['id']}`.as('id'),\n parent: sql`${parentColumn}`.as('parent'),\n relationTo: sql`${collection}`.as('relationTo'),\n sortPath: sql`${sortColumn ?? null}`.as('sortPath'),\n }\n const collectionWhere =\n where && Object.keys(where).length > 0\n ? buildPolymorphicJoinWhere({\n adapter,\n collection,\n locale,\n shouldUseVersionTable,\n table,\n where,\n wherePlan,\n })\n : undefined\n const hasLocalizedWhere = [...wherePlan.values()].some((pathPlan) => {\n const collectionField = pathPlan.fieldsByCollection.get(collection)\n\n return collectionField?.type === 'scalar' && collectionField.isLocalized\n })\n // Multiple relationship rows can match one target; count and page the document once.\n const shouldDeduplicate =\n Boolean(relationshipTable || arrayJoins?.length) ||\n (hasLocalizedWhere && (!locale || locale === 'all'))\n let collectionQuery = (\n shouldDeduplicate ? db.selectDistinct(selectFields) : db.select(selectFields)\n )\n .from(table)\n .$dynamic()\n\n if (relationshipTable) {\n collectionQuery = collectionQuery.innerJoin(relationshipTable, relationshipRowCondition)\n }\n\n for (const { condition, table: arrayTable } of arrayJoins ?? []) {\n collectionQuery = collectionQuery.innerJoin(arrayTable, condition)\n }\n\n if (hasLocalizedWhere) {\n const localesTable = adapter.tables[`${getTableName(table)}${adapter.localesSuffix}`]\n\n collectionQuery = collectionQuery.leftJoin(\n localesTable,\n and(\n eq(table['id'], localesTable._parentID),\n locale && locale !== 'all' ? eq(localesTable._locale, locale) : undefined,\n ),\n )\n }\n\n // Older versions may contain the same relationship; exclude them before counting and paging.\n if (collectionWhere || shouldUseVersionTable) {\n collectionQuery = collectionQuery.where(\n and(collectionWhere, shouldUseVersionTable ? eq(table['latest'], true) : undefined),\n )\n }\n\n if (unionQuery === null) {\n unionQuery = collectionQuery\n } else {\n unionQuery = unionQuery.unionAll(collectionQuery)\n }\n }\n\n const subQueryAlias = `${columnName}_subquery`\n // A versioned parent has a separate version ID; relationships point at its document ID.\n const parentIDColumn = adapter.tables[currentTableName][versions ? 'parent' : 'id']\n const parentID = sql`${sql.identifier(currentTableName)}.${sql.identifier(parentIDColumn.name)}`\n const parentConstraint = eq(parentID, sql`${sql.identifier(subQueryAlias)}.\"parent\"`)\n const countExpression = shouldCount\n ? sql`${db\n .select({ count: count() })\n .from(sql`${unionQuery.as(subQueryAlias)}`)\n .where(parentConstraint)}`.as(`${columnName}_count`)\n : undefined\n\n const sortedUnionAlias = `${columnName}_sorted`\n let limitOffsetSQL = sql.empty()\n\n if (limit) {\n limitOffsetSQL = sql` LIMIT ${limit}`\n }\n\n if (page && limit !== 0) {\n const offset = (page - 1) * pageSize\n\n if (offset > 0) {\n limitOffsetSQL = sql`${limitOffsetSQL} OFFSET ${offset}`\n }\n }\n\n const parentWhere = eq(sql`${sql.identifier(sortedUnionAlias)}.\"parent\"`, parentID)\n // Sort each parent's rows before limiting; relationTo and ID keep equal sort values stable.\n const documents = sql`(\n SELECT ${jsonAggBuildObject(adapter, {\n id: sql.raw(`\"${subQueryAlias}\".\"id\"`),\n relationTo: sql.raw(`\"${subQueryAlias}\".\"relationTo\"`),\n })}\n FROM (\n SELECT * FROM ${sql`${unionQuery.as(sortedUnionAlias)}`}\n WHERE ${parentWhere}\n order by ${sortOrder(sql`\"sortPath\"`)}, ${asc(sql`\"relationTo\"`)}, ${asc(sql`\"id\"`)}${limitOffsetSQL}\n ) AS ${sql.raw(`\"${subQueryAlias}\"`)}\n )`.as(columnName)\n\n return {\n columnName,\n count: countExpression,\n documents,\n }\n}\n\nconst getSortField = ({\n adapter,\n collections,\n sort,\n}: {\n adapter: DrizzleAdapter\n collections: string[]\n sort?: string\n}): string => {\n if (sort) {\n return sort\n }\n\n const hasCreatedAt = collections.some((collection) =>\n adapter.payload.collections[collection].config.fields.some(\n (field) => field.type === 'date' && field.name === 'createdAt',\n ),\n )\n\n return hasCreatedAt ? '-createdAt' : 'id'\n}\n"],"names":["and","asc","count","desc","eq","getTableName","sql","buildVersionCollectionFields","getFieldByPath","hasDraftsEnabled","toSnakeCase","getTableColumnFromPath","resolveRelationshipPath","jsonAggBuildObject","buildPolymorphicJoinWhere","createPolymorphicJoinWherePlan","buildPolymorphicJoinQuery","adapter","currentTableName","draftsEnabled","field","limit","locale","page","pageSize","parentCollectionSlug","path","shouldCount","sort","versions","where","Array","isArray","collection","Error","length","collections","columnName","replaceAll","name","db","drizzle","collectionTables","map","target","payload","shouldUseVersionTable","Boolean","config","tableName","tableNameMap","get","versionsSuffix","table","tables","undefined","fields","flattenedFields","relationshipFieldPath","on","relationshipField","isRelationshipOrUpload","type","relationTo","relationshipPath","parentIsLocalized","hasMany","relationshipTable","relationshipsSuffix","parentColumn","relationshipLocale","pathSegments","split","isPostgres","relationshipPathPattern","segment","index","arrayPositionIndices","includes","replace","join","expectedDotCount","relationshipPathCondition","relationshipRowCondition","parent","isLocalized","arrayJoins","resolvedColumn","collectionPath","joins","selectFields","value","relationshipColumnName","sortField","getSortField","sortOrder","startsWith","sortPath","wherePlan","Map","unionQuery","collectionTable","versionSortColumnName","sortColumnName","sortColumn","id","as","collectionWhere","Object","keys","hasLocalizedWhere","values","some","pathPlan","collectionField","fieldsByCollection","shouldDeduplicate","collectionQuery","selectDistinct","select","from","$dynamic","innerJoin","condition","arrayTable","localesTable","localesSuffix","leftJoin","_parentID","_locale","unionAll","subQueryAlias","parentIDColumn","parentID","identifier","parentConstraint","countExpression","sortedUnionAlias","limitOffsetSQL","empty","offset","parentWhere","documents","raw","hasCreatedAt"],"mappings":"AAKA,SAASA,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAEC,EAAE,EAAEC,YAAY,EAAEC,GAAG,QAAQ,cAAa;AAC1E,SAASC,4BAA4B,EAAEC,cAAc,QAAQ,UAAS;AACtE,SAASC,gBAAgB,QAAQ,iBAAgB;AACjD,OAAOC,iBAAiB,gBAAe;AAMvC,SAASC,sBAAsB,QAAQ,uCAAsC;AAC7E,SAASC,uBAAuB,QAAQ,wCAAuC;AAC/E,SAASC,kBAAkB,QAAQ,uBAAsB;AACzD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,8BAA8B,QAAQ,sCAAqC;AAyBpF;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMC,4BAA4B,CAAC,EACxCC,OAAO,EACPC,gBAAgB,EAChBC,aAAa,EACbC,KAAK,EACLC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,WAAWH,KAAK,EAChBI,oBAAoB,EACpBC,IAAI,EACJC,WAAW,EACXC,IA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,CAACH,WAAW,CAACe,MAAM,CAACQ,MAAM,CAACwD,IAAI,CACxD,CAAC5F,QAAUA,MAAM0C,IAAI,KAAK,UAAU1C,MAAMmB,IAAI,KAAK;IAIvD,OAAOyG,eAAe,eAAe;AACvC"}
|
|
@@ -6,6 +6,7 @@ type BuildPolymorphicJoinWhereArgs = {
|
|
|
6
6
|
adapter: DrizzleAdapter;
|
|
7
7
|
collection: string;
|
|
8
8
|
locale?: string;
|
|
9
|
+
shouldUseVersionTable?: boolean;
|
|
9
10
|
table: GenericTable;
|
|
10
11
|
where: Where;
|
|
11
12
|
wherePlan: PolymorphicJoinWherePlan;
|
|
@@ -15,6 +16,6 @@ type BuildPolymorphicJoinWhereArgs = {
|
|
|
15
16
|
* that is absent from this collection resolves to SQL NULL, and relationTo resolves to the current
|
|
16
17
|
* collection slug.
|
|
17
18
|
*/
|
|
18
|
-
export declare const buildPolymorphicJoinWhere: ({ adapter, collection, locale, table, where, wherePlan, }: BuildPolymorphicJoinWhereArgs) => SQL | undefined;
|
|
19
|
+
export declare const buildPolymorphicJoinWhere: ({ adapter, collection, locale, shouldUseVersionTable, table, where, wherePlan, }: BuildPolymorphicJoinWhereArgs) => SQL | undefined;
|
|
19
20
|
export {};
|
|
20
21
|
//# sourceMappingURL=buildPolymorphicJoinWhere.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildPolymorphicJoinWhere.d.ts","sourceRoot":"","sources":["../../src/find/buildPolymorphicJoinWhere.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAU,GAAG,EAAE,MAAM,aAAa,CAAA;AAG9C,OAAO,EAAkD,KAAK,KAAK,EAAE,MAAM,SAAS,CAAA;AAIpF,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC/D,OAAO,KAAK,EACV,wBAAwB,EAGzB,MAAM,qCAAqC,CAAA;AAO5C,KAAK,6BAA6B,GAAG;IACnC,OAAO,EAAE,cAAc,CAAA;IACvB,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,YAAY,CAAA;IACnB,KAAK,EAAE,KAAK,CAAA;IACZ,SAAS,EAAE,wBAAwB,CAAA;CACpC,CAAA;AAqBD;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,
|
|
1
|
+
{"version":3,"file":"buildPolymorphicJoinWhere.d.ts","sourceRoot":"","sources":["../../src/find/buildPolymorphicJoinWhere.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAU,GAAG,EAAE,MAAM,aAAa,CAAA;AAG9C,OAAO,EAAkD,KAAK,KAAK,EAAE,MAAM,SAAS,CAAA;AAIpF,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC/D,OAAO,KAAK,EACV,wBAAwB,EAGzB,MAAM,qCAAqC,CAAA;AAO5C,KAAK,6BAA6B,GAAG;IACnC,OAAO,EAAE,cAAc,CAAA;IACvB,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,qBAAqB,CAAC,EAAE,OAAO,CAAA;IAC/B,KAAK,EAAE,YAAY,CAAA;IACnB,KAAK,EAAE,KAAK,CAAA;IACZ,SAAS,EAAE,wBAAwB,CAAA;CACpC,CAAA;AAqBD;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,qFAQnC,6BAA6B,KAAG,GAAG,GAAG,SAwMxC,CAAA"}
|
|
@@ -14,7 +14,7 @@ const supportedJSONQueryOperators = new Set([
|
|
|
14
14
|
* Builds a where clause for one collection before the polymorphic branches are combined. A field
|
|
15
15
|
* that is absent from this collection resolves to SQL NULL, and relationTo resolves to the current
|
|
16
16
|
* collection slug.
|
|
17
|
-
*/ export const buildPolymorphicJoinWhere = ({ adapter, collection, locale, table, where, wherePlan })=>{
|
|
17
|
+
*/ export const buildPolymorphicJoinWhere = ({ adapter, collection, locale, shouldUseVersionTable = false, table, where, wherePlan })=>{
|
|
18
18
|
const constraints = [];
|
|
19
19
|
for(const key in where){
|
|
20
20
|
if ([
|
|
@@ -33,6 +33,7 @@ const supportedJSONQueryOperators = new Set([
|
|
|
33
33
|
adapter,
|
|
34
34
|
collection,
|
|
35
35
|
locale,
|
|
36
|
+
shouldUseVersionTable,
|
|
36
37
|
table,
|
|
37
38
|
where: nestedWhere,
|
|
38
39
|
wherePlan
|
|
@@ -47,6 +48,7 @@ const supportedJSONQueryOperators = new Set([
|
|
|
47
48
|
adapter,
|
|
48
49
|
collection,
|
|
49
50
|
schemaPath: key,
|
|
51
|
+
shouldUseVersionTable,
|
|
50
52
|
table,
|
|
51
53
|
wherePlan
|
|
52
54
|
});
|
|
@@ -206,7 +208,7 @@ const supportedJSONQueryOperators = new Set([
|
|
|
206
208
|
}
|
|
207
209
|
return and(...constraints);
|
|
208
210
|
};
|
|
209
|
-
const resolveWherePath = ({ adapter, collection, schemaPath, table, wherePlan })=>{
|
|
211
|
+
const resolveWherePath = ({ adapter, collection, schemaPath, shouldUseVersionTable, table, wherePlan })=>{
|
|
210
212
|
const pathPlan = wherePlan.get(schemaPath);
|
|
211
213
|
if (!pathPlan) {
|
|
212
214
|
throw new QueryError([
|
|
@@ -253,6 +255,7 @@ const resolveWherePath = ({ adapter, collection, schemaPath, table, wherePlan })
|
|
|
253
255
|
adapter,
|
|
254
256
|
collection,
|
|
255
257
|
pathPlan,
|
|
258
|
+
shouldUseVersionTable,
|
|
256
259
|
table
|
|
257
260
|
}),
|
|
258
261
|
pathPlan
|
|
@@ -269,20 +272,30 @@ const resolveWherePath = ({ adapter, collection, schemaPath, table, wherePlan })
|
|
|
269
272
|
pathPlan
|
|
270
273
|
};
|
|
271
274
|
}
|
|
275
|
+
let column = sql`null`;
|
|
276
|
+
if (fieldContext) {
|
|
277
|
+
const columnName = shouldUseVersionTable ? `version_${pathPlan.columnPath}` : pathPlan.columnPath;
|
|
278
|
+
if (fieldContext.isLocalized) {
|
|
279
|
+
column = adapter.tables[`${getTableName(table)}${adapter.localesSuffix}`][columnName];
|
|
280
|
+
} else {
|
|
281
|
+
const tableColumnName = shouldUseVersionTable && schemaPath === 'id' ? 'parent' : columnName;
|
|
282
|
+
column = table[tableColumnName];
|
|
283
|
+
}
|
|
284
|
+
}
|
|
272
285
|
return {
|
|
273
286
|
type: 'scalar',
|
|
274
|
-
column
|
|
287
|
+
column,
|
|
275
288
|
fieldContext,
|
|
276
289
|
pathPlan,
|
|
277
290
|
queryValueContext
|
|
278
291
|
};
|
|
279
292
|
};
|
|
280
|
-
const getHasManySelectExpression = ({ adapter, collection, pathPlan, table })=>{
|
|
293
|
+
const getHasManySelectExpression = ({ adapter, collection, pathPlan, shouldUseVersionTable, table })=>{
|
|
281
294
|
if (pathPlan.fieldsByCollection.get(collection)?.type !== 'hasManySelect') {
|
|
282
295
|
return adapter.name === 'postgres' ? `'[]'::jsonb` : `'[]'`;
|
|
283
296
|
}
|
|
284
297
|
const selectTablePath = pathPlan.schemaPath.split('.').map((pathSegment)=>toSnakeCase(pathSegment)).join('_');
|
|
285
|
-
const valuesTableName = adapter.tableNameMap.get(`${toSnakeCase(collection)}_${selectTablePath}`);
|
|
298
|
+
const valuesTableName = adapter.tableNameMap.get(shouldUseVersionTable ? `${getTableName(table)}_version_${selectTablePath}` : `${toSnakeCase(collection)}_${selectTablePath}`);
|
|
286
299
|
if (!valuesTableName) {
|
|
287
300
|
throw new Error(`Polymorphic join collection "${collection}" has no value table for "${pathPlan.schemaPath}"`);
|
|
288
301
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/find/buildPolymorphicJoinWhere.ts"],"sourcesContent":["import type { Column, SQL } from 'drizzle-orm'\n\nimport { and, getTableName, isNotNull, isNull, or, sql } from 'drizzle-orm'\nimport { type FlattenedField, type Operator, QueryError, type Where } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleResolvedOperator } from '../queries/operatorMap.js'\nimport type { DrizzleAdapter, GenericTable } from '../types.js'\nimport type {\n PolymorphicJoinWherePlan,\n ScalarWhereField,\n WherePathPlan,\n} from './createPolymorphicJoinWherePlan.js'\n\nimport { buildOperatorConstraint } from '../queries/buildOperatorConstraint.js'\nimport { sanitizeQueryValue } from '../queries/sanitizeQueryValue.js'\n\nconst supportedJSONQueryOperators = new Set(['contains', 'equals', 'exists', 'in', 'like'])\n\ntype BuildPolymorphicJoinWhereArgs = {\n adapter: DrizzleAdapter\n collection: string\n locale?: string\n table: GenericTable\n where: Where\n wherePlan: PolymorphicJoinWherePlan\n}\n\ntype ResolvedWherePath =\n | {\n column: Column | SQL\n fieldContext?: ScalarWhereField\n pathPlan: WherePathPlan\n queryValueContext: ScalarWhereField\n type: 'scalar'\n }\n | {\n fieldContext: FlattenedField\n jsonExpression: string\n pathPlan: WherePathPlan\n type: 'hasManySelect'\n }\n | {\n pathPlan: WherePathPlan\n type: 'invalid'\n }\n\n/**\n * Builds a where clause for one collection before the polymorphic branches are combined. A field\n * that is absent from this collection resolves to SQL NULL, and relationTo resolves to the current\n * collection slug.\n */\nexport const buildPolymorphicJoinWhere = ({\n adapter,\n collection,\n locale,\n table,\n where,\n wherePlan,\n}: BuildPolymorphicJoinWhereArgs): SQL | undefined => {\n const constraints: SQL[] = []\n\n for (const key in where) {\n if (['AND', 'OR'].includes(key.toUpperCase())) {\n if (!Array.isArray(where[key])) {\n throw new QueryError([{ path: key }])\n }\n\n const combine = key.toUpperCase() === 'AND' ? and : or\n const nestedConstraints = where[key].map((nestedWhere) =>\n buildPolymorphicJoinWhere({\n adapter,\n collection,\n locale,\n table,\n where: nestedWhere,\n wherePlan,\n }),\n )\n const nestedCondition = combine(...nestedConstraints)\n\n if (nestedCondition) {\n constraints.push(nestedCondition)\n }\n\n continue\n }\n\n const resolvedPath = resolveWherePath({\n adapter,\n collection,\n schemaPath: key,\n table,\n wherePlan,\n })\n\n for (let payloadOperator of Object.keys(where[key])) {\n const originalOperator = payloadOperator as Operator\n let value = where[key][payloadOperator]\n\n if (resolvedPath.type === 'invalid') {\n throw new QueryError([{ path: `${key}.${payloadOperator}` }])\n }\n\n if (resolvedPath.type === 'hasManySelect') {\n if (!supportedJSONQueryOperators.has(payloadOperator)) {\n throw new QueryError([{ path: `${key}.${payloadOperator}` }])\n }\n\n const sanitizedQueryValue = sanitizeQueryValue({\n adapter,\n field: resolvedPath.fieldContext,\n isUUID: false,\n operator: payloadOperator,\n relationOrPath: key,\n val: value,\n })\n\n if (sanitizedQueryValue === null) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n if (sanitizedQueryValue.columns) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n value = sanitizedQueryValue.value\n\n if (payloadOperator === 'in' && Array.isArray(value) && value.length === 0) {\n constraints.push(sql.raw('false'))\n continue\n }\n\n const jsonQueryOperator =\n payloadOperator === 'exists' ? 'exists' : sanitizedQueryValue.operator\n\n constraints.push(\n sql.raw(\n adapter.createJSONQuery({\n column: resolvedPath.jsonExpression,\n operator: jsonQueryOperator,\n pathSegments: [resolvedPath.pathPlan.columnPath],\n value,\n }),\n ),\n )\n continue\n }\n\n if (payloadOperator === '$raw') {\n if (typeof value !== 'string') {\n throw new QueryError([{ path: `${key}.${payloadOperator}` }])\n }\n\n constraints.push(sql.raw(value))\n continue\n }\n\n const { column, fieldContext, queryValueContext } = resolvedPath\n\n if (\n payloadOperator === 'like' &&\n (queryValueContext.field.type === 'number' ||\n queryValueContext.field.type === 'relationship' ||\n queryValueContext.field.type === 'upload' ||\n queryValueContext.isUUID)\n ) {\n payloadOperator = 'equals'\n }\n\n const sanitizedQueryValue = sanitizeQueryValue({\n adapter,\n field: queryValueContext.field,\n isUUID: queryValueContext.isUUID,\n operator: payloadOperator,\n relationOrPath: key,\n val: value,\n })\n\n if (sanitizedQueryValue === null) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n if (sanitizedQueryValue.columns) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n payloadOperator = sanitizedQueryValue.operator\n value = sanitizedQueryValue.value\n\n if (!(payloadOperator in adapter.operators)) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n const resolvedOperator = payloadOperator as DrizzleResolvedOperator\n const operator = adapter.operators[resolvedOperator]\n const buildColumnConstraint = (constraintValue: unknown) => {\n if (!fieldContext) {\n return operator(column, constraintValue)\n }\n\n return buildOperatorConstraint({\n adapter,\n column,\n field: fieldContext.field,\n locale,\n originalOperator,\n path: key,\n resolvedOperator,\n value: constraintValue,\n })\n }\n\n if (originalOperator === 'equals' && value === null) {\n constraints.push(isNull(column))\n continue\n }\n\n if (originalOperator === 'not_equals') {\n if (value === null) {\n constraints.push(isNotNull(column))\n } else {\n const notEqualsConstraint = or(isNull(column), buildColumnConstraint(value))\n\n if (notEqualsConstraint) {\n constraints.push(notEqualsConstraint)\n }\n }\n continue\n }\n\n if (originalOperator === 'in' && Array.isArray(value) && value.includes(null)) {\n const nonNullValues = value.filter((item) => item !== null)\n const inConstraint = buildColumnConstraint(nonNullValues)\n const nullAwareInConstraint = or(isNull(column), inConstraint)\n\n if (nullAwareInConstraint) {\n constraints.push(nullAwareInConstraint)\n }\n continue\n }\n\n if (payloadOperator === 'like' && typeof value === 'string') {\n const wordConstraints = value.split(' ').map((word) => buildColumnConstraint(`%${word}%`))\n const wordCondition = and(...wordConstraints)\n\n if (wordCondition) {\n constraints.push(wordCondition)\n }\n continue\n }\n\n constraints.push(buildColumnConstraint(value))\n }\n }\n\n return and(...constraints)\n}\n\nconst resolveWherePath = ({\n adapter,\n collection,\n schemaPath,\n table,\n wherePlan,\n}: {\n schemaPath: string\n} & Omit<BuildPolymorphicJoinWhereArgs, 'locale' | 'where'>): ResolvedWherePath => {\n const pathPlan = wherePlan.get(schemaPath)\n\n if (!pathPlan) {\n throw new QueryError([{ path: schemaPath }])\n }\n\n if (pathPlan.type === 'invalid') {\n return { type: 'invalid', pathPlan }\n }\n\n if (schemaPath === 'relationTo') {\n return {\n type: 'scalar',\n column: adapter.name === 'postgres' ? sql`cast(${collection} as text)` : sql`${collection}`,\n pathPlan,\n queryValueContext: {\n type: 'scalar',\n field: { name: 'relationTo', type: 'text' },\n isUUID: false,\n },\n }\n }\n\n if (pathPlan.type === 'hasManySelect') {\n const fieldContext = [...pathPlan.fieldsByCollection.values()].find(\n (field) => field.type === 'hasManySelect',\n )?.field\n\n if (!fieldContext) {\n return { type: 'invalid', pathPlan }\n }\n\n return {\n type: 'hasManySelect',\n fieldContext,\n jsonExpression: getHasManySelectExpression({\n adapter,\n collection,\n pathPlan,\n table,\n }),\n pathPlan,\n }\n }\n\n const collectionField = pathPlan.fieldsByCollection.get(collection)\n const fieldContext = collectionField?.type === 'scalar' ? collectionField : undefined\n const queryValueContext =\n fieldContext ??\n [...pathPlan.fieldsByCollection.values()].find(\n (field): field is ScalarWhereField => field.type === 'scalar',\n )\n\n if (!queryValueContext) {\n return { type: 'invalid', pathPlan }\n }\n\n return {\n type: 'scalar',\n column: fieldContext\n ? fieldContext.isLocalized\n ? adapter.tables[`${getTableName(table)}${adapter.localesSuffix}`][pathPlan.columnPath]\n : table[pathPlan.columnPath]\n : sql`null`,\n fieldContext,\n pathPlan,\n queryValueContext,\n }\n}\n\nconst getHasManySelectExpression = ({\n adapter,\n collection,\n pathPlan,\n table,\n}: {\n adapter: DrizzleAdapter\n collection: string\n pathPlan: WherePathPlan\n table: GenericTable\n}): string => {\n if (pathPlan.fieldsByCollection.get(collection)?.type !== 'hasManySelect') {\n return adapter.name === 'postgres' ? `'[]'::jsonb` : `'[]'`\n }\n\n const selectTablePath = pathPlan.schemaPath\n .split('.')\n .map((pathSegment) => toSnakeCase(pathSegment))\n .join('_')\n const valuesTableName = adapter.tableNameMap.get(`${toSnakeCase(collection)}_${selectTablePath}`)\n\n if (!valuesTableName) {\n throw new Error(\n `Polymorphic join collection \"${collection}\" has no value table for \"${pathPlan.schemaPath}\"`,\n )\n }\n\n let qualifiedValuesTableName = valuesTableName\n let parentTableName = getTableName(table)\n\n if (adapter.schemaName) {\n qualifiedValuesTableName = `\"${adapter.schemaName}\".\"${valuesTableName}\"`\n parentTableName = `\"${adapter.schemaName}\".\"${parentTableName}\"`\n }\n\n if (adapter.name === 'postgres') {\n return `(select coalesce(jsonb_agg(${qualifiedValuesTableName}.value), '[]'::jsonb) from ${qualifiedValuesTableName} where ${qualifiedValuesTableName}.parent_id = ${parentTableName}.id)`\n }\n\n return `(select json_group_array(${qualifiedValuesTableName}.value) from ${qualifiedValuesTableName} where ${qualifiedValuesTableName}.parent_id = ${parentTableName}.id)`\n}\n"],"names":["and","getTableName","isNotNull","isNull","or","sql","QueryError","toSnakeCase","buildOperatorConstraint","sanitizeQueryValue","supportedJSONQueryOperators","Set","buildPolymorphicJoinWhere","adapter","collection","locale","table","where","wherePlan","constraints","key","includes","toUpperCase","Array","isArray","path","combine","nestedConstraints","map","nestedWhere","nestedCondition","push","resolvedPath","resolveWherePath","schemaPath","payloadOperator","Object","keys","originalOperator","value","type","has","sanitizedQueryValue","field","fieldContext","isUUID","operator","relationOrPath","val","columns","length","raw","jsonQueryOperator","createJSONQuery","column","jsonExpression","pathSegments","pathPlan","columnPath","queryValueContext","operators","resolvedOperator","buildColumnConstraint","constraintValue","notEqualsConstraint","nonNullValues","filter","item","inConstraint","nullAwareInConstraint","wordConstraints","split","word","wordCondition","get","name","fieldsByCollection","values","find","getHasManySelectExpression","collectionField","undefined","isLocalized","tables","localesSuffix","selectTablePath","pathSegment","join","valuesTableName","tableNameMap","Error","qualifiedValuesTableName","parentTableName","schemaName"],"mappings":"AAEA,SAASA,GAAG,EAAEC,YAAY,EAAEC,SAAS,EAAEC,MAAM,EAAEC,EAAE,EAAEC,GAAG,QAAQ,cAAa;AAC3E,SAA6CC,UAAU,QAAoB,UAAS;AACpF,OAAOC,iBAAiB,gBAAe;AAUvC,SAASC,uBAAuB,QAAQ,wCAAuC;AAC/E,SAASC,kBAAkB,QAAQ,mCAAkC;AAErE,MAAMC,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O,EAAEA,yBAAyB,aAAa,EAAEC,gBAAgB,IAAI,CAAC;AAC5K"}
|
|
1
|
+
{"version":3,"sources":["../../src/find/buildPolymorphicJoinWhere.ts"],"sourcesContent":["import type { Column, SQL } from 'drizzle-orm'\n\nimport { and, getTableName, isNotNull, isNull, or, sql } from 'drizzle-orm'\nimport { type FlattenedField, type Operator, QueryError, type Where } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleResolvedOperator } from '../queries/operatorMap.js'\nimport type { DrizzleAdapter, GenericTable } from '../types.js'\nimport type {\n PolymorphicJoinWherePlan,\n ScalarWhereField,\n WherePathPlan,\n} from './createPolymorphicJoinWherePlan.js'\n\nimport { buildOperatorConstraint } from '../queries/buildOperatorConstraint.js'\nimport { sanitizeQueryValue } from '../queries/sanitizeQueryValue.js'\n\nconst supportedJSONQueryOperators = new Set(['contains', 'equals', 'exists', 'in', 'like'])\n\ntype BuildPolymorphicJoinWhereArgs = {\n adapter: DrizzleAdapter\n collection: string\n locale?: string\n shouldUseVersionTable?: boolean\n table: GenericTable\n where: Where\n wherePlan: PolymorphicJoinWherePlan\n}\n\ntype ResolvedWherePath =\n | {\n column: Column | SQL\n fieldContext?: ScalarWhereField\n pathPlan: WherePathPlan\n queryValueContext: ScalarWhereField\n type: 'scalar'\n }\n | {\n fieldContext: FlattenedField\n jsonExpression: string\n pathPlan: WherePathPlan\n type: 'hasManySelect'\n }\n | {\n pathPlan: WherePathPlan\n type: 'invalid'\n }\n\n/**\n * Builds a where clause for one collection before the polymorphic branches are combined. A field\n * that is absent from this collection resolves to SQL NULL, and relationTo resolves to the current\n * collection slug.\n */\nexport const buildPolymorphicJoinWhere = ({\n adapter,\n collection,\n locale,\n shouldUseVersionTable = false,\n table,\n where,\n wherePlan,\n}: BuildPolymorphicJoinWhereArgs): SQL | undefined => {\n const constraints: SQL[] = []\n\n for (const key in where) {\n if (['AND', 'OR'].includes(key.toUpperCase())) {\n if (!Array.isArray(where[key])) {\n throw new QueryError([{ path: key }])\n }\n\n const combine = key.toUpperCase() === 'AND' ? and : or\n const nestedConstraints = where[key].map((nestedWhere) =>\n buildPolymorphicJoinWhere({\n adapter,\n collection,\n locale,\n shouldUseVersionTable,\n table,\n where: nestedWhere,\n wherePlan,\n }),\n )\n const nestedCondition = combine(...nestedConstraints)\n\n if (nestedCondition) {\n constraints.push(nestedCondition)\n }\n\n continue\n }\n\n const resolvedPath = resolveWherePath({\n adapter,\n collection,\n schemaPath: key,\n shouldUseVersionTable,\n table,\n wherePlan,\n })\n\n for (let payloadOperator of Object.keys(where[key])) {\n const originalOperator = payloadOperator as Operator\n let value = where[key][payloadOperator]\n\n if (resolvedPath.type === 'invalid') {\n throw new QueryError([{ path: `${key}.${payloadOperator}` }])\n }\n\n if (resolvedPath.type === 'hasManySelect') {\n if (!supportedJSONQueryOperators.has(payloadOperator)) {\n throw new QueryError([{ path: `${key}.${payloadOperator}` }])\n }\n\n const sanitizedQueryValue = sanitizeQueryValue({\n adapter,\n field: resolvedPath.fieldContext,\n isUUID: false,\n operator: payloadOperator,\n relationOrPath: key,\n val: value,\n })\n\n if (sanitizedQueryValue === null) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n if (sanitizedQueryValue.columns) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n value = sanitizedQueryValue.value\n\n if (payloadOperator === 'in' && Array.isArray(value) && value.length === 0) {\n constraints.push(sql.raw('false'))\n continue\n }\n\n const jsonQueryOperator =\n payloadOperator === 'exists' ? 'exists' : sanitizedQueryValue.operator\n\n constraints.push(\n sql.raw(\n adapter.createJSONQuery({\n column: resolvedPath.jsonExpression,\n operator: jsonQueryOperator,\n pathSegments: [resolvedPath.pathPlan.columnPath],\n value,\n }),\n ),\n )\n continue\n }\n\n if (payloadOperator === '$raw') {\n if (typeof value !== 'string') {\n throw new QueryError([{ path: `${key}.${payloadOperator}` }])\n }\n\n constraints.push(sql.raw(value))\n continue\n }\n\n const { column, fieldContext, queryValueContext } = resolvedPath\n\n if (\n payloadOperator === 'like' &&\n (queryValueContext.field.type === 'number' ||\n queryValueContext.field.type === 'relationship' ||\n queryValueContext.field.type === 'upload' ||\n queryValueContext.isUUID)\n ) {\n payloadOperator = 'equals'\n }\n\n const sanitizedQueryValue = sanitizeQueryValue({\n adapter,\n field: queryValueContext.field,\n isUUID: queryValueContext.isUUID,\n operator: payloadOperator,\n relationOrPath: key,\n val: value,\n })\n\n if (sanitizedQueryValue === null) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n if (sanitizedQueryValue.columns) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n payloadOperator = sanitizedQueryValue.operator\n value = sanitizedQueryValue.value\n\n if (!(payloadOperator in adapter.operators)) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n const resolvedOperator = payloadOperator as DrizzleResolvedOperator\n const operator = adapter.operators[resolvedOperator]\n const buildColumnConstraint = (constraintValue: unknown) => {\n if (!fieldContext) {\n return operator(column, constraintValue)\n }\n\n return buildOperatorConstraint({\n adapter,\n column,\n field: fieldContext.field,\n locale,\n originalOperator,\n path: key,\n resolvedOperator,\n value: constraintValue,\n })\n }\n\n if (originalOperator === 'equals' && value === null) {\n constraints.push(isNull(column))\n continue\n }\n\n if (originalOperator === 'not_equals') {\n if (value === null) {\n constraints.push(isNotNull(column))\n } else {\n const notEqualsConstraint = or(isNull(column), buildColumnConstraint(value))\n\n if (notEqualsConstraint) {\n constraints.push(notEqualsConstraint)\n }\n }\n continue\n }\n\n if (originalOperator === 'in' && Array.isArray(value) && value.includes(null)) {\n const nonNullValues = value.filter((item) => item !== null)\n const inConstraint = buildColumnConstraint(nonNullValues)\n const nullAwareInConstraint = or(isNull(column), inConstraint)\n\n if (nullAwareInConstraint) {\n constraints.push(nullAwareInConstraint)\n }\n continue\n }\n\n if (payloadOperator === 'like' && typeof value === 'string') {\n const wordConstraints = value.split(' ').map((word) => buildColumnConstraint(`%${word}%`))\n const wordCondition = and(...wordConstraints)\n\n if (wordCondition) {\n constraints.push(wordCondition)\n }\n continue\n }\n\n constraints.push(buildColumnConstraint(value))\n }\n }\n\n return and(...constraints)\n}\n\nconst resolveWherePath = ({\n adapter,\n collection,\n schemaPath,\n shouldUseVersionTable,\n table,\n wherePlan,\n}: {\n schemaPath: string\n} & Omit<BuildPolymorphicJoinWhereArgs, 'locale' | 'where'>): ResolvedWherePath => {\n const pathPlan = wherePlan.get(schemaPath)\n\n if (!pathPlan) {\n throw new QueryError([{ path: schemaPath }])\n }\n\n if (pathPlan.type === 'invalid') {\n return { type: 'invalid', pathPlan }\n }\n\n if (schemaPath === 'relationTo') {\n return {\n type: 'scalar',\n column: adapter.name === 'postgres' ? sql`cast(${collection} as text)` : sql`${collection}`,\n pathPlan,\n queryValueContext: {\n type: 'scalar',\n field: { name: 'relationTo', type: 'text' },\n isUUID: false,\n },\n }\n }\n\n if (pathPlan.type === 'hasManySelect') {\n const fieldContext = [...pathPlan.fieldsByCollection.values()].find(\n (field) => field.type === 'hasManySelect',\n )?.field\n\n if (!fieldContext) {\n return { type: 'invalid', pathPlan }\n }\n\n return {\n type: 'hasManySelect',\n fieldContext,\n jsonExpression: getHasManySelectExpression({\n adapter,\n collection,\n pathPlan,\n shouldUseVersionTable,\n table,\n }),\n pathPlan,\n }\n }\n\n const collectionField = pathPlan.fieldsByCollection.get(collection)\n const fieldContext = collectionField?.type === 'scalar' ? collectionField : undefined\n const queryValueContext =\n fieldContext ??\n [...pathPlan.fieldsByCollection.values()].find(\n (field): field is ScalarWhereField => field.type === 'scalar',\n )\n\n if (!queryValueContext) {\n return { type: 'invalid', pathPlan }\n }\n\n let column: Column | SQL = sql`null`\n\n if (fieldContext) {\n const columnName = shouldUseVersionTable\n ? `version_${pathPlan.columnPath}`\n : pathPlan.columnPath\n\n if (fieldContext.isLocalized) {\n column = adapter.tables[`${getTableName(table)}${adapter.localesSuffix}`][columnName]\n } else {\n const tableColumnName = shouldUseVersionTable && schemaPath === 'id' ? 'parent' : columnName\n\n column = table[tableColumnName]\n }\n }\n\n return {\n type: 'scalar',\n column,\n fieldContext,\n pathPlan,\n queryValueContext,\n }\n}\n\nconst getHasManySelectExpression = ({\n adapter,\n collection,\n pathPlan,\n shouldUseVersionTable,\n table,\n}: {\n adapter: DrizzleAdapter\n collection: string\n pathPlan: WherePathPlan\n shouldUseVersionTable?: boolean\n table: GenericTable\n}): string => {\n if (pathPlan.fieldsByCollection.get(collection)?.type !== 'hasManySelect') {\n return adapter.name === 'postgres' ? `'[]'::jsonb` : `'[]'`\n }\n\n const selectTablePath = pathPlan.schemaPath\n .split('.')\n .map((pathSegment) => toSnakeCase(pathSegment))\n .join('_')\n const valuesTableName = adapter.tableNameMap.get(\n shouldUseVersionTable\n ? `${getTableName(table)}_version_${selectTablePath}`\n : `${toSnakeCase(collection)}_${selectTablePath}`,\n )\n\n if (!valuesTableName) {\n throw new Error(\n `Polymorphic join collection \"${collection}\" has no value table for \"${pathPlan.schemaPath}\"`,\n )\n }\n\n let qualifiedValuesTableName = valuesTableName\n let parentTableName = getTableName(table)\n\n if (adapter.schemaName) {\n qualifiedValuesTableName = `\"${adapter.schemaName}\".\"${valuesTableName}\"`\n parentTableName = `\"${adapter.schemaName}\".\"${parentTableName}\"`\n }\n\n if (adapter.name === 'postgres') {\n return `(select coalesce(jsonb_agg(${qualifiedValuesTableName}.value), '[]'::jsonb) from ${qualifiedValuesTableName} where ${qualifiedValuesTableName}.parent_id = ${parentTableName}.id)`\n }\n\n return `(select json_group_array(${qualifiedValuesTableName}.value) from ${qualifiedValuesTableName} where ${qualifiedValuesTableName}.parent_id = ${parentTableName}.id)`\n}\n"],"names":["and","getTableName","isNotNull","isNull","or","sql","QueryError","toSnakeCase","buildOperatorConstraint","sanitizeQueryValue","supportedJSONQueryOperators","Set","buildPolymorphicJoinWhere","adapter","collection","locale","shouldUseVersionTable","table","where","wherePlan","constraints","key","includes","toUpperCase","Array","isArray","path","combine","nestedConstraints","map","nestedWhere","nestedCondition","push","resolvedPath","resolveWherePath","schemaPath","payloadOperator","Object","keys","originalOperator","value","type","has","sanitizedQueryValue","field","fieldContext","isUUID","operator","relationOrPath","val","columns","length","raw","jsonQueryOperator","createJSONQuery","column","jsonExpression","pathSegments","pathPlan","columnPath","queryValueContext","operators","resolvedOperator","buildColumnConstraint","constraintValue","notEqualsConstraint","nonNullValues","filter","item","inConstraint","nullAwareInConstraint","wordConstraints","split","word","wordCondition","get","name","fieldsByCollection","values","find","getHasManySelectExpression","collectionField","undefined","columnName","isLocalized","tables","localesSuffix","tableColumnName","selectTablePath","pathSegment","join","valuesTableName","tableNameMap","Error","qualifiedValuesTableName","parentTableName","schemaName"],"mappings":"AAEA,SAASA,GAAG,EAAEC,YAAY,EAAEC,SAAS,EAAEC,MAAM,EAAEC,EAAE,EAAEC,GAAG,QAAQ,cAAa;AAC3E,SAA6CC,UAAU,QAAoB,UAAS;AACpF,OAAOC,iBAAiB,gBAAe;AAUvC,SAASC,uBAAuB,QAAQ,wCAAuC;AAC/E,SAASC,kBAAkB,QAAQ,mCAAkC;AAErE,MAAMC,8BAA8B,IAAIC,IAAI;IAAC;IAAY;IAAU;IAAU;IAAM;CAAO;AA+B1F;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B,CAAC,EACxCC,OAAO,EACPC,UAAU,EACVC,MAAM,EACNC,wBAAwB,KAAK,EAC7BC,KAAK,EACLC,KAAK,EACLC,SAAS,EACqB;IAC9B,MAAMC,cAAqB,EAAE;IAE7B,IAAK,MAAMC,OAAOH,MAAO;QACvB,IAAI;YAAC;YAAO;SAAK,CAACI,QAAQ,CAACD,IAAIE,WAAW,KAAK;YAC7C,IAAI,CAACC,MAAMC,OAAO,CAACP,KAAK,CAACG,IAAI,GAAG;gBAC9B,MAAM,IAAIf,WAAW;oBAAC;wBAAEoB,MAAML;oBAAI;iBAAE;YACtC;YAEA,MAAMM,UAAUN,IAAIE,WAAW,OAAO,QAAQvB,MAAMI;YACpD,MAAMwB,oBAAo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
|
@@ -254,14 +254,17 @@ export const traverseFields = ({ _locales, adapter, collectionSlug, currentArgs,
|
|
|
254
254
|
const polymorphicJoinQuery = buildPolymorphicJoinQuery({
|
|
255
255
|
adapter,
|
|
256
256
|
currentTableName,
|
|
257
|
+
draftsEnabled,
|
|
257
258
|
field,
|
|
258
259
|
limit,
|
|
259
260
|
locale,
|
|
260
261
|
page,
|
|
261
262
|
pageSize: limitArg,
|
|
263
|
+
parentCollectionSlug: collectionSlug,
|
|
262
264
|
path,
|
|
263
265
|
shouldCount,
|
|
264
266
|
sort,
|
|
267
|
+
versions,
|
|
265
268
|
where
|
|
266
269
|
});
|
|
267
270
|
currentArgs.extras[polymorphicJoinQuery.columnName] = polymorphicJoinQuery.documents;
|