Skip to content

Commit 8af00f2

Browse files
authored
fix: join field works on collections with versions enabled (#8715)
- Fixes errors with drizzle when building the schema #8680 - Adds `joins` to `db.queryDrafts` to have them when doing `.find` with `draft: true`
1 parent 4c396c7 commit 8af00f2

File tree

19 files changed

+340
-195
lines changed

19 files changed

+340
-195
lines changed

packages/db-mongodb/src/queryDrafts.ts

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,23 @@ import { combineQueries, flattenWhereToOperators } from 'payload'
66
import type { MongooseAdapter } from './index.js'
77

88
import { buildSortParam } from './queries/buildSortParam.js'
9+
import { buildJoinAggregation } from './utilities/buildJoinAggregation.js'
910
import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js'
1011
import { withSession } from './withSession.js'
1112

1213
export const queryDrafts: QueryDrafts = async function queryDrafts(
1314
this: MongooseAdapter,
14-
{ collection, limit, locale, page, pagination, req = {} as PayloadRequest, sort: sortArg, where },
15+
{
16+
collection,
17+
joins,
18+
limit,
19+
locale,
20+
page,
21+
pagination,
22+
req = {} as PayloadRequest,
23+
sort: sortArg,
24+
where,
25+
},
1526
) {
1627
const VersionModel = this.versions[collection]
1728
const collectionConfig = this.payload.collections[collection].config
@@ -89,7 +100,29 @@ export const queryDrafts: QueryDrafts = async function queryDrafts(
89100
paginationOptions.options.limit = limit
90101
}
91102

92-
const result = await VersionModel.paginate(versionQuery, paginationOptions)
103+
let result
104+
105+
const aggregate = await buildJoinAggregation({
106+
adapter: this,
107+
collection,
108+
collectionConfig,
109+
joins,
110+
limit,
111+
locale,
112+
query: versionQuery,
113+
versions: true,
114+
})
115+
116+
// build join aggregation
117+
if (aggregate) {
118+
result = await VersionModel.aggregatePaginate(
119+
VersionModel.aggregate(aggregate),
120+
paginationOptions,
121+
)
122+
} else {
123+
result = await VersionModel.paginate(versionQuery, paginationOptions)
124+
}
125+
93126
const docs = JSON.parse(JSON.stringify(result.docs))
94127

95128
return {

packages/db-mongodb/src/utilities/buildJoinAggregation.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ type BuildJoinAggregationArgs = {
1515
locale: string
1616
// the where clause for the top collection
1717
query?: Where
18+
/** whether the query is from drafts */
19+
versions?: boolean
1820
}
1921

2022
export const buildJoinAggregation = async ({
@@ -25,6 +27,7 @@ export const buildJoinAggregation = async ({
2527
limit,
2628
locale,
2729
query,
30+
versions,
2831
}: BuildJoinAggregationArgs): Promise<PipelineStage[] | undefined> => {
2932
if (Object.keys(collectionConfig.joins).length === 0 || joins === false) {
3033
return
@@ -90,15 +93,15 @@ export const buildJoinAggregation = async ({
9093

9194
if (adapter.payload.config.localization && locale === 'all') {
9295
adapter.payload.config.localization.localeCodes.forEach((code) => {
93-
const as = `${join.schemaPath}${code}`
96+
const as = `${versions ? `version.${join.schemaPath}` : join.schemaPath}${code}`
9497

9598
aggregate.push(
9699
{
97100
$lookup: {
98101
as: `${as}.docs`,
99102
foreignField: `${join.field.on}${code}`,
100103
from: slug,
101-
localField: '_id',
104+
localField: versions ? 'parent' : '_id',
102105
pipeline,
103106
},
104107
},
@@ -131,15 +134,15 @@ export const buildJoinAggregation = async ({
131134
} else {
132135
const localeSuffix =
133136
join.field.localized && adapter.payload.config.localization && locale ? `.${locale}` : ''
134-
const as = `${join.schemaPath}${localeSuffix}`
137+
const as = `${versions ? `version.${join.schemaPath}` : join.schemaPath}${localeSuffix}`
135138

136139
aggregate.push(
137140
{
138141
$lookup: {
139142
as: `${as}.docs`,
140143
foreignField: `${join.field.on}${localeSuffix}`,
141144
from: slug,
142-
localField: '_id',
145+
localField: versions ? 'parent' : '_id',
143146
pipeline,
144147
},
145148
},

packages/db-sqlite/src/init.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,6 @@ export const init: Init = async function init(this: SQLiteAdapter) {
7070
disableNotNull: !!collection?.versions?.drafts,
7171
disableUnique: false,
7272
fields: collection.fields,
73-
joins: collection.joins,
7473
locales,
7574
tableName,
7675
timestamps: collection.timestamps,

packages/db-sqlite/src/schema/build.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,6 @@ type Args = {
6161
disableRelsTableUnique?: boolean
6262
disableUnique: boolean
6363
fields: Field[]
64-
joins?: SanitizedJoins
6564
locales?: [string, ...string[]]
6665
rootRelationships?: Set<string>
6766
rootRelationsToBuild?: RelationMap
@@ -95,7 +94,6 @@ export const buildTable = ({
9594
disableRelsTableUnique,
9695
disableUnique = false,
9796
fields,
98-
joins,
9997
locales,
10098
rootRelationships,
10199
rootRelationsToBuild,
@@ -144,7 +142,6 @@ export const buildTable = ({
144142
disableUnique,
145143
fields,
146144
indexes,
147-
joins,
148145
locales,
149146
localesColumns,
150147
localesIndexes,

packages/db-sqlite/src/schema/traverseFields.ts

Lines changed: 0 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ type Args = {
4444
fields: (Field | TabAsField)[]
4545
forceLocalized?: boolean
4646
indexes: Record<string, (cols: GenericColumns) => IndexBuilder>
47-
joins?: SanitizedJoins
4847
locales: [string, ...string[]]
4948
localesColumns: Record<string, SQLiteColumnBuilder>
5049
localesIndexes: Record<string, (cols: GenericColumns) => IndexBuilder>
@@ -84,7 +83,6 @@ export const traverseFields = ({
8483
fields,
8584
forceLocalized,
8685
indexes,
87-
joins,
8886
locales,
8987
localesColumns,
9088
localesIndexes,
@@ -669,7 +667,6 @@ export const traverseFields = ({
669667
fields: field.fields,
670668
forceLocalized,
671669
indexes,
672-
joins,
673670
locales,
674671
localesColumns,
675672
localesIndexes,
@@ -725,7 +722,6 @@ export const traverseFields = ({
725722
fields: field.fields,
726723
forceLocalized: field.localized,
727724
indexes,
728-
joins,
729725
locales,
730726
localesColumns,
731727
localesIndexes,
@@ -782,7 +778,6 @@ export const traverseFields = ({
782778
fields: field.tabs.map((tab) => ({ ...tab, type: 'tab' })),
783779
forceLocalized,
784780
indexes,
785-
joins,
786781
locales,
787782
localesColumns,
788783
localesIndexes,
@@ -839,7 +834,6 @@ export const traverseFields = ({
839834
fields: field.fields,
840835
forceLocalized,
841836
indexes,
842-
joins,
843837
locales,
844838
localesColumns,
845839
localesIndexes,
@@ -937,30 +931,6 @@ export const traverseFields = ({
937931

938932
break
939933

940-
case 'join': {
941-
// fieldName could be 'posts' or 'group_posts'
942-
// using `on` as the key for the relation
943-
const localized = adapter.payload.config.localization && field.localized
944-
const fieldSchemaPath = `${fieldPrefix || ''}${field.name}`
945-
let target: string
946-
const joinConfig = joins[field.collection].find(
947-
({ schemaPath }) => fieldSchemaPath === schemaPath,
948-
)
949-
if (joinConfig.targetField.hasMany) {
950-
target = `${adapter.tableNameMap.get(toSnakeCase(field.collection))}${adapter.relationshipsSuffix}`
951-
} else {
952-
target = `${adapter.tableNameMap.get(toSnakeCase(field.collection))}${localized ? adapter.localesSuffix : ''}`
953-
}
954-
relationsToBuild.set(fieldName, {
955-
type: 'many',
956-
// joins are not localized on the parent table
957-
localized: false,
958-
relationName: field.on.replaceAll('.', '_'),
959-
target,
960-
})
961-
break
962-
}
963-
964934
default:
965935
break
966936
}

packages/drizzle/src/find/buildFindManyArgs.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type BuildFindQueryArgs = {
1616
joins?: BuildQueryJoinAliases
1717
locale?: string
1818
tableName: string
19+
versions?: boolean
1920
}
2021

2122
export type Result = {
@@ -34,6 +35,7 @@ export const buildFindManyArgs = ({
3435
joins = [],
3536
locale,
3637
tableName,
38+
versions,
3739
}: BuildFindQueryArgs): Record<string, unknown> => {
3840
const result: Result = {
3941
extras: {},
@@ -97,6 +99,7 @@ export const buildFindManyArgs = ({
9799
tablePath: '',
98100
topLevelArgs: result,
99101
topLevelTableName: tableName,
102+
versions,
100103
})
101104

102105
return result

packages/drizzle/src/find/findMany.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ type Args = {
1414
adapter: DrizzleAdapter
1515
fields: Field[]
1616
tableName: string
17+
versions?: boolean
1718
} & Omit<FindArgs, 'collection'>
1819

1920
export const findMany = async function find({
@@ -28,6 +29,7 @@ export const findMany = async function find({
2829
skip,
2930
sort,
3031
tableName,
32+
versions,
3133
where: whereArg,
3234
}: Args) {
3335
const db = adapter.sessions[await req.transactionID]?.db || adapter.drizzle
@@ -71,6 +73,7 @@ export const findMany = async function find({
7173
joinQuery,
7274
joins,
7375
tableName,
76+
versions,
7477
})
7578

7679
selectDistinctMethods.push({ args: [offset], method: 'offset' })

0 commit comments

Comments
 (0)