@payloadcms/drizzle 4.0.0-internal.934870d → 4.0.0-internal.970009e

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.
Files changed (34) hide show
  1. package/dist/find/buildPolymorphicJoinQuery.d.ts +3 -2
  2. package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -1
  3. package/dist/find/buildPolymorphicJoinQuery.js +16 -5
  4. package/dist/find/buildPolymorphicJoinQuery.js.map +1 -1
  5. package/dist/find/buildPolymorphicJoinWhere.js +1 -1
  6. package/dist/find/buildPolymorphicJoinWhere.js.map +1 -1
  7. package/dist/find/createPolymorphicJoinWherePlan.d.ts +2 -1
  8. package/dist/find/createPolymorphicJoinWherePlan.d.ts.map +1 -1
  9. package/dist/find/createPolymorphicJoinWherePlan.js +14 -5
  10. package/dist/find/createPolymorphicJoinWherePlan.js.map +1 -1
  11. package/dist/find/traverseFields.d.ts.map +1 -1
  12. package/dist/find/traverseFields.js +1 -0
  13. package/dist/find/traverseFields.js.map +1 -1
  14. package/dist/schema/build.js +3 -3
  15. package/dist/schema/build.js.map +1 -1
  16. package/dist/sqlite/execute.js.map +1 -1
  17. package/dist/transform/read/traverseFields.js.map +1 -1
  18. package/dist/types.d.ts.map +1 -1
  19. package/dist/types.js.map +1 -1
  20. package/dist/upsertRow/index.js.map +1 -1
  21. package/dist/utilities/blocksToJsonMigrator.d.ts.map +1 -1
  22. package/dist/utilities/blocksToJsonMigrator.js +6 -17
  23. package/dist/utilities/blocksToJsonMigrator.js.map +1 -1
  24. package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
  25. package/dist/utilities/createSchemaGenerator.js +7 -12
  26. package/dist/utilities/createSchemaGenerator.js.map +1 -1
  27. package/dist/utilities/executeSchemaHooks.js +1 -1
  28. package/dist/utilities/executeSchemaHooks.js.map +1 -1
  29. package/dist/utilities/formatGeneratedFile.d.ts +10 -0
  30. package/dist/utilities/formatGeneratedFile.d.ts.map +1 -0
  31. package/dist/utilities/formatGeneratedFile.js +58 -0
  32. package/dist/utilities/formatGeneratedFile.js.map +1 -0
  33. package/dist/utilities/getTransaction.js.map +1 -1
  34. package/package.json +16 -19
@@ -8,6 +8,7 @@ type BuildPolymorphicJoinQueryArgs = {
8
8
  limit: number;
9
9
  locale?: string;
10
10
  page?: number;
11
+ pageSize?: number;
11
12
  path: string;
12
13
  shouldCount: boolean;
13
14
  sort?: string | string[];
@@ -26,13 +27,13 @@ type PolymorphicJoinQuery = {
26
27
  *
27
28
  * `field.collection` must contain at least one configured collection. Each mapped table must have
28
29
  * an `id` column and the column named by `field.on`. The supplied `limit` is used as-is; callers can
29
- * include an extra look-ahead row when they calculate pagination.
30
+ * include an extra look-ahead row and supply the original `pageSize` for offset calculation.
30
31
  *
31
32
  * @returns The stable projection name, the document projection, and the count projection when
32
33
  * `shouldCount` is true.
33
34
  * @throws If the join definition, target collection, mapped table, required columns, or sort shape
34
35
  * cannot be represented by the polymorphic query.
35
36
  */
36
- export declare const buildPolymorphicJoinQuery: ({ adapter, currentTableName, field, limit, locale, page, path, shouldCount, sort, where, }: BuildPolymorphicJoinQueryArgs) => PolymorphicJoinQuery;
37
+ export declare const buildPolymorphicJoinQuery: ({ adapter, currentTableName, field, limit, locale, page, pageSize, path, shouldCount, sort, where, }: BuildPolymorphicJoinQueryArgs) => PolymorphicJoinQuery;
37
38
  export {};
38
39
  //# 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;AAKtC,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,KAAK,EAAE,MAAM,SAAS,CAAA;AAG7D,OAAO,KAAK,EAAE,cAAc,EAAgB,MAAM,aAAa,CAAA;AAO/D,KAAK,6BAA6B,GAAG;IAC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,MAAM,GAAG,MAAM,EAAE,CAAA;IACxB,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,yGAYnC,6BAA6B,KAAG,oBAmJlC,CAAA"}
@@ -1,4 +1,4 @@
1
- import { asc, count, desc, eq, sql } from 'drizzle-orm';
1
+ import { and, asc, count, desc, eq, getTableName, sql } from 'drizzle-orm';
2
2
  import toSnakeCase from 'to-snake-case';
3
3
  import { jsonAggBuildObject } from '../utilities/json.js';
4
4
  import { buildPolymorphicJoinWhere } from './buildPolymorphicJoinWhere.js';
@@ -11,13 +11,13 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
11
11
  *
12
12
  * `field.collection` must contain at least one configured collection. Each mapped table must have
13
13
  * an `id` column and the column named by `field.on`. The supplied `limit` is used as-is; callers can
14
- * include an extra look-ahead row when they calculate pagination.
14
+ * include an extra look-ahead row and supply the original `pageSize` for offset calculation.
15
15
  *
16
16
  * @returns The stable projection name, the document projection, and the count projection when
17
17
  * `shouldCount` is true.
18
18
  * @throws If the join definition, target collection, mapped table, required columns, or sort shape
19
19
  * cannot be represented by the polymorphic query.
20
- */ export const buildPolymorphicJoinQuery = ({ adapter, currentTableName, field, limit, locale, page, path, shouldCount, sort, where })=>{
20
+ */ export const buildPolymorphicJoinQuery = ({ adapter, currentTableName, field, limit, locale, page, pageSize = limit, path, shouldCount, sort, where })=>{
21
21
  if (!Array.isArray(field.collection)) {
22
22
  throw new Error('A polymorphic join requires a collection array');
23
23
  }
@@ -80,7 +80,18 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
80
80
  where,
81
81
  wherePlan
82
82
  }) : undefined;
83
- let collectionQuery = db.select(selectFields).from(table).$dynamic();
83
+ const hasLocalizedWhere = [
84
+ ...wherePlan.values()
85
+ ].some((pathPlan)=>{
86
+ const collectionField = pathPlan.fieldsByCollection.get(collection);
87
+ return collectionField?.type === 'scalar' && collectionField.isLocalized;
88
+ });
89
+ const shouldDeduplicate = hasLocalizedWhere && (!locale || locale === 'all');
90
+ let collectionQuery = (shouldDeduplicate ? db.selectDistinct(selectFields) : db.select(selectFields)).from(table).$dynamic();
91
+ if (hasLocalizedWhere) {
92
+ const localesTable = adapter.tables[`${getTableName(table)}${adapter.localesSuffix}`];
93
+ collectionQuery = collectionQuery.leftJoin(localesTable, and(eq(table['id'], localesTable._parentID), locale && locale !== 'all' ? eq(localesTable._locale, locale) : undefined));
94
+ }
84
95
  if (collectionWhere) {
85
96
  collectionQuery = collectionQuery.where(collectionWhere);
86
97
  }
@@ -102,7 +113,7 @@ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan
102
113
  limitOffsetSQL = sql` LIMIT ${limit}`;
103
114
  }
104
115
  if (page && limit !== 0) {
105
- const offset = (page - 1) * limit;
116
+ const offset = (page - 1) * pageSize;
106
117
  if (offset > 0) {
107
118
  limitOffsetSQL = sql`${limitOffsetSQL} OFFSET ${offset}`;
108
119
  }
@@ -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 { asc, count, desc, eq, 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 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 when they calculate pagination.\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 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 let collectionQuery = db.select(selectFields).from(table).$dynamic()\n\n if (collectionWhere) {\n collectionQuery = collectionQuery.where(collectionWhere)\n }\n\n if (unionQuery === null) {\n unionQuery = collectionQuery as unknown as SQLiteSelect\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) * limit\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":["asc","count","desc","eq","sql","toSnakeCase","jsonAggBuildObject","buildPolymorphicJoinWhere","createPolymorphicJoinWherePlan","buildPolymorphicJoinQuery","adapter","currentTableName","field","limit","locale","page","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","collectionQuery","select","from","$dynamic","unionAll","subQueryAlias","parentConstraint","raw","countExpression","orderBy","sortedUnionAlias","limitOffsetSQL","empty","offset","parentWhere","documents","hasCreatedAt","some","config","fields","type"],"mappings":"AAIA,SAASA,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAEC,EAAE,EAAEC,GAAG,QAAQ,cAAa;AAEvD,OAAOC,iBAAi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E,GAAG,CAAC,CAAC,CAAC,EAAEF,cAAc,MAAM,CAAC;QACrCT,YAAYtD,IAAIiE,GAAG,CAAC,CAAC,CAAC,EAAEF,cAAc,cAAc,CAAC;IACvD,GAAG;;oBAEa,EAAE/D,GAAG,CAAC,EAAEgD,WAAWK,EAAE,CAACe,kBAAkB,CAAC,CAAC;YAClD,EAAEI,YAAY,EAAEH,eAAe;SAClC,EAAErE,IAAIiE,GAAG,CAAC,CAAC,CAAC,EAAEF,cAAc,CAAC,CAAC,EAAE;GACtC,CAAC,CAACV,EAAE,CAAC/B;IAEN,OAAO;QACLA;QACAzB,OAAOqE;QACPO;IACF;AACF,EAAC;AAED,MAAMhC,eAAe,CAAC,EACpBnC,OAAO,EACPe,WAAW,EACXP,IAAI,EAKL;IACC,IAAIA,MAAM;QACR,OAAOA;IACT;IAEA,MAAM4D,eAAerD,YAAYsD,IAAI,CAAC,CAACzD,aACrCZ,QAAQ2B,OAAO,CAACZ,WAAW,CAACH,WAAW,CAAC0D,MAAM,CAACC,MAAM,CAACF,IAAI,CACxD,CAACnE,QAAUA,MAAMsE,IAAI,KAAK,UAAUtE,MAAMgB,IAAI,KAAK;IAIvD,OAAOkD,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'\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,GAAG;QACpC,MAAM,IAAIC,MAAM;IAClB;IAEA,IAAIZ,MAAMW,UAAU,CAACE,MAAM,KAAK,GAAG;QACjC,MAAM,IAAID,MAAM;IAClB;IAEA,IAAIH,MAAMC,OAAO,CAACH,OAAO;QACvB,MAAM,IAAIK,MAAM;IAClB;IAEA,MAAME,cAAcd,MAAMW,UAAU;IACpC,MAAMI,aAAa,GAAGV,KAAKW,UAAU,CAAC,KAAK,OAAOhB,MAAMiB,IAAI,EAAE;IAC9D,MAAMC,KAAKpB,QAAQqB,OAA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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"}
@@ -271,7 +271,7 @@ const resolveWherePath = ({ adapter, collection, schemaPath, table, wherePlan })
271
271
  }
272
272
  return {
273
273
  type: 'scalar',
274
- column: fieldContext ? table[pathPlan.columnPath] : sql`null`,
274
+ column: fieldContext ? fieldContext.isLocalized ? adapter.tables[`${getTableName(table)}${adapter.localesSuffix}`][pathPlan.columnPath] : table[pathPlan.columnPath] : sql`null`,
275
275
  fieldContext,
276
276
  pathPlan,
277
277
  queryValueContext
@@ -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: 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 ? table[pathPlan.columnPath] : 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","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;AA8B1F;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B,CAAC,EACxCC,OAAO,EAC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AAC,GAAG,CAAC,IAAI,CAAC;IAC7D;IAEA,MAAMO,kBAAkBzB,SAASvB,UAAU,CACxCqC,KAAK,CAAC,KACN3C,GAAG,CAAC,CAACuD,cAAgB5E,YAAY4E,cACjCC,IAAI,CAAC;IACR,MAAMC,kBAAkBxE,QAAQyE,YAAY,CAACZ,GAAG,CAAC,GAAGnE,YAAYO,YAAY,CAAC,EAAEoE,iBAAiB;IAEhG,IAAI,CAACG,iBAAiB;QACpB,MAAM,IAAIE,MACR,CAAC,6BAA6B,EAAEzE,WAAW,0BAA0B,EAAE2C,SAASvB,UAAU,CAAC,CAAC,CAAC;IAEjG;IAEA,IAAIsD,2BAA2BH;IAC/B,IAAII,kBAAkBxF,aAAae;IAEnC,IAAIH,QAAQ6E,UAAU,EAAE;QACtBF,2BAA2B,CAAC,CAAC,EAAE3E,QAAQ6E,UAAU,CAAC,GAAG,EAAEL,gBAAgB,CAAC,CAAC;QACzEI,kBAAkB,CAAC,CAAC,EAAE5E,QAAQ6E,UAAU,CAAC,GAAG,EAAED,gBAAgB,CAAC,CAAC;IAClE;IAEA,IAAI5E,QAAQ8D,IAAI,KAAK,YAAY;QAC/B,OAAO,CAAC,2BAA2B,EAAEa,yBAAyB,2BAA2B,EAAEA,yBAAyB,OAAO,EAAEA,yBAAyB,aAAa,EAAEC,gBAAgB,IAAI,CAAC;IAC5L;IAEA,OAAO,CAAC,yBAAyB,EAAED,yBAAyB,aAAa,EAAEA,yBAAyB,OAAO,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 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: 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,8BAA8B,IAAIC,IAAI;IAAC;IAAY;IAAU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rizzleAdapter } from '../types.js';
3
3
  export type ScalarWhereField = {
4
4
  field: FlattenedField;
5
+ isLocalized?: boolean;
5
6
  isUUID: boolean;
6
7
  type: 'scalar';
7
8
  };
@@ -22,7 +23,7 @@ export type PolymorphicJoinWherePlan = Map<string, WherePathPlan>;
22
23
  * whether the path uses a scalar column or a has-many select value table. A field may be absent
23
24
  * from some target collections; those branches compare against SQL NULL or an empty JSON array.
24
25
  *
25
- * Paths are marked as invalid when their storage shapes conflict, require localized or separate-row
26
+ * Paths are marked as invalid when their storage shapes conflict, require separate-row
26
27
  * traversal, have no matching field, lack a required column, or collide after path flattening.
27
28
  *
28
29
  * @returns A plan keyed by each unique schema path in `where`.
@@ -1 +1 @@
1
- {"version":3,"file":"createPolymorphicJoinWherePlan.d.ts","sourceRoot":"","sources":["../../src/find/createPolymorphicJoinWherePlan.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,cAAc,EAAkB,KAAK,KAAK,EAAE,MAAM,SAAS,CAAA;AAGzE,OAAO,KAAK,EAAE,cAAc,EAAgB,MAAM,aAAa,CAAA;AAK/D,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,cAAc,CAAA;IACrB,MAAM,EAAE,OAAO,CAAA;IACf,IAAI,EAAE,QAAQ,CAAA;CACf,CAAA;AAED,KAAK,oBAAoB,GAAG;IAAE,KAAK,EAAE,cAAc,CAAC;IAAC,IAAI,EAAE,eAAe,CAAA;CAAE,GAAG,gBAAgB,CAAA;AAE/F,MAAM,MAAM,aAAa,GAAG;IAC1B,UAAU,EAAE,MAAM,CAAA;IAClB,kBAAkB,EAAE,GAAG,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAA;IACrD,UAAU,EAAE,MAAM,CAAA;IAClB,IAAI,EAAE,eAAe,GAAG,SAAS,GAAG,QAAQ,CAAA;CAC7C,CAAA;AAED,MAAM,MAAM,wBAAwB,GAAG,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAA;AAEjE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,8BAA8B,qCAIxC;IACD,OAAO,EAAE,cAAc,CAAA;IACvB,WAAW,EAAE,MAAM,EAAE,CAAA;IACrB,KAAK,EAAE,KAAK,CAAA;CACb,KAAG,wBAoIH,CAAA"}
1
+ {"version":3,"file":"createPolymorphicJoinWherePlan.d.ts","sourceRoot":"","sources":["../../src/find/createPolymorphicJoinWherePlan.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,cAAc,EAAkB,KAAK,KAAK,EAAE,MAAM,SAAS,CAAA;AAGzE,OAAO,KAAK,EAAE,cAAc,EAAgB,MAAM,aAAa,CAAA;AAK/D,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,cAAc,CAAA;IACrB,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,MAAM,EAAE,OAAO,CAAA;IACf,IAAI,EAAE,QAAQ,CAAA;CACf,CAAA;AAED,KAAK,oBAAoB,GAAG;IAAE,KAAK,EAAE,cAAc,CAAC;IAAC,IAAI,EAAE,eAAe,CAAA;CAAE,GAAG,gBAAgB,CAAA;AAE/F,MAAM,MAAM,aAAa,GAAG;IAC1B,UAAU,EAAE,MAAM,CAAA;IAClB,kBAAkB,EAAE,GAAG,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAA;IACrD,UAAU,EAAE,MAAM,CAAA;IAClB,IAAI,EAAE,eAAe,GAAG,SAAS,GAAG,QAAQ,CAAA;CAC7C,CAAA;AAED,MAAM,MAAM,wBAAwB,GAAG,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAA;AAEjE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,8BAA8B,qCAIxC;IACD,OAAO,EAAE,cAAc,CAAA;IACvB,WAAW,EAAE,MAAM,EAAE,CAAA;IACrB,KAAK,EAAE,KAAK,CAAA;CACb,KAAG,wBA0IH,CAAA"}
@@ -8,7 +8,7 @@ import { sanitizePathSegment } from '../utilities/sanitizePathSegment.js';
8
8
  * whether the path uses a scalar column or a has-many select value table. A field may be absent
9
9
  * from some target collections; those branches compare against SQL NULL or an empty JSON array.
10
10
  *
11
- * Paths are marked as invalid when their storage shapes conflict, require localized or separate-row
11
+ * Paths are marked as invalid when their storage shapes conflict, require separate-row
12
12
  * traversal, have no matching field, lack a required column, or collide after path flattening.
13
13
  *
14
14
  * @returns A plan keyed by each unique schema path in `where`.
@@ -27,7 +27,8 @@ import { sanitizePathSegment } from '../utilities/sanitizePathSegment.js';
27
27
  return {
28
28
  collection,
29
29
  collectionConfig,
30
- table
30
+ table,
31
+ tableName
31
32
  };
32
33
  });
33
34
  const schemaPathsByColumnPath = new Map();
@@ -46,7 +47,7 @@ import { sanitizePathSegment } from '../utilities/sanitizePathSegment.js';
46
47
  let hasManySelect = false;
47
48
  let hasUnsupportedFieldShape = false;
48
49
  const scalarQueryValueSignatures = new Set();
49
- for (const { collection, collectionConfig, table } of collectionContexts){
50
+ for (const { collection, collectionConfig, table, tableName } of collectionContexts){
50
51
  const fieldAtPath = getFieldByPath({
51
52
  fields: collectionConfig.flattenedFields,
52
53
  path: schemaPath
@@ -78,7 +79,7 @@ import { sanitizePathSegment } from '../utilities/sanitizePathSegment.js';
78
79
  continue;
79
80
  }
80
81
  isFieldPresent = true;
81
- if (fieldAtPath.pathHasLocalized || pathHasSeparateRows({
82
+ if (pathHasSeparateRows({
82
83
  fields: collectionConfig.flattenedFields,
83
84
  path: schemaPath
84
85
  })) {
@@ -86,6 +87,10 @@ import { sanitizePathSegment } from '../utilities/sanitizePathSegment.js';
86
87
  continue;
87
88
  }
88
89
  if (fieldAtPath.field.type === 'select' && fieldAtPath.field.hasMany) {
90
+ if (fieldAtPath.pathHasLocalized) {
91
+ hasUnsupportedFieldShape = true;
92
+ continue;
93
+ }
89
94
  hasManySelect = true;
90
95
  fieldsByCollection.set(collection, {
91
96
  type: 'hasManySelect',
@@ -93,7 +98,8 @@ import { sanitizePathSegment } from '../utilities/sanitizePathSegment.js';
93
98
  });
94
99
  continue;
95
100
  }
96
- const fieldColumn = table[columnPath];
101
+ const fieldTable = fieldAtPath.pathHasLocalized ? adapter.tables[`${tableName}${adapter.localesSuffix}`] : table;
102
+ const fieldColumn = fieldTable?.[columnPath];
97
103
  if (!fieldColumn) {
98
104
  hasUnsupportedFieldShape = true;
99
105
  continue;
@@ -101,6 +107,9 @@ import { sanitizePathSegment } from '../utilities/sanitizePathSegment.js';
101
107
  fieldsByCollection.set(collection, {
102
108
  type: 'scalar',
103
109
  field: fieldAtPath.field,
110
+ ...fieldAtPath.pathHasLocalized && {
111
+ isLocalized: true
112
+ },
104
113
  isUUID: fieldColumn.columnType === 'PgUUID'
105
114
  });
106
115
  scalarQueryValueSignatures.add(getScalarQueryValueSignature({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/find/createPolymorphicJoinWherePlan.ts"],"sourcesContent":["import type { Column } from 'drizzle-orm'\n\nimport { type FlattenedField, getFieldByPath, type Where } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter, GenericTable } from '../types.js'\n\nimport { isUUIDType } from '../utilities/isUUIDType.js'\nimport { sanitizePathSegment } from '../utilities/sanitizePathSegment.js'\n\nexport type ScalarWhereField = {\n field: FlattenedField\n isUUID: boolean\n type: 'scalar'\n}\n\ntype CollectionWhereField = { field: FlattenedField; type: 'hasManySelect' } | ScalarWhereField\n\nexport type WherePathPlan = {\n columnPath: string\n fieldsByCollection: Map<string, CollectionWhereField>\n schemaPath: string\n type: 'hasManySelect' | 'invalid' | 'scalar'\n}\n\nexport type PolymorphicJoinWherePlan = Map<string, WherePathPlan>\n\n/**\n * Analyzes every leaf path in a polymorphic join where clause before SQL is built. Each plan entry\n * records the flattened column path, the compatible field shape for each target collection, and\n * whether the path uses a scalar column or a has-many select value table. A field may be absent\n * from some target collections; those branches compare against SQL NULL or an empty JSON array.\n *\n * Paths are marked as invalid when their storage shapes conflict, require localized or separate-row\n * traversal, have no matching field, lack a required column, or collide after path flattening.\n *\n * @returns A plan keyed by each unique schema path in `where`.\n * @throws If a target collection or its mapped database table is not available in the adapter.\n */\nexport const createPolymorphicJoinWherePlan = ({\n adapter,\n collections,\n where,\n}: {\n adapter: DrizzleAdapter\n collections: string[]\n where: Where\n}): PolymorphicJoinWherePlan => {\n const collectionContexts = collections.map((collection) => {\n const collectionConfig = adapter.payload.collections[collection]?.config\n\n if (!collectionConfig) {\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 return { collection, collectionConfig, table }\n })\n const schemaPathsByColumnPath = new Map<string, Set<string>>()\n const schemaPaths = new Set(getWhereSchemaPaths(where))\n\n for (const schemaPath of schemaPaths) {\n const columnPath = getColumnPath(schemaPath)\n const paths = schemaPathsByColumnPath.get(columnPath) ?? new Set<string>()\n\n paths.add(schemaPath)\n schemaPathsByColumnPath.set(columnPath, paths)\n }\n\n const plan: PolymorphicJoinWherePlan = new Map()\n\n for (const schemaPath of schemaPaths) {\n const columnPath = getColumnPath(schemaPath)\n const fieldsByCollection = new Map<string, CollectionWhereField>()\n let isFieldPresent = schemaPath === 'id' || schemaPath === 'relationTo'\n let hasManySelect = false\n let hasUnsupportedFieldShape = false\n const scalarQueryValueSignatures = new Set<string>()\n\n for (const { collection, collectionConfig, table } of collectionContexts) {\n const fieldAtPath = getFieldByPath({\n fields: collectionConfig.flattenedFields,\n path: schemaPath,\n })\n\n if (schemaPath === 'id') {\n const idColumn = table['id'] as Column | undefined\n\n if (!idColumn) {\n hasUnsupportedFieldShape = true\n } else {\n scalarQueryValueSignatures.add(`id:${idColumn.getSQLType()}`)\n fieldsByCollection.set(collection, {\n type: 'scalar',\n field:\n fieldAtPath?.field ??\n ({\n name: 'id',\n type: isUUIDType(adapter.idType) ? 'text' : 'number',\n } as FlattenedField),\n isUUID: !fieldAtPath && isUUIDType(adapter.idType),\n })\n }\n\n continue\n }\n\n if (!fieldAtPath) {\n if (\n pathHasUnsupportedNestedContainer({\n fields: collectionConfig.flattenedFields,\n path: schemaPath,\n })\n ) {\n hasUnsupportedFieldShape = true\n }\n\n continue\n }\n\n isFieldPresent = true\n\n if (\n fieldAtPath.pathHasLocalized ||\n pathHasSeparateRows({ fields: collectionConfig.flattenedFields, path: schemaPath })\n ) {\n hasUnsupportedFieldShape = true\n continue\n }\n\n if (fieldAtPath.field.type === 'select' && fieldAtPath.field.hasMany) {\n hasManySelect = true\n fieldsByCollection.set(collection, {\n type: 'hasManySelect',\n field: fieldAtPath.field,\n })\n continue\n }\n\n const fieldColumn = table[columnPath] as Column | undefined\n\n if (!fieldColumn) {\n hasUnsupportedFieldShape = true\n continue\n }\n\n fieldsByCollection.set(collection, {\n type: 'scalar',\n field: fieldAtPath.field,\n isUUID: fieldColumn.columnType === 'PgUUID',\n })\n scalarQueryValueSignatures.add(\n getScalarQueryValueSignature({ column: fieldColumn, field: fieldAtPath.field }),\n )\n }\n\n const hasColumnPathCollision = (schemaPathsByColumnPath.get(columnPath)?.size ?? 0) > 1\n const isInvalid =\n hasColumnPathCollision ||\n !isFieldPresent ||\n hasUnsupportedFieldShape ||\n (hasManySelect && scalarQueryValueSignatures.size > 0) ||\n scalarQueryValueSignatures.size > 1\n\n plan.set(schemaPath, {\n type: isInvalid ? 'invalid' : hasManySelect ? 'hasManySelect' : 'scalar',\n columnPath,\n fieldsByCollection,\n schemaPath,\n })\n }\n\n return plan\n}\n\nconst textQueryFieldTypes = new Set<FlattenedField['type']>([\n 'code',\n 'email',\n 'slug',\n 'text',\n 'textarea',\n])\n\nconst getScalarQueryValueSignature = ({\n column,\n field,\n}: {\n column: Column\n field: FlattenedField\n}): string => {\n if (field.type === 'select' || field.type === 'radio') {\n const optionValues = field.options.map((option) =>\n typeof option === 'string' ? option : option.value,\n )\n\n return `${field.type}:${JSON.stringify(optionValues)}`\n }\n\n if (textQueryFieldTypes.has(field.type)) {\n return 'text'\n }\n\n return `${field.type}:${column.getSQLType()}`\n}\n\nconst getWhereSchemaPaths = (where: Where): string[] => {\n const paths: string[] = []\n\n for (const key in where) {\n if (['AND', 'OR'].includes(key.toUpperCase())) {\n if (Array.isArray(where[key])) {\n for (const nestedWhere of where[key]) {\n paths.push(...getWhereSchemaPaths(nestedWhere))\n }\n }\n } else {\n paths.push(key)\n }\n }\n\n return paths\n}\n\nconst getColumnPath = (schemaPath: string): string =>\n schemaPath\n .split('.')\n .map((segment) => sanitizePathSegment(segment))\n .join('_')\n\nconst pathHasSeparateRows = ({ fields, path }: { fields: FlattenedField[]; path: string }) => {\n const pathSegments = path.split('.')\n\n for (let segmentIndex = 1; segmentIndex < pathSegments.length; segmentIndex++) {\n const fieldAtParentPath = getFieldByPath({\n fields,\n path: pathSegments.slice(0, segmentIndex).join('.'),\n })\n\n if (fieldAtParentPath?.field.type === 'array' || fieldAtParentPath?.field.type === 'blocks') {\n return true\n }\n }\n\n return false\n}\n\nconst pathHasUnsupportedNestedContainer = ({\n fields,\n path,\n}: {\n fields: FlattenedField[]\n path: string\n}) => {\n const pathSegments = path.split('.')\n\n for (let segmentIndex = 1; segmentIndex < pathSegments.length; segmentIndex++) {\n const fieldAtParentPath = getFieldByPath({\n fields,\n path: pathSegments.slice(0, segmentIndex).join('.'),\n })\n\n if (!fieldAtParentPath) {\n return false\n }\n\n if (!['group', 'tab'].includes(fieldAtParentPath.field.type)) {\n return true\n }\n }\n\n return false\n}\n"],"names":["getFieldByPath","toSnakeCase","isUUIDType","sanitizePathSegment","createPolymorphicJoinWherePlan","adapter","collections","where","collectionContexts","map","collection","collectionConfig","payload","config","Error","tableName","tableNameMap","get","table","tables","undefined","schemaPathsByColumnPath","Map","schemaPaths","Set","getWhereSchemaPaths","schemaPath","columnPath","getColumnPath","paths","add","set","plan","fieldsByCollection","isFieldPresent","hasManySelect","hasUnsupportedFieldShape","scalarQueryValueSignatures","fieldAtPath","fields","flattenedFields","path","idColumn","getSQLType","type","field","name","idType","isUUID","pathHasUnsupportedNestedContainer","pathHasLocalized","pathHasSeparateRows","hasMany","fieldColumn","columnType","getScalarQueryValueSignature","column","hasColumnPathCollision","size","isInvalid","textQueryFieldTypes","optionValues","options","option","value","JSON","stringify","has","key","includes","toUpperCase","Array","isArray","nestedWhere","push","split","segment","join","pathSegments","segmentIndex","length","fieldAtParentPath","slice"],"mappings":"AAEA,SAA8BA,cAAc,QAAoB,UAAS;AACzE,OAAOC,iBAAiB,gBAAe;AAIvC,SAASC,UAAU,QAAQ,6BAA4B;AACvD,SAASC,mBAAmB,QAAQ,sCAAqC;AAmBzE;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,iCAAiC,CAAC,EAC7CC,OAAO,EACPC,WAAW,EACXC,KAAK,EAKN;IACC,MAAMC,qBAAqBF,YAAYG,GAAG,CAAC,CAACC;QAC1C,MAAMC,mBAAmBN,QAAQO,OAAO,CAACN,WAAW,CAACI,WAAW,EAAEG;QAElE,IAAI,CAACF,kBAAkB;YACrB,MAAM,IAAIG,MAAM,CAAC,qCAAqC,EAAEJ,WAAW,CAAC,CAAC;QACvE;QAEA,MAAMK,YAAYV,QAAQW,YAAY,CAACC,GAAG,CAAChB,YAAYS;QACvD,MAAMQ,QAAQH,YAAaV,QAAQc,MAAM,CAACJ,UAAU,GAAgCK;QAEpF,IAAI,CAACF,OAAO;YACV,MAAM,IAAIJ,MAAM,CAAC,6BAA6B,EAAEJ,WAAW,uBAAuB,CAAC;QACrF;QAEA,OAAO;YAAEA;YAAYC;YAAkBO;QAAM;IAC/C;IACA,MAAMG,0BAA0B,IAAIC;IACpC,MAAMC,cAAc,IAAIC,IAAIC,oBAAoBlB;IAEhD,KAAK,MAAMmB,cAAcH,YAAa;QACpC,MAAMI,aAAaC,cAAcF;QACjC,MAAMG,QAAQR,wBAAwBJ,GAAG,CAACU,eAAe,IAAIH;QAE7DK,MAAMC,GAAG,CAACJ;QACVL,wBAAwBU,GA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IAAI,CAAC;QACjD;QAEA,IAAI,CAACI,mBAAmB;YACtB,OAAO;QACT;QAEA,IAAI,CAAC;YAAC;YAAS;SAAM,CAACZ,QAAQ,CAACY,kBAAkBpC,KAAK,CAACD,IAAI,GAAG;YAC5D,OAAO;QACT;IACF;IAEA,OAAO;AACT"}
1
+ {"version":3,"sources":["../../src/find/createPolymorphicJoinWherePlan.ts"],"sourcesContent":["import type { Column } from 'drizzle-orm'\n\nimport { type FlattenedField, getFieldByPath, type Where } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter, GenericTable } from '../types.js'\n\nimport { isUUIDType } from '../utilities/isUUIDType.js'\nimport { sanitizePathSegment } from '../utilities/sanitizePathSegment.js'\n\nexport type ScalarWhereField = {\n field: FlattenedField\n isLocalized?: boolean\n isUUID: boolean\n type: 'scalar'\n}\n\ntype CollectionWhereField = { field: FlattenedField; type: 'hasManySelect' } | ScalarWhereField\n\nexport type WherePathPlan = {\n columnPath: string\n fieldsByCollection: Map<string, CollectionWhereField>\n schemaPath: string\n type: 'hasManySelect' | 'invalid' | 'scalar'\n}\n\nexport type PolymorphicJoinWherePlan = Map<string, WherePathPlan>\n\n/**\n * Analyzes every leaf path in a polymorphic join where clause before SQL is built. Each plan entry\n * records the flattened column path, the compatible field shape for each target collection, and\n * whether the path uses a scalar column or a has-many select value table. A field may be absent\n * from some target collections; those branches compare against SQL NULL or an empty JSON array.\n *\n * Paths are marked as invalid when their storage shapes conflict, require separate-row\n * traversal, have no matching field, lack a required column, or collide after path flattening.\n *\n * @returns A plan keyed by each unique schema path in `where`.\n * @throws If a target collection or its mapped database table is not available in the adapter.\n */\nexport const createPolymorphicJoinWherePlan = ({\n adapter,\n collections,\n where,\n}: {\n adapter: DrizzleAdapter\n collections: string[]\n where: Where\n}): PolymorphicJoinWherePlan => {\n const collectionContexts = collections.map((collection) => {\n const collectionConfig = adapter.payload.collections[collection]?.config\n\n if (!collectionConfig) {\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 return { collection, collectionConfig, table, tableName }\n })\n const schemaPathsByColumnPath = new Map<string, Set<string>>()\n const schemaPaths = new Set(getWhereSchemaPaths(where))\n\n for (const schemaPath of schemaPaths) {\n const columnPath = getColumnPath(schemaPath)\n const paths = schemaPathsByColumnPath.get(columnPath) ?? new Set<string>()\n\n paths.add(schemaPath)\n schemaPathsByColumnPath.set(columnPath, paths)\n }\n\n const plan: PolymorphicJoinWherePlan = new Map()\n\n for (const schemaPath of schemaPaths) {\n const columnPath = getColumnPath(schemaPath)\n const fieldsByCollection = new Map<string, CollectionWhereField>()\n let isFieldPresent = schemaPath === 'id' || schemaPath === 'relationTo'\n let hasManySelect = false\n let hasUnsupportedFieldShape = false\n const scalarQueryValueSignatures = new Set<string>()\n\n for (const { collection, collectionConfig, table, tableName } of collectionContexts) {\n const fieldAtPath = getFieldByPath({\n fields: collectionConfig.flattenedFields,\n path: schemaPath,\n })\n\n if (schemaPath === 'id') {\n const idColumn = table['id'] as Column | undefined\n\n if (!idColumn) {\n hasUnsupportedFieldShape = true\n } else {\n scalarQueryValueSignatures.add(`id:${idColumn.getSQLType()}`)\n fieldsByCollection.set(collection, {\n type: 'scalar',\n field:\n fieldAtPath?.field ??\n ({\n name: 'id',\n type: isUUIDType(adapter.idType) ? 'text' : 'number',\n } as FlattenedField),\n isUUID: !fieldAtPath && isUUIDType(adapter.idType),\n })\n }\n\n continue\n }\n\n if (!fieldAtPath) {\n if (\n pathHasUnsupportedNestedContainer({\n fields: collectionConfig.flattenedFields,\n path: schemaPath,\n })\n ) {\n hasUnsupportedFieldShape = true\n }\n\n continue\n }\n\n isFieldPresent = true\n\n if (pathHasSeparateRows({ fields: collectionConfig.flattenedFields, path: schemaPath })) {\n hasUnsupportedFieldShape = true\n continue\n }\n\n if (fieldAtPath.field.type === 'select' && fieldAtPath.field.hasMany) {\n if (fieldAtPath.pathHasLocalized) {\n hasUnsupportedFieldShape = true\n continue\n }\n\n hasManySelect = true\n fieldsByCollection.set(collection, {\n type: 'hasManySelect',\n field: fieldAtPath.field,\n })\n continue\n }\n\n const fieldTable = fieldAtPath.pathHasLocalized\n ? adapter.tables[`${tableName}${adapter.localesSuffix}`]\n : table\n const fieldColumn = fieldTable?.[columnPath] as Column | undefined\n\n if (!fieldColumn) {\n hasUnsupportedFieldShape = true\n continue\n }\n\n fieldsByCollection.set(collection, {\n type: 'scalar',\n field: fieldAtPath.field,\n ...(fieldAtPath.pathHasLocalized && { isLocalized: true }),\n isUUID: fieldColumn.columnType === 'PgUUID',\n })\n scalarQueryValueSignatures.add(\n getScalarQueryValueSignature({ column: fieldColumn, field: fieldAtPath.field }),\n )\n }\n\n const hasColumnPathCollision = (schemaPathsByColumnPath.get(columnPath)?.size ?? 0) > 1\n const isInvalid =\n hasColumnPathCollision ||\n !isFieldPresent ||\n hasUnsupportedFieldShape ||\n (hasManySelect && scalarQueryValueSignatures.size > 0) ||\n scalarQueryValueSignatures.size > 1\n\n plan.set(schemaPath, {\n type: isInvalid ? 'invalid' : hasManySelect ? 'hasManySelect' : 'scalar',\n columnPath,\n fieldsByCollection,\n schemaPath,\n })\n }\n\n return plan\n}\n\nconst textQueryFieldTypes = new Set<FlattenedField['type']>([\n 'code',\n 'email',\n 'slug',\n 'text',\n 'textarea',\n])\n\nconst getScalarQueryValueSignature = ({\n column,\n field,\n}: {\n column: Column\n field: FlattenedField\n}): string => {\n if (field.type === 'select' || field.type === 'radio') {\n const optionValues = field.options.map((option) =>\n typeof option === 'string' ? option : option.value,\n )\n\n return `${field.type}:${JSON.stringify(optionValues)}`\n }\n\n if (textQueryFieldTypes.has(field.type)) {\n return 'text'\n }\n\n return `${field.type}:${column.getSQLType()}`\n}\n\nconst getWhereSchemaPaths = (where: Where): string[] => {\n const paths: string[] = []\n\n for (const key in where) {\n if (['AND', 'OR'].includes(key.toUpperCase())) {\n if (Array.isArray(where[key])) {\n for (const nestedWhere of where[key]) {\n paths.push(...getWhereSchemaPaths(nestedWhere))\n }\n }\n } else {\n paths.push(key)\n }\n }\n\n return paths\n}\n\nconst getColumnPath = (schemaPath: string): string =>\n schemaPath\n .split('.')\n .map((segment) => sanitizePathSegment(segment))\n .join('_')\n\nconst pathHasSeparateRows = ({ fields, path }: { fields: FlattenedField[]; path: string }) => {\n const pathSegments = path.split('.')\n\n for (let segmentIndex = 1; segmentIndex < pathSegments.length; segmentIndex++) {\n const fieldAtParentPath = getFieldByPath({\n fields,\n path: pathSegments.slice(0, segmentIndex).join('.'),\n })\n\n if (fieldAtParentPath?.field.type === 'array' || fieldAtParentPath?.field.type === 'blocks') {\n return true\n }\n }\n\n return false\n}\n\nconst pathHasUnsupportedNestedContainer = ({\n fields,\n path,\n}: {\n fields: FlattenedField[]\n path: string\n}) => {\n const pathSegments = path.split('.')\n\n for (let segmentIndex = 1; segmentIndex < pathSegments.length; segmentIndex++) {\n const fieldAtParentPath = getFieldByPath({\n fields,\n path: pathSegments.slice(0, segmentIndex).join('.'),\n })\n\n if (!fieldAtParentPath) {\n return false\n }\n\n if (!['group', 'tab'].includes(fieldAtParentPath.field.type)) {\n return true\n }\n }\n\n return false\n}\n"],"names":["getFieldByPath","toSnakeCase","isUUIDType","sanitizePathSegment","createPolymorphicJoinWherePlan","adapter","collections","where","collectionContexts","map","collection","collectionConfig","payload","config","Error","tableName","tableNameMap","get","table","tables","undefined","schemaPathsByColumnPath","Map","schemaPaths","Set","getWhereSchemaPaths","schemaPath","columnPath","getColumnPath","paths","add","set","plan","fieldsByCollection","isFieldPresent","hasManySelect","hasUnsupportedFieldShape","scalarQueryValueSignatures","fieldAtPath","fields","flattenedFields","path","idColumn","getSQLType","type","field","name","idType","isUUID","pathHasUnsupportedNestedContainer","pathHasSeparateRows","hasMany","pathHasLocalized","fieldTable","localesSuffix","fieldColumn","isLocalized","columnType","getScalarQueryValueSignature","column","hasColumnPathCollision","size","isInvalid","textQueryFieldTypes","optionValues","options","option","value","JSON","stringify","has","key","includes","toUpperCase","Array","isArray","nestedWhere","push","split","segment","join","pathSegments","segmentIndex","length","fieldAtParentPath","slice"],"mappings":"AAEA,SAA8BA,cAAc,QAAoB,UAAS;AACzE,OAAOC,iBAAiB,gBAAe;AAIvC,SAASC,UAAU,QAAQ,6BAA4B;AACvD,SAASC,mBAAmB,QAAQ,sCAAqC;AAoBzE;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,iCAAiC,CAAC,EAC7CC,OAAO,EACPC,WAAW,EACXC,KAAK,EAKN;IACC,MAAMC,qBAAqBF,YAAYG,GAAG,CAAC,CAACC;QAC1C,MAAMC,mBAAmBN,QAAQO,OAAO,CAACN,WAAW,CAACI,WAAW,EAAEG;QAElE,IAAI,CAACF,kBAAkB;YACrB,MAAM,IAAIG,MAAM,CAAC,qCAAqC,EAAEJ,WAAW,CAAC,CAAC;QACvE;QAEA,MAAMK,YAAYV,QAAQW,YAAY,CAACC,GAAG,CAAChB,YAAYS;QACvD,MAAMQ,QAAQH,YAAaV,QAAQc,MAAM,CAACJ,UAAU,GAAgCK;QAEpF,IAAI,CAACF,OAAO;YACV,MAAM,IAAIJ,MAAM,CAAC,6BAA6B,EAAEJ,WAAW,uBAAuB,CAAC;QACrF;QAEA,OAAO;YAAEA;YAAYC;YAAkBO;YAAOH;QAAU;IAC1D;IACA,MAAMM,0BAA0B,IAAIC;IACpC,MAAMC,cAAc,IAAIC,IAAIC,oBAAoBlB;IAEhD,KAAK,MAAMmB,cAAcH,YAAa;QACpC,MAAMI,aAAaC,cAAcF;QACjC,MAAMG,QAAQR,wBAAwBJ,GAAG,CAACU,eAAe,IAAIH;QAE7DK,MAAMC,GAAG,CAACJ;QACVL,wBAAwBU,GAAG,CAACJ,YAAYE;IAC1C;IAEA,MAAMG,OAAiC,IAAIV;IAE3C,KAAK,MAAMI,cAAcH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AI,EAAE,MAAM,CAAA;IACZ,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,uBAAuB,CAAC,EAAE,OAAO,CAAA;IACjC,UAAU,CAAC,EAAE,UAAU,CAAA;IACvB,SAAS,EAAE,MAAM,CAAA;IACjB,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACrC,iBAAiB,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,gBAAgB,EAAE;QAChB,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,IAAI,CAAC,EAAE,OAAO,CAAA;QACd,KAAK,CAAC,EAAE,OAAO,CAAA;KAChB,CAAA;CACF,CAAA;AAED,eAAO,MAAM,cAAc,iSAuBxB,iBAAiB,4BA2oBnB,CAAA"}
@@ -258,6 +258,7 @@ export const traverseFields = ({ _locales, adapter, collectionSlug, currentArgs,
258
258
  limit,
259
259
  locale,
260
260
  page,
261
+ pageSize: limitArg,
261
262
  path,
262
263
  shouldCount,
263
264
  sort,