@payloadcms/db-postgres 3.0.0-canary.6041f49 → 3.0.0-canary.6d9b462

Sign up to get free protection for your applications and to get access to all the features.
Files changed (132) hide show
  1. package/dist/connect.d.ts.map +1 -1
  2. package/dist/connect.js +12 -7
  3. package/dist/connect.js.map +1 -1
  4. package/dist/count.d.ts.map +1 -1
  5. package/dist/count.js +1 -10
  6. package/dist/count.js.map +1 -1
  7. package/dist/createMigration.d.ts.map +1 -1
  8. package/dist/createMigration.js +56 -35
  9. package/dist/createMigration.js.map +1 -1
  10. package/dist/createVersion.d.ts.map +1 -1
  11. package/dist/createVersion.js +2 -6
  12. package/dist/createVersion.js.map +1 -1
  13. package/dist/deleteOne.js +2 -2
  14. package/dist/deleteOne.js.map +1 -1
  15. package/dist/destroy.d.ts.map +1 -1
  16. package/dist/destroy.js +4 -0
  17. package/dist/destroy.js.map +1 -1
  18. package/dist/exports/migration-utils.d.ts +2 -0
  19. package/dist/exports/migration-utils.d.ts.map +1 -0
  20. package/dist/exports/migration-utils.js +3 -0
  21. package/dist/exports/migration-utils.js.map +1 -0
  22. package/dist/find/buildFindManyArgs.d.ts +5 -1
  23. package/dist/find/buildFindManyArgs.d.ts.map +1 -1
  24. package/dist/find/buildFindManyArgs.js +2 -1
  25. package/dist/find/buildFindManyArgs.js.map +1 -1
  26. package/dist/find/findMany.d.ts.map +1 -1
  27. package/dist/find/findMany.js +4 -15
  28. package/dist/find/findMany.js.map +1 -1
  29. package/dist/find/traverseFields.d.ts +3 -2
  30. package/dist/find/traverseFields.d.ts.map +1 -1
  31. package/dist/find/traverseFields.js +22 -4
  32. package/dist/find/traverseFields.js.map +1 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +9 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/init.d.ts.map +1 -1
  37. package/dist/init.js +14 -19
  38. package/dist/init.js.map +1 -1
  39. package/dist/predefinedMigrations/relationships-v2-v3.d.ts +4 -0
  40. package/dist/predefinedMigrations/relationships-v2-v3.d.ts.map +1 -0
  41. package/dist/predefinedMigrations/relationships-v2-v3.js.map +1 -0
  42. package/dist/predefinedMigrations/relationships-v2-v3.mjs +11 -0
  43. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts +20 -0
  44. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -0
  45. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js +170 -0
  46. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -0
  47. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts +11 -0
  48. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts.map +1 -0
  49. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js +191 -0
  50. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js.map +1 -0
  51. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts +3 -0
  52. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts.map +1 -0
  53. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js +56 -0
  54. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js.map +1 -0
  55. package/dist/predefinedMigrations/v2-v3/index.d.ts +24 -0
  56. package/dist/predefinedMigrations/v2-v3/index.d.ts.map +1 -0
  57. package/dist/predefinedMigrations/v2-v3/index.js +211 -0
  58. package/dist/predefinedMigrations/v2-v3/index.js.map +1 -0
  59. package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts +19 -0
  60. package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts.map +1 -0
  61. package/dist/predefinedMigrations/v2-v3/migrateRelationships.js +57 -0
  62. package/dist/predefinedMigrations/v2-v3/migrateRelationships.js.map +1 -0
  63. package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts +23 -0
  64. package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts.map +1 -0
  65. package/dist/predefinedMigrations/v2-v3/traverseFields.js +85 -0
  66. package/dist/predefinedMigrations/v2-v3/traverseFields.js.map +1 -0
  67. package/dist/predefinedMigrations/v2-v3/types.d.ts +9 -0
  68. package/dist/predefinedMigrations/v2-v3/types.d.ts.map +1 -0
  69. package/dist/predefinedMigrations/v2-v3/types.js +6 -0
  70. package/dist/predefinedMigrations/v2-v3/types.js.map +1 -0
  71. package/dist/queries/buildAndOrConditions.d.ts +3 -4
  72. package/dist/queries/buildAndOrConditions.d.ts.map +1 -1
  73. package/dist/queries/buildAndOrConditions.js +1 -2
  74. package/dist/queries/buildAndOrConditions.js.map +1 -1
  75. package/dist/queries/buildQuery.d.ts +1 -2
  76. package/dist/queries/buildQuery.d.ts.map +1 -1
  77. package/dist/queries/buildQuery.js +1 -5
  78. package/dist/queries/buildQuery.js.map +1 -1
  79. package/dist/queries/getTableColumnFromPath.d.ts +3 -4
  80. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  81. package/dist/queries/getTableColumnFromPath.js +168 -96
  82. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  83. package/dist/queries/parseParams.d.ts +3 -4
  84. package/dist/queries/parseParams.d.ts.map +1 -1
  85. package/dist/queries/parseParams.js +7 -6
  86. package/dist/queries/parseParams.js.map +1 -1
  87. package/dist/queries/selectDistinct.d.ts +3 -4
  88. package/dist/queries/selectDistinct.d.ts.map +1 -1
  89. package/dist/queries/selectDistinct.js +3 -14
  90. package/dist/queries/selectDistinct.js.map +1 -1
  91. package/dist/schema/build.d.ts +8 -4
  92. package/dist/schema/build.d.ts.map +1 -1
  93. package/dist/schema/build.js +161 -112
  94. package/dist/schema/build.js.map +1 -1
  95. package/dist/schema/traverseFields.d.ts +4 -6
  96. package/dist/schema/traverseFields.d.ts.map +1 -1
  97. package/dist/schema/traverseFields.js +103 -40
  98. package/dist/schema/traverseFields.js.map +1 -1
  99. package/dist/transactions/beginTransaction.d.ts.map +1 -1
  100. package/dist/transactions/beginTransaction.js +4 -0
  101. package/dist/transactions/beginTransaction.js.map +1 -1
  102. package/dist/transform/read/index.d.ts +3 -1
  103. package/dist/transform/read/index.d.ts.map +1 -1
  104. package/dist/transform/read/index.js +2 -1
  105. package/dist/transform/read/index.js.map +1 -1
  106. package/dist/transform/read/relationship.d.ts.map +1 -1
  107. package/dist/transform/read/relationship.js +0 -4
  108. package/dist/transform/read/relationship.js.map +1 -1
  109. package/dist/transform/read/traverseFields.d.ts +6 -1
  110. package/dist/transform/read/traverseFields.d.ts.map +1 -1
  111. package/dist/transform/read/traverseFields.js +69 -55
  112. package/dist/transform/read/traverseFields.js.map +1 -1
  113. package/dist/transform/write/traverseFields.d.ts.map +1 -1
  114. package/dist/transform/write/traverseFields.js +20 -3
  115. package/dist/transform/write/traverseFields.js.map +1 -1
  116. package/dist/types.d.ts +3 -0
  117. package/dist/types.d.ts.map +1 -1
  118. package/dist/types.js.map +1 -1
  119. package/dist/update.d.ts.map +1 -1
  120. package/dist/update.js +1 -2
  121. package/dist/update.js.map +1 -1
  122. package/dist/upsertRow/index.d.ts +1 -1
  123. package/dist/upsertRow/index.d.ts.map +1 -1
  124. package/dist/upsertRow/index.js +3 -1
  125. package/dist/upsertRow/index.js.map +1 -1
  126. package/dist/upsertRow/types.d.ts +5 -0
  127. package/dist/upsertRow/types.d.ts.map +1 -1
  128. package/dist/upsertRow/types.js.map +1 -1
  129. package/dist/utilities/pushDevSchema.d.ts.map +1 -1
  130. package/dist/utilities/pushDevSchema.js +1 -1
  131. package/dist/utilities/pushDevSchema.js.map +1 -1
  132. package/package.json +12 -6
@@ -7,7 +7,7 @@ import { createJSONQuery } from './createJSONQuery/index.js';
7
7
  import { getTableColumnFromPath } from './getTableColumnFromPath.js';
8
8
  import { operatorMap } from './operatorMap.js';
9
9
  import { sanitizeQueryValue } from './sanitizeQueryValue.js';
10
- export async function parseParams({ adapter, fields, joinAliases, joins, locale, selectFields, tableName, where }) {
10
+ export async function parseParams({ adapter, fields, joins, locale, selectFields, tableName, where }) {
11
11
  let result;
12
12
  const constraints = [];
13
13
  if (typeof where === 'object' && Object.keys(where).length > 0) {
@@ -25,7 +25,6 @@ export async function parseParams({ adapter, fields, joinAliases, joins, locale,
25
25
  const builtConditions = await buildAndOrConditions({
26
26
  adapter,
27
27
  fields,
28
- joinAliases,
29
28
  joins,
30
29
  locale,
31
30
  selectFields,
@@ -41,14 +40,13 @@ export async function parseParams({ adapter, fields, joinAliases, joins, locale,
41
40
  // So we need to loop on keys again here to handle each operator independently
42
41
  const pathOperators = where[relationOrPath];
43
42
  if (typeof pathOperators === 'object') {
44
- for (const operator of Object.keys(pathOperators)){
43
+ for (let operator of Object.keys(pathOperators)){
45
44
  if (validOperators.includes(operator)) {
46
45
  const val = where[relationOrPath][operator];
47
46
  const { columnName, constraints: queryConstraints, field, getNotNullColumnByValue, pathSegments, rawColumn, table } = getTableColumnFromPath({
48
47
  adapter,
49
48
  collectionPath: relationOrPath,
50
49
  fields,
51
- joinAliases,
52
50
  joins,
53
51
  locale,
54
52
  pathSegments: relationOrPath.replace(/__/g, '.').split('.'),
@@ -124,6 +122,9 @@ export async function parseParams({ adapter, fields, joinAliases, joins, locale,
124
122
  }
125
123
  break;
126
124
  }
125
+ if (operator === 'like' && (field.type === 'number' || table[columnName].columnType === 'PgUUID')) {
126
+ operator = 'equals';
127
+ }
127
128
  if (operator === 'like') {
128
129
  constraints.push(and(...val.split(' ').map((word)=>ilike(table[columnName], `%${word}%`))));
129
130
  break;
@@ -144,10 +145,10 @@ export async function parseParams({ adapter, fields, joinAliases, joins, locale,
144
145
  break;
145
146
  }
146
147
  if ((field.type === 'relationship' || field.type === 'upload') && Array.isArray(queryValue) && operator === 'not_in') {
147
- constraints.push(sql`${notInArray(table[columnName], queryValue)} OR
148
+ constraints.push(sql`(${notInArray(table[columnName], queryValue)} OR
148
149
  ${table[columnName]}
149
150
  IS
150
- NULL`);
151
+ NULL)`);
151
152
  break;
152
153
  }
153
154
  if (operator === 'equals' && queryValue === null) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/queries/parseParams.ts"],"sourcesContent":["/* eslint-disable no-await-in-loop */\nimport type { SQL } from 'drizzle-orm'\nimport type { Field, Operator, Where } from 'payload/types'\n\nimport { and, ilike, isNotNull, isNull, ne, notInArray, or, sql } from 'drizzle-orm'\nimport { QueryError } from 'payload/errors'\nimport { validOperators } from 'payload/types'\n\nimport type { GenericColumn, PostgresAdapter } from '../types.js'\nimport type { BuildQueryJoinAliases, BuildQueryJoins } from './buildQuery.js'\n\nimport { buildAndOrConditions } from './buildAndOrConditions.js'\nimport { convertPathToJSONTraversal } from './createJSONQuery/convertPathToJSONTraversal.js'\nimport { createJSONQuery } from './createJSONQuery/index.js'\nimport { getTableColumnFromPath } from './getTableColumnFromPath.js'\nimport { operatorMap } from './operatorMap.js'\nimport { sanitizeQueryValue } from './sanitizeQueryValue.js'\n\ntype Args = {\n adapter: PostgresAdapter\n fields: Field[]\n joinAliases: BuildQueryJoinAliases\n joins: BuildQueryJoins\n locale: string\n selectFields: Record<string, GenericColumn>\n tableName: string\n where: Where\n}\n\nexport async function parseParams({\n adapter,\n fields,\n joinAliases,\n joins,\n locale,\n selectFields,\n tableName,\n where,\n}: Args): Promise<SQL> {\n let result: SQL\n const constraints: SQL[] = []\n\n if (typeof where === 'object' && Object.keys(where).length > 0) {\n // We need to determine if the whereKey is an AND, OR, or a schema path\n for (const relationOrPath of Object.keys(where)) {\n if (relationOrPath) {\n const condition = where[relationOrPath]\n let conditionOperator: 'and' | 'or'\n if (relationOrPath.toLowerCase() === 'and') {\n conditionOperator = 'and'\n } else if (relationOrPath.toLowerCase() === 'or') {\n conditionOperator = 'or'\n }\n if (Array.isArray(condition)) {\n const builtConditions = await buildAndOrConditions({\n adapter,\n fields,\n joinAliases,\n joins,\n locale,\n selectFields,\n tableName,\n where: condition,\n })\n if (builtConditions.length > 0) {\n result = operatorMap[conditionOperator](...builtConditions)\n }\n } else {\n // It's a path - and there can be multiple comparisons on a single path.\n // For example - title like 'test' and title not equal to 'tester'\n // So we need to loop on keys again here to handle each operator independently\n const pathOperators = where[relationOrPath]\n if (typeof pathOperators === 'object') {\n for (const operator of Object.keys(pathOperators)) {\n if (validOperators.includes(operator as Operator)) {\n const val = where[relationOrPath][operator]\n const {\n columnName,\n constraints: queryConstraints,\n field,\n getNotNullColumnByValue,\n pathSegments,\n rawColumn,\n table,\n } = getTableColumnFromPath({\n adapter,\n collectionPath: relationOrPath,\n fields,\n joinAliases,\n joins,\n locale,\n pathSegments: relationOrPath.replace(/__/g, '.').split('.'),\n selectFields,\n tableName,\n value: val,\n })\n\n queryConstraints.forEach(({ columnName: col, table: constraintTable, value }) => {\n if (typeof value === 'string' && value.indexOf('%') > -1) {\n constraints.push(operatorMap.like(constraintTable[col], value))\n } else {\n constraints.push(operatorMap.equals(constraintTable[col], value))\n }\n })\n\n if (\n ['json', 'richText'].includes(field.type) &&\n Array.isArray(pathSegments) &&\n pathSegments.length > 1\n ) {\n const segments = pathSegments.slice(1)\n segments.unshift(table[columnName].name)\n\n if (field.type === 'richText') {\n const jsonQuery = createJSONQuery({\n operator,\n pathSegments: segments,\n treatAsArray: ['children'],\n treatRootAsArray: true,\n value: val,\n })\n\n constraints.push(sql.raw(jsonQuery))\n break\n }\n\n const jsonQuery = convertPathToJSONTraversal(pathSegments)\n const operatorKeys = {\n contains: { operator: 'ilike', wildcard: '%' },\n equals: { operator: '=', wildcard: '' },\n exists: { operator: val === true ? 'is not null' : 'is null' },\n like: { operator: 'like', wildcard: '%' },\n not_equals: { operator: '<>', wildcard: '' },\n }\n let formattedValue = `'${operatorKeys[operator].wildcard}${val}${operatorKeys[operator].wildcard}'`\n\n if (operator === 'exists') {\n formattedValue = ''\n }\n\n constraints.push(\n sql.raw(\n `${table[columnName].name}${jsonQuery} ${operatorKeys[operator].operator} ${formattedValue}`,\n ),\n )\n\n break\n }\n\n if (getNotNullColumnByValue) {\n const columnName = getNotNullColumnByValue(val)\n if (columnName) {\n constraints.push(isNotNull(table[columnName]))\n } else {\n throw new QueryError([{ path: relationOrPath }])\n }\n break\n }\n\n if (operator === 'like') {\n constraints.push(\n and(...val.split(' ').map((word) => ilike(table[columnName], `%${word}%`))),\n )\n break\n }\n\n const sanitizedQueryValue = sanitizeQueryValue({\n adapter,\n field,\n operator,\n relationOrPath,\n val,\n })\n\n if (sanitizedQueryValue === null) {\n break\n }\n\n const { operator: queryOperator, value: queryValue } = sanitizedQueryValue\n\n if (queryOperator === 'not_equals' && queryValue !== null) {\n constraints.push(\n or(\n isNull(rawColumn || table[columnName]),\n /* eslint-disable @typescript-eslint/no-explicit-any */\n ne<any>(rawColumn || table[columnName], queryValue),\n ),\n )\n break\n }\n\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n Array.isArray(queryValue) &&\n operator === 'not_in'\n ) {\n constraints.push(\n sql`${notInArray(table[columnName], queryValue)} OR\n ${table[columnName]}\n IS\n NULL`,\n )\n\n break\n }\n\n if (operator === 'equals' && queryValue === null) {\n constraints.push(isNull(rawColumn || table[columnName]))\n break\n }\n\n if (operator === 'not_equals' && queryValue === null) {\n constraints.push(isNotNull(rawColumn || table[columnName]))\n break\n }\n\n constraints.push(\n operatorMap[queryOperator](rawColumn || table[columnName], queryValue),\n )\n }\n }\n }\n }\n }\n }\n }\n if (constraints.length > 0) {\n if (result) {\n result = and(result, ...constraints)\n } else {\n result = and(...constraints)\n }\n }\n if (constraints.length === 1 && !result) {\n ;[result] = constraints\n }\n\n return result\n}\n"],"names":["and","ilike","isNotNull","isNull","ne","notInArray","or","sql","QueryError","validOperators","buildAndOrConditions","convertPathToJSONTraversal","createJSONQuery","getTableColumnFromPath","operatorMap","sanitizeQueryValue","parseParams","adapter","fields","joinAliases","joins","locale","selectFields","tableName","where","result","constraints","Object","keys","length","relationOrPath","condition","conditionOperator","toLowerCase","Array","isArray","builtConditions","pathOperators","operator","includes","val","columnName","queryConstraints","field","getNotNullColumnByValue","pathSegments","rawColumn","table","collectionPath","replace","split","value","forEach","col","constraintTable","indexOf","push","like","equals","type","segments","slice","unshift","name","jsonQuery","treatAsArray","treatRootAsArray","raw","operatorKeys","contains","wildcard","exists","not_equals","formattedValue","path","map","word","sanitizedQueryValue","queryOperator","queryValue"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,mCAAmC,GAInC,SAASA,GAAG,EAAEC,KAAK,EAAEC,SAAS,EAAEC,MAAM,EAAEC,EAAE,EAAEC,UAAU,EAAEC,EAAE,EAAEC,GAAG,QAAQ,cAAa;AACpF,SAASC,UAAU,QAAQ,iBAAgB;AAC3C,SAASC,cAAc,QAAQ,gBAAe;AAK9C,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,sBAAsB,QAAQ,8BAA6B;AACpE,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAa5D,OAAO,eAAeC,YAAY,EAChCC,OAAO,EACPC,MAAM,EACNC,WAAW,EACXC,KAAK,EACLC,MAAM,EACNC,YAAY,EACZC,SAAS,EACTC,KAAK,EACA;IACL,IAAIC;IACJ,MAAMC,cAAqB,EAAE;IAE7B,IAAI,OAAOF,UAAU,YAAYG,OAAOC,IAAI,CAACJ,OAAOK,MAAM,GAAG,GAAG;QAC9D,uEAAuE;QACvE,KAAK,MAAMC,kBAAkBH,OAAOC,IAAI,CAACJ,OAAQ;YAC/C,IAAIM,gBAAgB;gBAClB,MAAMC,YAAYP,KAAK,CAACM,eAAe;gBACvC,IAAIE;gBACJ,IAAIF,eAAeG,WAAW,OAAO,OAAO;oBAC1CD,oBAAoB;gBACtB,OAAO,IAAIF,eAAeG,WAAW,OAA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aAAa,gBAAgByC,eAAe,MAAM;oCACpDrD,YAAY8B,IAAI,CAACtD,UAAU4C,aAAaC,KAAK,CAACN,WAAW;oCACzD;gCACF;gCAEAf,YAAY8B,IAAI,CACd1C,WAAW,CAACgE,cAAc,CAAChC,aAAaC,KAAK,CAACN,WAAW,EAAEsC;4BAE/D;wBACF;oBACF;gBACF;YACF;QACF;IACF;IACA,IAAIrD,YAAYG,MAAM,GAAG,GAAG;QAC1B,IAAIJ,QAAQ;YACVA,SAASzB,IAAIyB,WAAWC;QAC1B,OAAO;YACLD,SAASzB,OAAO0B;QAClB;IACF;IACA,IAAIA,YAAYG,MAAM,KAAK,KAAK,CAACJ,QAAQ;QACtC,CAACA,OAAO,GAAGC;IACd;IAEA,OAAOD;AACT"}
1
+ {"version":3,"sources":["../../src/queries/parseParams.ts"],"sourcesContent":["/* eslint-disable no-await-in-loop */\nimport type { SQL } from 'drizzle-orm'\nimport type { Field, Operator, Where } from 'payload/types'\n\nimport { and, ilike, isNotNull, isNull, ne, notInArray, or, sql } from 'drizzle-orm'\nimport { QueryError } from 'payload/errors'\nimport { validOperators } from 'payload/types'\n\nimport type { GenericColumn, PostgresAdapter } from '../types.js'\nimport type { BuildQueryJoinAliases } from './buildQuery.js'\n\nimport { buildAndOrConditions } from './buildAndOrConditions.js'\nimport { convertPathToJSONTraversal } from './createJSONQuery/convertPathToJSONTraversal.js'\nimport { createJSONQuery } from './createJSONQuery/index.js'\nimport { getTableColumnFromPath } from './getTableColumnFromPath.js'\nimport { operatorMap } from './operatorMap.js'\nimport { sanitizeQueryValue } from './sanitizeQueryValue.js'\n\ntype Args = {\n adapter: PostgresAdapter\n fields: Field[]\n joins: BuildQueryJoinAliases\n locale: string\n selectFields: Record<string, GenericColumn>\n tableName: string\n where: Where\n}\n\nexport async function parseParams({\n adapter,\n fields,\n joins,\n locale,\n selectFields,\n tableName,\n where,\n}: Args): Promise<SQL> {\n let result: SQL\n const constraints: SQL[] = []\n\n if (typeof where === 'object' && Object.keys(where).length > 0) {\n // We need to determine if the whereKey is an AND, OR, or a schema path\n for (const relationOrPath of Object.keys(where)) {\n if (relationOrPath) {\n const condition = where[relationOrPath]\n let conditionOperator: 'and' | 'or'\n if (relationOrPath.toLowerCase() === 'and') {\n conditionOperator = 'and'\n } else if (relationOrPath.toLowerCase() === 'or') {\n conditionOperator = 'or'\n }\n if (Array.isArray(condition)) {\n const builtConditions = await buildAndOrConditions({\n adapter,\n fields,\n joins,\n locale,\n selectFields,\n tableName,\n where: condition,\n })\n if (builtConditions.length > 0) {\n result = operatorMap[conditionOperator](...builtConditions)\n }\n } else {\n // It's a path - and there can be multiple comparisons on a single path.\n // For example - title like 'test' and title not equal to 'tester'\n // So we need to loop on keys again here to handle each operator independently\n const pathOperators = where[relationOrPath]\n if (typeof pathOperators === 'object') {\n for (let operator of Object.keys(pathOperators)) {\n if (validOperators.includes(operator as Operator)) {\n const val = where[relationOrPath][operator]\n const {\n columnName,\n constraints: queryConstraints,\n field,\n getNotNullColumnByValue,\n pathSegments,\n rawColumn,\n table,\n } = getTableColumnFromPath({\n adapter,\n collectionPath: relationOrPath,\n fields,\n joins,\n locale,\n pathSegments: relationOrPath.replace(/__/g, '.').split('.'),\n selectFields,\n tableName,\n value: val,\n })\n\n queryConstraints.forEach(({ columnName: col, table: constraintTable, value }) => {\n if (typeof value === 'string' && value.indexOf('%') > -1) {\n constraints.push(operatorMap.like(constraintTable[col], value))\n } else {\n constraints.push(operatorMap.equals(constraintTable[col], value))\n }\n })\n\n if (\n ['json', 'richText'].includes(field.type) &&\n Array.isArray(pathSegments) &&\n pathSegments.length > 1\n ) {\n const segments = pathSegments.slice(1)\n segments.unshift(table[columnName].name)\n\n if (field.type === 'richText') {\n const jsonQuery = createJSONQuery({\n operator,\n pathSegments: segments,\n treatAsArray: ['children'],\n treatRootAsArray: true,\n value: val,\n })\n\n constraints.push(sql.raw(jsonQuery))\n break\n }\n\n const jsonQuery = convertPathToJSONTraversal(pathSegments)\n const operatorKeys = {\n contains: { operator: 'ilike', wildcard: '%' },\n equals: { operator: '=', wildcard: '' },\n exists: { operator: val === true ? 'is not null' : 'is null' },\n like: { operator: 'like', wildcard: '%' },\n not_equals: { operator: '<>', wildcard: '' },\n }\n let formattedValue = `'${operatorKeys[operator].wildcard}${val}${operatorKeys[operator].wildcard}'`\n\n if (operator === 'exists') {\n formattedValue = ''\n }\n\n constraints.push(\n sql.raw(\n `${table[columnName].name}${jsonQuery} ${operatorKeys[operator].operator} ${formattedValue}`,\n ),\n )\n\n break\n }\n\n if (getNotNullColumnByValue) {\n const columnName = getNotNullColumnByValue(val)\n if (columnName) {\n constraints.push(isNotNull(table[columnName]))\n } else {\n throw new QueryError([{ path: relationOrPath }])\n }\n break\n }\n\n if (\n operator === 'like' &&\n (field.type === 'number' || table[columnName].columnType === 'PgUUID')\n ) {\n operator = 'equals'\n }\n\n if (operator === 'like') {\n constraints.push(\n and(...val.split(' ').map((word) => ilike(table[columnName], `%${word}%`))),\n )\n break\n }\n\n const sanitizedQueryValue = sanitizeQueryValue({\n adapter,\n field,\n operator,\n relationOrPath,\n val,\n })\n\n if (sanitizedQueryValue === null) {\n break\n }\n\n const { operator: queryOperator, value: queryValue } = sanitizedQueryValue\n\n if (queryOperator === 'not_equals' && queryValue !== null) {\n constraints.push(\n or(\n isNull(rawColumn || table[columnName]),\n /* eslint-disable @typescript-eslint/no-explicit-any */\n ne<any>(rawColumn || table[columnName], queryValue),\n ),\n )\n break\n }\n\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n Array.isArray(queryValue) &&\n operator === 'not_in'\n ) {\n constraints.push(\n sql`(${notInArray(table[columnName], queryValue)} OR\n ${table[columnName]}\n IS\n NULL)`,\n )\n\n break\n }\n\n if (operator === 'equals' && queryValue === null) {\n constraints.push(isNull(rawColumn || table[columnName]))\n break\n }\n\n if (operator === 'not_equals' && queryValue === null) {\n constraints.push(isNotNull(rawColumn || table[columnName]))\n break\n }\n\n constraints.push(\n operatorMap[queryOperator](rawColumn || table[columnName], queryValue),\n )\n }\n }\n }\n }\n }\n }\n }\n if (constraints.length > 0) {\n if (result) {\n result = and(result, ...constraints)\n } else {\n result = and(...constraints)\n }\n }\n if (constraints.length === 1 && !result) {\n ;[result] = constraints\n }\n\n return result\n}\n"],"names":["and","ilike","isNotNull","isNull","ne","notInArray","or","sql","QueryError","validOperators","buildAndOrConditions","convertPathToJSONTraversal","createJSONQuery","getTableColumnFromPath","operatorMap","sanitizeQueryValue","parseParams","adapter","fields","joins","locale","selectFields","tableName","where","result","constraints","Object","keys","length","relationOrPath","condition","conditionOperator","toLowerCase","Array","isArray","builtConditions","pathOperators","operator","includes","val","columnName","queryConstraints","field","getNotNullColumnByValue","pathSegments","rawColumn","table","collectionPath","replace","split","value","forEach","col","constraintTable","indexOf","push","like","equals","type","segments","slice","unshift","name","jsonQuery","treatAsArray","treatRootAsArray","raw","operatorKeys","contains","wildcard","exists","not_equals","formattedValue","path","columnType","map","word","sanitizedQueryValue","queryOperator","queryValue"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,mCAAmC,GAInC,SAASA,GAAG,EAAEC,KAAK,EAAEC,SAAS,EAAEC,MAAM,EAAEC,EAAE,EAAEC,UAAU,EAAEC,EAAE,EAAEC,GAAG,QAAQ,cAAa;AACpF,SAASC,UAAU,QAAQ,iBAAgB;AAC3C,SAASC,cAAc,QAAQ,gBAAe;AAK9C,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,sBAAsB,QAAQ,8BAA6B;AACpE,SAASC,WAAW,QAAQ,mBAAkB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GAAGF;gCAEvD,IAAIC,kBAAkB,gBAAgBC,eAAe,MAAM;oCACzDtD,YAAY8B,IAAI,CACdjD,GACEH,OAAO0C,aAAaC,KAAK,CAACN,WAAW,GACrC,qDAAqD,GACrDpC,GAAQyC,aAAaC,KAAK,CAACN,WAAW,EAAEuC;oCAG5C;gCACF;gCAEA,IACE,AAACrC,CAAAA,MAAMgB,IAAI,KAAK,kBAAkBhB,MAAMgB,IAAI,KAAK,QAAO,KACxDzB,MAAMC,OAAO,CAAC6C,eACd1C,aAAa,UACb;oCACAZ,YAAY8B,IAAI,CACdhD,GAAG,CAAC,CAAC,EAAEF,WAAWyC,KAAK,CAACN,WAAW,EAAEuC,YAAY;oBACjD,EAAEjC,KAAK,CAACN,WAAW,CAAC;;yBAEf,CAAC;oCAGR;gCACF;gCAEA,IAAIH,aAAa,YAAY0C,eAAe,MAAM;oCAChDtD,YAAY8B,IAAI,CAACpD,OAAO0C,aAAaC,KAAK,CAACN,WAAW;oCACtD;gCACF;gCAEA,IAAIH,aAAa,gBAAgB0C,eAAe,MAAM;oCACpDtD,YAAY8B,IAAI,CAACrD,UAAU2C,aAAaC,KAAK,CAACN,WAAW;oCACzD;gCACF;gCAEAf,YAAY8B,IAAI,CACdzC,WAAW,CAACgE,cAAc,CAACjC,aAAaC,KAAK,CAACN,WAAW,EAAEuC;4BAE/D;wBACF;oBACF;gBACF;YACF;QACF;IACF;IACA,IAAItD,YAAYG,MAAM,GAAG,GAAG;QAC1B,IAAIJ,QAAQ;YACVA,SAASxB,IAAIwB,WAAWC;QAC1B,OAAO;YACLD,SAASxB,OAAOyB;QAClB;IACF;IACA,IAAIA,YAAYG,MAAM,KAAK,KAAK,CAACJ,QAAQ;QACtC,CAACA,OAAO,GAAGC;IACd;IAEA,OAAOD;AACT"}
@@ -1,14 +1,13 @@
1
1
  import type { QueryPromise, SQL } from 'drizzle-orm';
2
2
  import type { ChainedMethods } from '../find/chainMethods.js';
3
3
  import type { DrizzleDB, PostgresAdapter } from '../types.js';
4
- import type { BuildQueryJoinAliases, BuildQueryJoins } from './buildQuery.js';
4
+ import type { BuildQueryJoinAliases } from './buildQuery.js';
5
5
  import { type GenericColumn } from '../types.js';
6
6
  type Args = {
7
7
  adapter: PostgresAdapter;
8
8
  chainedMethods?: ChainedMethods;
9
9
  db: DrizzleDB;
10
- joinAliases: BuildQueryJoinAliases;
11
- joins: BuildQueryJoins;
10
+ joins: BuildQueryJoinAliases;
12
11
  selectFields: Record<string, GenericColumn>;
13
12
  tableName: string;
14
13
  where: SQL;
@@ -16,7 +15,7 @@ type Args = {
16
15
  /**
17
16
  * Selects distinct records from a table only if there are joins that need to be used, otherwise return null
18
17
  */
19
- export declare const selectDistinct: ({ adapter, chainedMethods, db, joinAliases, joins, selectFields, tableName, where, }: Args) => QueryPromise<Record<string, GenericColumn> & {
18
+ export declare const selectDistinct: ({ adapter, chainedMethods, db, joins, selectFields, tableName, where, }: Args) => QueryPromise<Record<string, GenericColumn> & {
20
19
  id: number | string;
21
20
  }[]>;
22
21
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"selectDistinct.d.ts","sourceRoot":"","sources":["../../src/queries/selectDistinct.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAC7D,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC7D,OAAO,KAAK,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAG7E,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAA;AAEhD,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,cAAc,CAAC,EAAE,cAAc,CAAA;IAC/B,EAAE,EAAE,SAAS,CAAA;IACb,WAAW,EAAE,qBAAqB,CAAA;IAClC,KAAK,EAAE,eAAe,CAAA;IACtB,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAA;IAC3C,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,GAAG,CAAA;CACX,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,cAAc,yFASxB,IAAI,KAAG,aAAa,OAAO,MAAM,EAAE,aAAa,CAAC,GAAG;IAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,EAAE,CA2B/E,CAAA"}
1
+ {"version":3,"file":"selectDistinct.d.ts","sourceRoot":"","sources":["../../src/queries/selectDistinct.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAC7D,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC7D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAA;AAG5D,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAA;AAEhD,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,cAAc,CAAC,EAAE,cAAc,CAAA;IAC/B,EAAE,EAAE,SAAS,CAAA;IACb,KAAK,EAAE,qBAAqB,CAAA;IAC5B,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAA;IAC3C,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,GAAG,CAAA;CACX,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,cAAc,4EAQxB,IAAI,KAAG,aAAa,OAAO,MAAM,EAAE,aAAa,CAAC,GAAG;IAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,EAAE,CAkB/E,CAAA"}
@@ -1,8 +1,8 @@
1
1
  import { chainMethods } from '../find/chainMethods.js';
2
2
  /**
3
3
  * Selects distinct records from a table only if there are joins that need to be used, otherwise return null
4
- */ export const selectDistinct = ({ adapter, chainedMethods = [], db, joinAliases, joins, selectFields, tableName, where })=>{
5
- if (Object.keys(joins).length > 0 || joinAliases.length > 0) {
4
+ */ export const selectDistinct = ({ adapter, chainedMethods = [], db, joins, selectFields, tableName, where })=>{
5
+ if (Object.keys(joins).length > 0) {
6
6
  if (where) {
7
7
  chainedMethods.push({
8
8
  args: [
@@ -11,7 +11,7 @@ import { chainMethods } from '../find/chainMethods.js';
11
11
  method: 'where'
12
12
  });
13
13
  }
14
- joinAliases.forEach(({ condition, table })=>{
14
+ joins.forEach(({ condition, table })=>{
15
15
  chainedMethods.push({
16
16
  args: [
17
17
  table,
@@ -20,17 +20,6 @@ import { chainMethods } from '../find/chainMethods.js';
20
20
  method: 'leftJoin'
21
21
  });
22
22
  });
23
- Object.entries(joins).forEach(([joinTable, condition])=>{
24
- if (joinTable) {
25
- chainedMethods.push({
26
- args: [
27
- adapter.tables[joinTable],
28
- condition
29
- ],
30
- method: 'leftJoin'
31
- });
32
- }
33
- });
34
23
  return chainMethods({
35
24
  methods: chainedMethods,
36
25
  query: db.selectDistinct(selectFields).from(adapter.tables[tableName])
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/queries/selectDistinct.ts"],"sourcesContent":["import type { QueryPromise, SQL } from 'drizzle-orm'\n\nimport type { ChainedMethods } from '../find/chainMethods.js'\nimport type { DrizzleDB, PostgresAdapter } from '../types.js'\nimport type { BuildQueryJoinAliases, BuildQueryJoins } from './buildQuery.js'\n\nimport { chainMethods } from '../find/chainMethods.js'\nimport { type GenericColumn } from '../types.js'\n\ntype Args = {\n adapter: PostgresAdapter\n chainedMethods?: ChainedMethods\n db: DrizzleDB\n joinAliases: BuildQueryJoinAliases\n joins: BuildQueryJoins\n selectFields: Record<string, GenericColumn>\n tableName: string\n where: SQL\n}\n\n/**\n * Selects distinct records from a table only if there are joins that need to be used, otherwise return null\n */\nexport const selectDistinct = ({\n adapter,\n chainedMethods = [],\n db,\n joinAliases,\n joins,\n selectFields,\n tableName,\n where,\n}: Args): QueryPromise<Record<string, GenericColumn> & { id: number | string }[]> => {\n if (Object.keys(joins).length > 0 || joinAliases.length > 0) {\n if (where) {\n chainedMethods.push({ args: [where], method: 'where' })\n }\n\n joinAliases.forEach(({ condition, table }) => {\n chainedMethods.push({\n args: [table, condition],\n method: 'leftJoin',\n })\n })\n\n Object.entries(joins).forEach(([joinTable, condition]) => {\n if (joinTable) {\n chainedMethods.push({\n args: [adapter.tables[joinTable], condition],\n method: 'leftJoin',\n })\n }\n })\n\n return chainMethods({\n methods: chainedMethods,\n query: db.selectDistinct(selectFields).from(adapter.tables[tableName]),\n })\n }\n}\n"],"names":["chainMethods","selectDistinct","adapter","chainedMethods","db","joinAliases","joins","selectFields","tableName","where","Object","keys","length","push","args","method","forEach","condition","table","entries","joinTable","tables","methods","query","from"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAMA,SAASA,YAAY,QAAQ,0BAAyB;AActD;;CAEC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,OAAO,EACPC,iBAAiB,EAAE,EACnBC,EAAE,EACFC,WAAW,EACXC,KAAK,EACLC,YAAY,EACZC,SAAS,EACTC,KAAK,EACA;IACL,IAAIC,OAAOC,IAAI,CAACL,OAAOM,MAAM,GAAG,KAAKP,YAAYO,MAAM,GAAG,GAAG;QAC3D,IAAIH,OAAO;YACTN,eAAeU,IAAI,CAAC;gBAAEC,MAAM;oBAACL;iBAAM;gBAAEM,QAAQ;YAAQ;QACvD;QAEAV,YAAYW,OAAO,CAAC,CAAC,EAAEC,SAAS,EAAEC,KAAK,EAAE;YACvCf,eAAeU,IAAI,CAAC;gBAClBC,MAAM;oBAACI;oBAAOD;iBAAU;gBACxBF,QAAQ;YACV;QACF;QAEAL,OAAOS,OAAO,CAACb,OAAOU,OAAO,CAAC,CAAC,CAACI,WAAWH,UAAU;YACnD,IAAIG,WAAW;gBACbjB,eAAeU,IAAI,CAAC;oBAClBC,MAAM;wBAACZ,QAAQmB,MAAM,CAACD,UAAU;wBAAEH;qBAAU;oBAC5CF,QAAQ;gBACV;YACF;QACF;QAEA,OAAOf,aAAa;YAClBsB,SAASnB;YACToB,OAAOnB,GAAGH,cAAc,CAACM,cAAciB,IAAI,CAACtB,QAAQmB,MAAM,CAACb,UAAU;QACvE;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/queries/selectDistinct.ts"],"sourcesContent":["import type { QueryPromise, SQL } from 'drizzle-orm'\n\nimport type { ChainedMethods } from '../find/chainMethods.js'\nimport type { DrizzleDB, PostgresAdapter } from '../types.js'\nimport type { BuildQueryJoinAliases } from './buildQuery.js'\n\nimport { chainMethods } from '../find/chainMethods.js'\nimport { type GenericColumn } from '../types.js'\n\ntype Args = {\n adapter: PostgresAdapter\n chainedMethods?: ChainedMethods\n db: DrizzleDB\n joins: BuildQueryJoinAliases\n selectFields: Record<string, GenericColumn>\n tableName: string\n where: SQL\n}\n\n/**\n * Selects distinct records from a table only if there are joins that need to be used, otherwise return null\n */\nexport const selectDistinct = ({\n adapter,\n chainedMethods = [],\n db,\n joins,\n selectFields,\n tableName,\n where,\n}: Args): QueryPromise<Record<string, GenericColumn> & { id: number | string }[]> => {\n if (Object.keys(joins).length > 0) {\n if (where) {\n chainedMethods.push({ args: [where], method: 'where' })\n }\n\n joins.forEach(({ condition, table }) => {\n chainedMethods.push({\n args: [table, condition],\n method: 'leftJoin',\n })\n })\n\n return chainMethods({\n methods: chainedMethods,\n query: db.selectDistinct(selectFields).from(adapter.tables[tableName]),\n })\n }\n}\n"],"names":["chainMethods","selectDistinct","adapter","chainedMethods","db","joins","selectFields","tableName","where","Object","keys","length","push","args","method","forEach","condition","table","methods","query","from","tables"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAMA,SAASA,YAAY,QAAQ,0BAAyB;AAatD;;CAEC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,OAAO,EACPC,iBAAiB,EAAE,EACnBC,EAAE,EACFC,KAAK,EACLC,YAAY,EACZC,SAAS,EACTC,KAAK,EACA;IACL,IAAIC,OAAOC,IAAI,CAACL,OAAOM,MAAM,GAAG,GAAG;QACjC,IAAIH,OAAO;YACTL,eAAeS,IAAI,CAAC;gBAAEC,MAAM;oBAACL;iBAAM;gBAAEM,QAAQ;YAAQ;QACvD;QAEAT,MAAMU,OAAO,CAAC,CAAC,EAAEC,SAAS,EAAEC,KAAK,EAAE;YACjCd,eAAeS,IAAI,CAAC;gBAClBC,MAAM;oBAACI;oBAAOD;iBAAU;gBACxBF,QAAQ;YACV;QACF;QAEA,OAAOd,aAAa;YAClBkB,SAASf;YACTgB,OAAOf,GAAGH,cAAc,CAACK,cAAcc,IAAI,CAAClB,QAAQmB,MAAM,CAACd,UAAU;QACvE;IACF;AACF,EAAC"}
@@ -2,17 +2,21 @@ import type { ForeignKeyBuilder, IndexBuilder, PgColumnBuilder, UniqueConstraint
2
2
  import type { Field } from 'payload/types';
3
3
  import type { GenericColumns, PostgresAdapter } from '../types.js';
4
4
  export type BaseExtraConfig = Record<string, (cols: GenericColumns) => ForeignKeyBuilder | IndexBuilder | UniqueConstraintBuilder>;
5
+ export type RelationMap = Map<string, {
6
+ localized: boolean;
7
+ target: string;
8
+ type: 'many' | 'one';
9
+ }>;
5
10
  type Args = {
6
11
  adapter: PostgresAdapter;
7
12
  baseColumns?: Record<string, PgColumnBuilder>;
8
13
  baseExtraConfig?: BaseExtraConfig;
9
14
  buildNumbers?: boolean;
10
15
  buildRelationships?: boolean;
11
- buildTexts?: boolean;
12
16
  disableNotNull: boolean;
13
17
  disableUnique: boolean;
14
18
  fields: Field[];
15
- rootRelationsToBuild?: Map<string, string>;
19
+ rootRelationsToBuild?: RelationMap;
16
20
  rootRelationships?: Set<string>;
17
21
  rootTableIDColType?: string;
18
22
  rootTableName?: string;
@@ -23,8 +27,8 @@ type Args = {
23
27
  type Result = {
24
28
  hasManyNumberField: 'index' | boolean;
25
29
  hasManyTextField: 'index' | boolean;
26
- relationsToBuild: Map<string, string>;
30
+ relationsToBuild: RelationMap;
27
31
  };
28
- export declare const buildTable: ({ adapter, baseColumns, baseExtraConfig, buildNumbers, buildRelationships, buildTexts, disableNotNull, disableUnique, fields, rootRelationsToBuild, rootRelationships, rootTableIDColType, rootTableName: incomingRootTableName, tableName, timestamps, versions, }: Args) => Result;
32
+ export declare const buildTable: ({ adapter, baseColumns, baseExtraConfig, disableNotNull, disableUnique, fields, rootRelationsToBuild, rootRelationships, rootTableIDColType, rootTableName: incomingRootTableName, tableName, timestamps, versions, }: Args) => Result;
29
33
  export {};
30
34
  //# sourceMappingURL=build.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/schema/build.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,iBAAiB,EACjB,YAAY,EACZ,eAAe,EAEf,uBAAuB,EACxB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAA;AAe1C,OAAO,KAAK,EAAE,cAAc,EAAwB,eAAe,EAAE,MAAM,aAAa,CAAA;AAOxF,MAAM,MAAM,eAAe,GAAG,MAAM,CAClC,MAAM,EACN,CAAC,IAAI,EAAE,cAAc,KAAK,iBAAiB,GAAG,YAAY,GAAG,uBAAuB,CACrF,CAAA;AAED,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;IAC7C,eAAe,CAAC,EAAE,eAAe,CAAA;IACjC,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,cAAc,EAAE,OAAO,CAAA;IACvB,aAAa,EAAE,OAAO,CAAA;IACtB,MAAM,EAAE,KAAK,EAAE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EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;IAC7C,eAAe,CAAC,EAAE,eAAe,CAAA;IACjC,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,cAAc,EAAE,OAAO,CAAA;IACvB,aAAa,EAAE,OAAO,CAAA;IACtB,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,oBAAoB,CAAC,EAAE,WAAW,CAAA;IAClC,iBAAiB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IAC/B,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,SAAS,EAAE,MAAM,CAAA;IACjB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,QAAQ,EAAE,OAAO,CAAA;CAClB,CAAA;AAED,KAAK,MAAM,GAAG;IACZ,kBAAkB,EAAE,OAAO,GAAG,OAAO,CAAA;IACrC,gBAAgB,EAAE,OAAO,GAAG,OAAO,CAAA;IACnC,gBAAgB,EAAE,WAAW,CAAA;CAC9B,CAAA;AAED,eAAO,MAAM,UAAU,0NAcpB,IAAI,KAAG,MAqYT,CAAA"}
@@ -5,7 +5,8 @@ import { createTableName } from './createTableName.js';
5
5
  import { parentIDColumnMap } from './parentIDColumnMap.js';
6
6
  import { setColumnID } from './setColumnID.js';
7
7
  import { traverseFields } from './traverseFields.js';
8
- export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, buildNumbers, buildRelationships, buildTexts, disableNotNull, disableUnique = false, fields, rootRelationsToBuild, rootRelationships, rootTableIDColType, rootTableName: incomingRootTableName, tableName, timestamps, versions })=>{
8
+ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, disableNotNull, disableUnique = false, fields, rootRelationsToBuild, rootRelationships, rootTableIDColType, rootTableName: incomingRootTableName, tableName, timestamps, versions })=>{
9
+ const isRoot = !incomingRootTableName;
9
10
  const rootTableName = incomingRootTableName || tableName;
10
11
  const columns = baseColumns;
11
12
  const indexes = {};
@@ -26,9 +27,6 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
26
27
  });
27
28
  const { hasLocalizedField, hasLocalizedManyNumberField, hasLocalizedManyTextField, hasLocalizedRelationshipField, hasManyNumberField, hasManyTextField } = traverseFields({
28
29
  adapter,
29
- buildNumbers,
30
- buildRelationships,
31
- buildTexts,
32
30
  columns,
33
31
  disableNotNull,
34
32
  disableUnique,
@@ -45,6 +43,16 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
45
43
  rootTableName,
46
44
  versions
47
45
  });
46
+ // split the relationsToBuild by localized and non-localized
47
+ const localizedRelations = new Map();
48
+ const nonLocalizedRelations = new Map();
49
+ relationsToBuild.forEach(({ type, localized, target }, key)=>{
50
+ const map = localized ? localizedRelations : nonLocalizedRelations;
51
+ map.set(key, {
52
+ type,
53
+ target
54
+ });
55
+ });
48
56
  if (timestamps) {
49
57
  columns.createdAt = timestamp('created_at', {
50
58
  mode: 'string',
@@ -69,7 +77,7 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
69
77
  return result;
70
78
  });
71
79
  adapter.tables[tableName] = table;
72
- if (hasLocalizedField) {
80
+ if (hasLocalizedField || localizedRelations.size) {
73
81
  const localeTableName = `${tableName}${adapter.localesSuffix}`;
74
82
  localesColumns.id = serial('id').primaryKey();
75
83
  localesColumns._locale = adapter.enums.enum__locales('_locale').notNull();
@@ -92,111 +100,132 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
92
100
  });
93
101
  });
94
102
  adapter.tables[localeTableName] = localesTable;
95
- const localesTableRelations = relations(localesTable, ({ one })=>({
96
- _parentID: one(table, {
97
- fields: [
98
- localesTable._parentID
99
- ],
100
- references: [
101
- table.id
102
- ]
103
- })
104
- }));
105
- adapter.relations[`relations_${localeTableName}`] = localesTableRelations;
103
+ adapter.relations[`relations_${localeTableName}`] = relations(localesTable, ({ many, one })=>{
104
+ const result = {};
105
+ result._parentID = one(table, {
106
+ fields: [
107
+ localesTable._parentID
108
+ ],
109
+ references: [
110
+ table.id
111
+ ],
112
+ // name the relationship by what the many() relationName is
113
+ relationName: '_locales'
114
+ });
115
+ localizedRelations.forEach(({ type, target }, key)=>{
116
+ if (type === 'one') {
117
+ result[key] = one(adapter.tables[target], {
118
+ fields: [
119
+ localesTable[key]
120
+ ],
121
+ references: [
122
+ adapter.tables[target].id
123
+ ],
124
+ relationName: key
125
+ });
126
+ }
127
+ if (type === 'many') {
128
+ result[key] = many(adapter.tables[target], {
129
+ relationName: key
130
+ });
131
+ }
132
+ });
133
+ return result;
134
+ });
106
135
  }
107
- if (hasManyTextField && buildTexts) {
108
- const textsTableName = `${rootTableName}_texts`;
109
- const columns = {
110
- id: serial('id').primaryKey(),
111
- order: integer('order').notNull(),
112
- parent: parentIDColumnMap[idColType]('parent_id').notNull(),
113
- path: varchar('path').notNull(),
114
- text: varchar('text')
115
- };
116
- if (hasLocalizedManyTextField) {
117
- columns.locale = adapter.enums.enum__locales('locale');
118
- }
119
- textsTable = adapter.pgSchema.table(textsTableName, columns, (cols)=>{
120
- const config = {
121
- orderParentIdx: index(`${textsTableName}_order_parent_idx`).on(cols.order, cols.parent),
122
- parentFk: foreignKey({
123
- name: `${textsTableName}_parent_fk`,
124
- columns: [
125
- cols.parent
126
- ],
127
- foreignColumns: [
128
- table.id
129
- ]
130
- }).onDelete('cascade')
136
+ if (isRoot) {
137
+ if (hasManyTextField) {
138
+ const textsTableName = `${rootTableName}_texts`;
139
+ const columns = {
140
+ id: serial('id').primaryKey(),
141
+ order: integer('order').notNull(),
142
+ parent: parentIDColumnMap[idColType]('parent_id').notNull(),
143
+ path: varchar('path').notNull(),
144
+ text: varchar('text')
131
145
  };
132
- if (hasManyTextField === 'index') {
133
- config.text_idx = index(`${textsTableName}_text_idx`).on(cols.text);
134
- }
135
146
  if (hasLocalizedManyTextField) {
136
- config.localeParent = index(`${textsTableName}_locale_parent`).on(cols.locale, cols.parent);
147
+ columns.locale = adapter.enums.enum__locales('locale');
137
148
  }
138
- return config;
139
- });
140
- adapter.tables[textsTableName] = textsTable;
141
- const textsTableRelations = relations(textsTable, ({ one })=>({
142
- parent: one(table, {
143
- fields: [
144
- textsTable.parent
145
- ],
146
- references: [
147
- table.id
148
- ]
149
- })
150
- }));
151
- adapter.relations[`relations_${textsTableName}`] = textsTableRelations;
152
- }
153
- if (hasManyNumberField && buildNumbers) {
154
- const numbersTableName = `${rootTableName}_numbers`;
155
- const columns = {
156
- id: serial('id').primaryKey(),
157
- number: numeric('number'),
158
- order: integer('order').notNull(),
159
- parent: parentIDColumnMap[idColType]('parent_id').notNull(),
160
- path: varchar('path').notNull()
161
- };
162
- if (hasLocalizedManyNumberField) {
163
- columns.locale = adapter.enums.enum__locales('locale');
149
+ textsTable = adapter.pgSchema.table(textsTableName, columns, (cols)=>{
150
+ const config = {
151
+ orderParentIdx: index(`${textsTableName}_order_parent_idx`).on(cols.order, cols.parent),
152
+ parentFk: foreignKey({
153
+ name: `${textsTableName}_parent_fk`,
154
+ columns: [
155
+ cols.parent
156
+ ],
157
+ foreignColumns: [
158
+ table.id
159
+ ]
160
+ }).onDelete('cascade')
161
+ };
162
+ if (hasManyTextField === 'index') {
163
+ config.text_idx = index(`${textsTableName}_text_idx`).on(cols.text);
164
+ }
165
+ if (hasLocalizedManyTextField) {
166
+ config.localeParent = index(`${textsTableName}_locale_parent`).on(cols.locale, cols.parent);
167
+ }
168
+ return config;
169
+ });
170
+ adapter.tables[textsTableName] = textsTable;
171
+ adapter.relations[`relations_${textsTableName}`] = relations(textsTable, ({ one })=>({
172
+ parent: one(table, {
173
+ fields: [
174
+ textsTable.parent
175
+ ],
176
+ references: [
177
+ table.id
178
+ ],
179
+ relationName: '_texts'
180
+ })
181
+ }));
164
182
  }
165
- numbersTable = adapter.pgSchema.table(numbersTableName, columns, (cols)=>{
166
- const config = {
167
- orderParentIdx: index(`${numbersTableName}_order_parent_idx`).on(cols.order, cols.parent),
168
- parentFk: foreignKey({
169
- name: `${numbersTableName}_parent_fk`,
170
- columns: [
171
- cols.parent
172
- ],
173
- foreignColumns: [
174
- table.id
175
- ]
176
- }).onDelete('cascade')
183
+ if (hasManyNumberField) {
184
+ const numbersTableName = `${rootTableName}_numbers`;
185
+ const columns = {
186
+ id: serial('id').primaryKey(),
187
+ number: numeric('number'),
188
+ order: integer('order').notNull(),
189
+ parent: parentIDColumnMap[idColType]('parent_id').notNull(),
190
+ path: varchar('path').notNull()
177
191
  };
178
- if (hasManyNumberField === 'index') {
179
- config.numberIdx = index(`${numbersTableName}_number_idx`).on(cols.number);
180
- }
181
192
  if (hasLocalizedManyNumberField) {
182
- config.localeParent = index(`${numbersTableName}_locale_parent`).on(cols.locale, cols.parent);
193
+ columns.locale = adapter.enums.enum__locales('locale');
183
194
  }
184
- return config;
185
- });
186
- adapter.tables[numbersTableName] = numbersTable;
187
- const numbersTableRelations = relations(numbersTable, ({ one })=>({
188
- parent: one(table, {
189
- fields: [
190
- numbersTable.parent
191
- ],
192
- references: [
193
- table.id
194
- ]
195
- })
196
- }));
197
- adapter.relations[`relations_${numbersTableName}`] = numbersTableRelations;
198
- }
199
- if (buildRelationships) {
195
+ numbersTable = adapter.pgSchema.table(numbersTableName, columns, (cols)=>{
196
+ const config = {
197
+ orderParentIdx: index(`${numbersTableName}_order_parent_idx`).on(cols.order, cols.parent),
198
+ parentFk: foreignKey({
199
+ name: `${numbersTableName}_parent_fk`,
200
+ columns: [
201
+ cols.parent
202
+ ],
203
+ foreignColumns: [
204
+ table.id
205
+ ]
206
+ }).onDelete('cascade')
207
+ };
208
+ if (hasManyNumberField === 'index') {
209
+ config.numberIdx = index(`${numbersTableName}_number_idx`).on(cols.number);
210
+ }
211
+ if (hasLocalizedManyNumberField) {
212
+ config.localeParent = index(`${numbersTableName}_locale_parent`).on(cols.locale, cols.parent);
213
+ }
214
+ return config;
215
+ });
216
+ adapter.tables[numbersTableName] = numbersTable;
217
+ adapter.relations[`relations_${numbersTableName}`] = relations(numbersTable, ({ one })=>({
218
+ parent: one(table, {
219
+ fields: [
220
+ numbersTable.parent
221
+ ],
222
+ references: [
223
+ table.id
224
+ ],
225
+ relationName: '_numbers'
226
+ })
227
+ }));
228
+ }
200
229
  if (relationships.size) {
201
230
  const relationshipColumns = {
202
231
  id: serial('id').primaryKey(),
@@ -255,7 +284,7 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
255
284
  return result;
256
285
  });
257
286
  adapter.tables[relationshipsTableName] = relationshipsTable;
258
- const relationshipsTableRelations = relations(relationshipsTable, ({ one })=>{
287
+ adapter.relations[`relations_${relationshipsTableName}`] = relations(relationshipsTable, ({ one })=>{
259
288
  const result = {
260
289
  parent: one(table, {
261
290
  fields: [
@@ -280,27 +309,48 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
280
309
  ],
281
310
  references: [
282
311
  adapter.tables[relatedTableName].id
283
- ]
312
+ ],
313
+ relationName: relationTo
284
314
  });
285
315
  });
286
316
  return result;
287
317
  });
288
- adapter.relations[`relations_${relationshipsTableName}`] = relationshipsTableRelations;
289
318
  }
290
319
  }
291
- const tableRelations = relations(table, ({ many })=>{
320
+ adapter.relations[`relations_${tableName}`] = relations(table, ({ many, one })=>{
292
321
  const result = {};
293
- relationsToBuild.forEach((val, key)=>{
294
- result[key] = many(adapter.tables[val]);
322
+ nonLocalizedRelations.forEach(({ type, target }, key)=>{
323
+ if (type === 'one') {
324
+ result[key] = one(adapter.tables[target], {
325
+ fields: [
326
+ table[key]
327
+ ],
328
+ references: [
329
+ adapter.tables[target].id
330
+ ],
331
+ relationName: key
332
+ });
333
+ }
334
+ if (type === 'many') {
335
+ result[key] = many(adapter.tables[target], {
336
+ relationName: key
337
+ });
338
+ }
295
339
  });
296
340
  if (hasLocalizedField) {
297
- result._locales = many(localesTable);
341
+ result._locales = many(localesTable, {
342
+ relationName: '_locales'
343
+ });
298
344
  }
299
345
  if (hasManyTextField) {
300
- result._texts = many(textsTable);
346
+ result._texts = many(textsTable, {
347
+ relationName: '_texts'
348
+ });
301
349
  }
302
350
  if (hasManyNumberField) {
303
- result._numbers = many(numbersTable);
351
+ result._numbers = many(numbersTable, {
352
+ relationName: '_numbers'
353
+ });
304
354
  }
305
355
  if (relationships.size && relationshipsTable) {
306
356
  result._rels = many(relationshipsTable, {
@@ -309,7 +359,6 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
309
359
  }
310
360
  return result;
311
361
  });
312
- adapter.relations[`relations_${tableName}`] = tableRelations;
313
362
  return {
314
363
  hasManyNumberField,
315
364
  hasManyTextField,