1 import { IndexTypes } from "@medusajs/framework/types"
2 import {
3 isDefined,
4 isObject,
5 isString,
6 unflattenObjectKeys,
7 } from "@medusajs/framework/utils"
8 import { Knex } from "@medusajs/framework/mikro-orm/knex"
9 import { OrderBy, QueryFormat, QueryOptions, Select } from "@types"
10 import { getPivotTableName, normalizeTableName } from "./normalze-table-name"
11
12 const AND_OPERATOR = "$and"
13 const OR_OPERATOR = "$or"
14 const NOT_OPERATOR = "$not"
15
16 function escapeJsonPathString(val: string): string {
17 // Escape for JSONPath string
18 return val.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/'/g, "\\'")
19 }
20
21 function buildSafeJsonPathQuery(
22 field: string,
23 operator: string,
24 value: any
25 ): string {
26 let jsonPathOperator = operator
27 let caseInsensitiveFlag = ""
28 if (operator === "=") {
29 jsonPathOperator = "=="
30 } else if (operator.toUpperCase().includes("LIKE")) {
31 jsonPathOperator = "like_regex"
32
33 if (operator.toUpperCase() === "ILIKE") {
34 caseInsensitiveFlag = ' flag "i"'
35 }
36 } else if (operator === "IS") {
37 jsonPathOperator = "=="
38 } else if (operator === "IS NOT") {
39 jsonPathOperator = "!="
40 }
41
42 if (typeof value === "string") {
43 let val = value
44 if (jsonPathOperator === "like_regex") {
45 // Convert SQL LIKE wildcards to regex
46 val = val.replace(/%/g, ".*").replace(/_/g, ".")
47 }
48 value = `"${escapeJsonPathString(val)}"`
49 } else {
50 if ((operator === "IS" || operator === "IS NOT") && value === null) {
51 value = "null"
52 }
53 }
54
55 return `$.${field} ${jsonPathOperator} ${value}${caseInsensitiveFlag}`
56 }
57
58 export const OPERATOR_MAP = {
59 $eq: "=",
60 $lt: "<",
61 $gt: ">",
62 $lte: "<=",
63 $gte: ">=",
64 $ne: "!=",
65 $in: "IN",
66 $nin: "NOT IN",
67 $is: "IS",
68 $like: "LIKE",
69 $ilike: "ILIKE",
70 }
71
72 export class QueryBuilder {
73 #searchVectorColumnName = "document_tsv"
74
75 private readonly structure: Select
76 private readonly entityMap: Record<string, any>
77 private readonly knex: Knex
78 private readonly selector: QueryFormat
79 private readonly options?: QueryOptions
80 private readonly schema: IndexTypes.SchemaObjectRepresentation
81 private readonly allSchemaFields: Set<string>
82 private readonly rawConfig?: IndexTypes.IndexQueryConfig<any>
83 private readonly requestedFields: {
84 [key: string]: any
85 }
86 private readonly idsOnly?: boolean
87
88 constructor(args: {
89 schema: IndexTypes.SchemaObjectRepresentation
90 entityMap: Record<string, any>
91 knex: Knex
92 selector: QueryFormat
93 options?: QueryOptions
94 rawConfig?: IndexTypes.IndexQueryConfig<any>
95 requestedFields: {
96 [key: string]: any
97 }
98 idsOnly?: boolean
99 }) {
100 this.schema = args.schema
101 this.entityMap = args.entityMap
102 this.selector = args.selector
103 this.options = args.options
104 this.knex = args.knex
105 this.structure = this.selector.select
106 this.allSchemaFields = new Set(
107 Object.values(this.schema).flatMap((entity) => entity.fields ?? [])
108 )
109 this.rawConfig = args.rawConfig
110 this.requestedFields = args.requestedFields
111 this.idsOnly = args.idsOnly ?? false
112 }
113
114 private isLogicalOperator(key: string) {
115 return key === AND_OPERATOR || key === OR_OPERATOR || key === NOT_OPERATOR
116 }
117
118 private getStructureKeys(structure) {
119 const collectKeys = (obj: any, keys = new Set<string>()) => {
120 if (!isObject(obj)) {
121 return keys
122 }
123
124 Object.keys(obj).forEach((key) => {
125 if (this.isLogicalOperator(key)) {
126 if (Array.isArray(obj[key])) {
127 obj[key].forEach((item) => collectKeys(item, keys))
128 }
129 } else if (key !== "entity") {
130 keys.add(key)
131 }
132 })
133
134 return keys
135 }
136
137 return [...collectKeys(structure ?? {})]
138 }
139
140 private getEntity(
141 path,
142 throwWhenNotFound = true
143 ): IndexTypes.SchemaPropertiesMap[0] | undefined {
144 if (!this.schema._schemaPropertiesMap[path]) {
145 if (!throwWhenNotFound) {
146 return
147 }
148
149 throw new Error(
150 `Could not find entity for path: ${path}. It might not be indexed.`
151 )
152 }
153
154 return this.schema._schemaPropertiesMap[path]
155 }
156
157 private getGraphQLType(path, field) {
158 if (this.isLogicalOperator(field)) {
159 return "JSON"
160 }
161
162 const entity = this.getEntity(path)?.ref?.entity!
163 const fieldRef = this.entityMap[entity]._fields[field]
164
165 if (!fieldRef) {
166 throw new Error(`Field ${field} is not indexed.`)
167 }
168
169 const fieldType = fieldRef.type.toString()
170 const isArray = fieldType.startsWith("[")
171 const currentType = fieldType.replace(/\[|\]|\!/g, "")
172 return currentType + (isArray ? "[]" : "")
173 }
174
175 private transformValueToType(path, field, value) {
176 if (value === null) {
177 return null
178 }
179
180 const typeToFn = {
181 Int: (val) => parseInt(val, 10),
182 Float: (val) => parseFloat(val),
183 String: (val) => String(val),
184 Boolean: (val) => Boolean(val),
185 ID: (val) => String(val),
186 Date: (val) => new Date(val).toISOString(),
187 DateTime: (val) => new Date(val).toISOString(),
188 Time: (val) => new Date(`1970-01-01T${val}Z`).toISOString(),
189 }
190
191 const fullPath = [path, ...field]
192 const prop = fullPath.pop()
193 const fieldPath = fullPath.join(".")
194 const graphqlType = this.getGraphQLType(fieldPath, prop).replace("[]", "")
195
196 const fn = typeToFn[graphqlType]
197 if (Array.isArray(value)) {
198 return value.map((v) => (!fn ? v : fn(v)))
199 }
200 return !fn ? value : fn(value)
201 }
202
203 private getPostgresCastType(path, field) {
204 const graphqlToPostgresTypeMap = {
205 Int: "::int",
206 Float: "::double precision",
207 Boolean: "::boolean",
208 Date: "::timestamp",
209 DateTime: "::timestamp",
210 Time: "::time",
211 "": "",
212 }
213
214 const defaultValues = {
215 Int: "0",
216 Float: "0",
217 Boolean: "false",
218 Date: "1970-01-01 00:00:00",
219 DateTime: "1970-01-01 00:00:00",
220 Time: "00:00:00",
221 "": "",
222 }
223
224 const fullPath = [path, ...field]
225 const prop = fullPath.pop()
226 const fieldPath = fullPath.join(".")
227 let graphqlType = this.getGraphQLType(fieldPath, prop)
228 const isList = graphqlType.endsWith("[]")
229 graphqlType = graphqlType.replace("[]", "")
230
231 const cast =
232 (graphqlToPostgresTypeMap[graphqlType] ?? "") + (isList ? "[]" : "")
233
234 function generateCoalesceExpression(field) {
235 const defaultValue = defaultValues[graphqlType]
236 return `COALESCE(${field}, '${defaultValue}')${cast}`
237 }
238
239 return {
240 cast,
241 coalesce: generateCoalesceExpression,
242 }
243 }
244
245 private parseWhere(
246 aliasMapping: { [path: string]: string },
247 obj: object,
248 builder: Knex.QueryBuilder,
249 parentPath: string = ""
250 ) {
251 const keys = Object.keys(obj)
252
253 const getPathAndField = (key: string) => {
254 const fullKey = parentPath ? `${parentPath}.${key}` : key
255 const path = fullKey.split(".")
256 const field = [path.pop()]
257
258 while (!aliasMapping[path.join(".")] && path.length > 0) {
259 field.unshift(path.pop())
260 }
261
262 const attr = path.join(".")
263
264 return { field, attr }
265 }
266
267 const getPathOperation = (
268 attr: string,
269 path: string[],
270 value: unknown
271 ): string => {
272 const partialPath = path.length > 1 ? path.slice(0, -1) : path
273 const val = this.transformValueToType(attr, partialPath, value)
274 const result = path.reduceRight((acc, key) => {
275 return { [key]: acc }
276 }, val)
277
278 return JSON.stringify(result)
279 }
280
281 keys.forEach((key) => {
282 const pathAsArray = (parentPath ? `${parentPath}.${key}` : key).split(".")
283 const fieldOrLogicalOperator = pathAsArray.pop()!
284 let value = obj[key]
285
286 if (
287 this.isLogicalOperator(fieldOrLogicalOperator) &&
288 !Array.isArray(value)
289 ) {
290 value = [value]
291 }
292
293 if (fieldOrLogicalOperator === AND_OPERATOR && Array.isArray(value)) {
294 builder.where((qb) => {
295 value.forEach((cond) => {
296 qb.andWhere((subBuilder) =>
297 this.parseWhere(
298 aliasMapping,
299 cond,
300 subBuilder,
301 pathAsArray.join(".")
302 )
303 )
304 })
305 })
306 } else if (
307 fieldOrLogicalOperator === OR_OPERATOR &&
308 Array.isArray(value)
309 ) {
310 builder.where((qb) => {
311 value.forEach((cond) => {
312 qb.orWhere((subBuilder) =>
313 this.parseWhere(
314 aliasMapping,
315 cond,
316 subBuilder,
317 pathAsArray.join(".")
318 )
319 )
320 })
321 })
322 } else if (
323 fieldOrLogicalOperator === NOT_OPERATOR &&
324 (Array.isArray(value) || isObject(value))
325 ) {
326 builder.whereNot((qb) => {
327 if (Array.isArray(value)) {
328 value.forEach((cond) => {
329 qb.andWhere((subBuilder) =>
330 this.parseWhere(
331 aliasMapping,
332 cond,
333 subBuilder,
334 pathAsArray.join(".")
335 )
336 )
337 })
338 } else {
339 this.parseWhere(
340 aliasMapping,
341 value as any,
342 qb,
343 pathAsArray.join(".")
344 )
345 }
346 })
347 } else if (
348 isObject(value) &&
349 !Array.isArray(value) &&
350 !this.isLogicalOperator(fieldOrLogicalOperator)
351 ) {
352 const currentPath = parentPath ? `${parentPath}.${key}` : key
353
354 const subKeys = Object.keys(value)
355 const hasOperators = subKeys.some((subKey) => OPERATOR_MAP[subKey])
356
357 if (hasOperators) {
358 const { field, attr } = getPathAndField(key)
359
360 const subKeys = Object.keys(value)
361 subKeys.forEach((subKey) => {
362 let operator = OPERATOR_MAP[subKey]
363 if (operator) {
364 const nested = new Array(field.length).join("->?")
365
366 const subValue = this.transformValueToType(
367 attr,
368 field,
369 value[subKey]
370 )
371
372 let val =
373 operator === "IN" || operator === "NOT IN"
374 ? subValue
375 : [subValue]
376 if (operator === "=" && subValue === null) {
377 operator = "IS"
378 } else if (operator === "!=" && subValue === null) {
379 operator = "IS NOT"
380 }
381
382 if (operator === "=") {
383 const hasId = field[field.length - 1] === "id"
384 if (hasId) {
385 builder.whereRaw(`${aliasMapping[attr]}.id = ?`, subValue)
386 } else {
387 builder.whereRaw(
388 `${aliasMapping[attr]}.data @> ?::jsonb`,
389 [getPathOperation(attr, field as string[], subValue)]
390 )
391 }
392 } else if (operator === "IN" || operator === "NOT IN") {
393 if (val && !Array.isArray(val)) {
394 val = [val]
395 }
396 if (!val || val.length === 0) {
397 return
398 }
399
400 const inPlaceholders = val.map(() => "?").join(",")
401 const hasId = field[field.length - 1] === "id"
402 const isNegated = operator === "NOT IN"
403 if (hasId) {
404 builder.whereRaw(
405 `${aliasMapping[attr]}.id ${
406 isNegated ? "NOT IN" : "IN"
407 } (${inPlaceholders})`,
408 val
409 )
410 } else {
411 const targetField = field[field.length - 1] as string
412
413 const jsonbValues = val.map((item) =>
414 JSON.stringify({
415 [targetField]: item === null ? null : item,
416 })
417 )
418
419 if (isNegated) {
420 builder.whereRaw(
421 `NOT EXISTS (SELECT 1 FROM unnest(ARRAY[${inPlaceholders}]::JSONB[]) AS v(val) WHERE ${aliasMapping[attr]}.data${nested} @> v.val)`,
422 jsonbValues
423 )
424 } else {
425 builder.whereRaw(
426 `${aliasMapping[attr]}.data${nested} @> ANY(ARRAY[${inPlaceholders}]::JSONB[])`,
427 jsonbValues
428 )
429 }
430 }
431 } else {
432 const potentialIdFields = field[field.length - 1]
433 const hasId = potentialIdFields === "id"
434
435 if (hasId) {
436 builder.whereRaw(`(${aliasMapping[attr]}.id) ${operator} ?`, [
437 ...val,
438 ])
439 } else {
440 const targetField = field[field.length - 1] as string
441
442 const jsonPath = buildSafeJsonPathQuery(
443 targetField,
444 operator,
445 val[0]
446 )
447
448 builder.whereRaw(`${aliasMapping[attr]}.data${nested} @@ ?`, [
449 jsonPath,
450 ])
451 }
452 }
453 } else {
454 throw new Error(`Unsupported operator: ${subKey}`)
455 }
456 })
457 } else {
458 this.parseWhere(aliasMapping, value, builder, currentPath)
459 }
460 } else {
461 const { field, attr } = getPathAndField(key)
462 const nested = new Array(field.length).join("->?")
463
464 value = this.transformValueToType(attr, field, value)
465 if (Array.isArray(value)) {
466 if (value.length === 0) {
467 return
468 }
469
470 const inPlaceholders = value.map(() => "?").join(",")
471 const hasId = field[field.length - 1] === "id"
472 if (hasId) {
473 builder.whereRaw(
474 `${aliasMapping[attr]}.id IN (${inPlaceholders})`,
475 [...value]
476 )
477 } else {
478 const targetField = field[field.length - 1] as string
479
480 const jsonbValues = value.map((item) =>
481 JSON.stringify({ [targetField]: item === null ? null : item })
482 )
483 builder.whereRaw(
484 `${aliasMapping[attr]}.data${nested} @> ANY(ARRAY[${inPlaceholders}]::JSONB[])`,
485 jsonbValues
486 )
487 }
488 } else if (isDefined(value)) {
489 let operator = "="
490
491 if (operator === "=") {
492 const hasId = field[field.length - 1] === "id"
493 if (hasId) {
494 builder.whereRaw(`${aliasMapping[attr]}.id = ?`, value)
495 } else {
496 builder.whereRaw(
497 `${aliasMapping[attr]}.data @> ?::jsonb`,
498 [getPathOperation(attr, field as string[], value)]
499 )
500 }
501 } else {
502 if (value === null) {
503 operator = "IS"
504 }
505
506 const hasId = field[field.length - 1] === "id"
507 if (hasId) {
508 builder.whereRaw(`(${aliasMapping[attr]}.id) ${operator} ?`, [
509 value,
510 ])
511 } else {
512 const targetField = field[field.length - 1] as string
513
514 const jsonPath = buildSafeJsonPathQuery(
515 targetField,
516 operator,
517 value
518 )
519 builder.whereRaw(`${aliasMapping[attr]}.data${nested} @@ ?`, [
520 jsonPath,
521 ])
522 }
523 }
524 }
525 }
526 })
527
528 return builder
529 }
530
531 private getShortAlias(aliasMapping, alias, level = 0) {
532 aliasMapping.__aliasIndex ??= 0
533
534 if (aliasMapping[alias]) {
535 return aliasMapping[alias]
536 }
537
538 aliasMapping[alias] =
539 "t_" + aliasMapping.__aliasIndex++ + (level > 0 ? `_${level}` : "")
540
541 return aliasMapping[alias]
542 }
543
544 private buildQueryParts(
545 structure: Select,
546 parentAlias: string,
547 parentEntity: IndexTypes.SchemaObjectEntityRepresentation["parents"][0],
548 parentProperty: string,
549 aliasPath: string[] = [],
550 level = 0,
551 aliasMapping: { [path: string]: string } = {}
552 ): string[] {
553 const currentAliasPath = [...aliasPath, parentProperty].join(".")
554
555 const isSelectableField = this.allSchemaFields.has(parentProperty)
556 const entities = this.getEntity(currentAliasPath, false)
557
558 // !entityRef.alias means the object has not table, it's a nested object
559 if (isSelectableField || !entities || !entities?.ref?.alias) {
560 // We are currently selecting a specific field of the parent entity or the entity is not found on the index schema
561 // We don't need to build the query parts for this as there is no join
562 return []
563 }
564
565 const mainEntity = entities
566 const mainAlias = this.getShortAlias(
567 aliasMapping,
568 mainEntity.ref.entity.toLowerCase(),
569 level
570 )
571
572 const allEntities: {
573 entity: IndexTypes.SchemaPropertiesMap[0]
574 parEntity: IndexTypes.SchemaObjectEntityRepresentation["parents"][0]
575 parAlias: string
576 alias: string
577 }[] = []
578 if (!entities.shortCutOf) {
579 allEntities.push({
580 entity: entities,
581 parEntity: parentEntity,
582 parAlias: parentAlias,
583 alias: mainAlias,
584 })
585 } else {
586 const intermediateAlias = entities.shortCutOf.split(".")
587
588 for (let i = intermediateAlias.length - 1, x = 0; i >= 0; i--, x++) {
589 const intermediateEntity = this.getEntity(
590 intermediateAlias.join("."),
591 false
592 )
593 if (!intermediateEntity) {
594 break
595 }
596
597 intermediateAlias.pop()
598
599 if (intermediateEntity.ref.entity === parentEntity?.ref.entity) {
600 break
601 }
602
603 const parentIntermediateEntity = this.getEntity(
604 intermediateAlias.join(".")
605 )!
606
607 const alias =
608 this.getShortAlias(
609 aliasMapping,
610 intermediateEntity.ref.entity.toLowerCase(),
611 level
612 ) +
613 "_" +
614 x
615
616 const parAlias =
617 parentIntermediateEntity.ref.entity === parentEntity?.ref.entity
618 ? parentAlias
619 : this.getShortAlias(
620 aliasMapping,
621 parentIntermediateEntity.ref.entity.toLowerCase(),
622 level
623 ) +
624 "_" +
625 (x + 1)
626
627 if (x === 0) {
628 aliasMapping[currentAliasPath] = alias
629 }
630
631 allEntities.unshift({
632 entity: intermediateEntity as any,
633 parEntity:
634 parentIntermediateEntity as IndexTypes.SchemaObjectEntityRepresentation["parents"][0],
635 parAlias,
636 alias,
637 })
638 }
639 }
640
641 let queryParts: string[] = []
642 for (const join of allEntities) {
643 const joinBuilder = this.knex.queryBuilder()
644 const { alias, entity, parEntity, parAlias } = join
645
646 aliasMapping[currentAliasPath] = alias
647
648 if (level > 0) {
649 const cName = normalizeTableName(entity.ref.entity)
650
651 let joinTable = `cat_${cName} AS ${alias}`
652
653 if (entity.isInverse || parEntity.isInverse) {
654 const pName =
655 `${entity.ref.entity}${parEntity.ref.entity}`.toLowerCase()
656 const pivotTable = getPivotTableName(pName)
657
658 joinBuilder.leftJoin(
659 `${pivotTable} AS ${alias}_ref`,
660 `${alias}_ref.child_id`,
661 `${parAlias}.id`
662 )
663 joinBuilder.leftJoin(
664 joinTable,
665 `${alias}.id`,
666 `${alias}_ref.parent_id`
667 )
668 } else {
669 const pName =
670 `${parEntity.ref.entity}${entity.ref.entity}`.toLowerCase()
671 const pivotTable = getPivotTableName(pName)
672
673 joinBuilder.leftJoin(
674 `${pivotTable} AS ${alias}_ref`,
675 `${alias}_ref.parent_id`,
676 `${parAlias}.id`
677 )
678 joinBuilder.leftJoin(
679 joinTable,
680 `${alias}.id`,
681 `${alias}_ref.child_id`
682 )
683 }
684
685 const joinWhere = this.selector.joinWhere ?? {}
686 const joinKey = Object.keys(joinWhere).find((key) => {
687 const k = key.split(".")
688 k.pop()
689 const curPath = k.join(".")
690 if (curPath === currentAliasPath) {
691 const relEntity = this.getEntity(curPath, false)
692 return relEntity?.ref?.entity === entity.ref.entity
693 }
694
695 return false
696 })
697
698 if (joinKey) {
699 this.parseWhere(
700 aliasMapping,
701 { [joinKey]: joinWhere[joinKey] },
702 joinBuilder
703 )
704 }
705
706 queryParts.push(
707 joinBuilder.toQuery().replace("select * ", "").replace("where", "and")
708 )
709 }
710 }
711
712 const children = this.getStructureKeys(structure)
713 for (const child of children) {
714 const childStructure = structure[child] as Select
715 queryParts = queryParts
716 .concat(
717 this.buildQueryParts(
718 childStructure,
719 mainAlias,
720 mainEntity as any,
721 child,
722 aliasPath.concat(parentProperty),
723 level + 1,
724 aliasMapping
725 )
726 )
727 .filter(Boolean)
728 }
729
730 return queryParts
731 }
732
733 private buildSelectParts(
734 structure: Select,
735 parentProperty: string,
736 aliasMapping: { [path: string]: string },
737 aliasPath: string[] = [],
738 selectParts: object = {}
739 ): object {
740 const currentAliasPath = [...aliasPath, parentProperty].join(".")
741
742 const isSelectableField = this.allSchemaFields.has(parentProperty)
743 if (isSelectableField) {
744 // We are currently selecting a specific field of the parent entity
745 // Let's remove the parent alias from the select parts to not select everything entirely
746 // and add the specific field to the select parts
747 const parentAliasPath = aliasPath.join(".")
748 const alias = aliasMapping[parentAliasPath]
749 delete selectParts[parentAliasPath]
750
751 if (parentProperty === "id") {
752 selectParts[currentAliasPath] = `${alias}.id`
753 } else if (!this.idsOnly) {
754 selectParts[currentAliasPath] = this.knex.raw(
755 `${alias}.data->'${parentProperty}'`
756 )
757 }
758 return selectParts
759 }
760
761 const alias = aliasMapping[currentAliasPath]
762 // If the entity is not found in the schema (not indexed), we don't need to build the select parts
763 if (!alias) {
764 return selectParts
765 }
766
767 if (!this.idsOnly) {
768 selectParts[currentAliasPath] = `${alias}.data`
769 }
770
771 selectParts[currentAliasPath + ".id"] = `${alias}.id`
772
773 const children = this.getStructureKeys(structure)
774 for (const child of children) {
775 const childStructure = structure[child] as Select
776
777 this.buildSelectParts(
778 childStructure,
779 child,
780 aliasMapping,
781 aliasPath.concat(parentProperty),
782 selectParts
783 )
784 }
785
786 return selectParts
787 }
788
789 private transformOrderBy(arr: (object | string)[]): OrderBy {
790 const result = {}
791 const map = new Map()
792 map.set(true, "ASC")
793 map.set(1, "ASC")
794 map.set("ASC", "ASC")
795 map.set(false, "DESC")
796 map.set(-1, "DESC")
797 map.set("DESC", "DESC")
798
799 function nested(obj, prefix = "") {
800 const keys = Object.keys(obj)
801 if (!keys.length) {
802 return
803 } else if (keys.length > 1) {
804 throw new Error("Order by only supports one key per object.")
805 }
806 const key = keys[0]
807 let value = obj[key]
808 if (isObject(value)) {
809 nested(value, prefix + key + ".")
810 } else {
811 if (isString(value)) {
812 value = value.toUpperCase()
813 }
814 result[prefix + key] = map.get(value) ?? "ASC"
815 }
816 }
817 arr.forEach((obj) => nested(obj))
818
819 return result
820 }
821
822 public buildQuery({
823 hasPagination = true,
824 hasCount = false,
825 }: {
826 hasPagination?: boolean
827 hasCount?: boolean
828 }): { sql: string; sqlCount?: string } {
829 const selectOnlyStructure = this.selector.select
830 const structure = this.requestedFields
831 const filter = this.selector.where ?? {}
832
833 const { orderBy: order, skip, take } = this.options ?? {}
834
835 const orderBy = this.transformOrderBy(
836 (order && !Array.isArray(order) ? [order] : order) ?? []
837 )
838 const take_ = !isNaN(+take!) ? +take! : 15
839 const skip_ = !isNaN(+skip!) ? +skip! : 0
840
841 const rootKey = this.getStructureKeys(structure)[0]
842 const rootStructure = structure[rootKey] as Select
843
844 const entity = this.getEntity(rootKey)!
845 const rootEntity = entity.ref.entity.toLowerCase()
846 const aliasMapping: { [path: string]: string } = {}
847
848 let hasTextSearch: boolean = false
849 let textSearchQuery: string | null = null
850 const searchQueryFilterProp = `${rootKey}.q`
851
852 if (searchQueryFilterProp in filter) {
853 if (!filter[searchQueryFilterProp]) {
854 delete filter[searchQueryFilterProp]
855 } else {
856 hasTextSearch = true
857 textSearchQuery = filter[searchQueryFilterProp]
858 delete filter[searchQueryFilterProp]
859 }
860 }
861
862 const filterSortStructure =
863 unflattenObjectKeys({
864 ...(this.rawConfig?.filters
865 ? unflattenObjectKeys(this.rawConfig?.filters)
866 : {}),
867 ...orderBy,
868 })[rootKey] ?? {}
869
870 const joinParts = this.buildQueryParts(
871 filterSortStructure,
872 "",
873 entity as IndexTypes.SchemaObjectEntityRepresentation["parents"][0],
874 rootKey,
875 [],
876 0,
877 aliasMapping
878 )
879
880 const rootAlias = aliasMapping[rootKey]
881
882 const innerQueryBuilder = this.knex.queryBuilder()
883 // Outer query to select the full data based on the paginated IDs
884 const outerQueryBuilder = this.knex.queryBuilder()
885
886 innerQueryBuilder.distinct(`${rootAlias}.id`)
887
888 const orderBySelects: Array<string | Knex.Raw> = []
889 const orderByClauses: string[] = []
890
891 for (const aliasPath in orderBy) {
892 const path = aliasPath.split(".")
893 const field = path.pop()!
894 const attr = path.join(".")
895 const alias = aliasMapping[attr]
896 const direction = orderBy[aliasPath]
897 const pgType = this.getPostgresCastType(attr, [field])
898 const hasId = field === "id"
899
900 let orderExpression:
901 | string
902 | Knex.Raw<any> = `${rootAlias}.id ${direction}`
903
904 if (alias) {
905 const aggregateAlias = `"${aliasPath}_agg"`
906 let aggregateExpression = `(${alias}.data->>'${field}')${pgType.cast}`
907
908 if (hasId) {
909 aggregateExpression = `${alias}.id`
910 } else {
911 orderBySelects.push(
912 direction === "ASC"
913 ? this.knex.raw(
914 `MIN(${aggregateExpression}) AS ${aggregateAlias}`
915 )
916 : this.knex.raw(
917 `MAX(${aggregateExpression}) AS ${aggregateAlias}`
918 )
919 )
920 orderExpression = `${aggregateAlias} ${direction}`
921 }
922
923 outerQueryBuilder.orderByRaw(`${aggregateExpression} ${direction}`)
924 }
925
926 orderByClauses.push(orderExpression as string)
927 }
928
929 // Add ordering columns to the select list of the inner query
930 if (orderBySelects.length > 0) {
931 innerQueryBuilder.select(orderBySelects)
932 }
933
934 innerQueryBuilder.from(
935 `cat_${normalizeTableName(rootEntity)} AS ${this.getShortAlias(
936 aliasMapping,
937 rootKey
938 )}`
939 )
940
941 joinParts.forEach((joinPart) => {
942 innerQueryBuilder.joinRaw(joinPart)
943 })
944
945 if (hasTextSearch) {
946 const searchWhereParts = [
947 `${rootAlias}.${
948 this.#searchVectorColumnName
949 } @@ plainto_tsquery('simple', ?)`,
950 ...joinParts.flatMap((part) => {
951 const aliases = part
952 .split(" as ")
953 .flatMap((chunk) => chunk.split(" on "))
954 .filter(
955 (alias) => alias.startsWith('"t_') && !alias.includes("_ref")
956 )
957 return aliases.map(
958 (alias) =>
959 `${alias}.${
960 this.#searchVectorColumnName
961 } @@ plainto_tsquery('simple', ?)`
962 )
963 }),
964 ]
965
966 innerQueryBuilder.whereRaw(
967 `(${searchWhereParts.join(" OR ")})`,
968 Array(searchWhereParts.length).fill(textSearchQuery)
969 )
970 }
971
972 this.parseWhere(aliasMapping, filter, innerQueryBuilder)
973
974 // Group by root ID in the inner query
975 if (orderBySelects.length > 0) {
976 innerQueryBuilder.groupBy(`${rootAlias}.id`)
977 }
978
979 if (orderByClauses.length > 0) {
980 innerQueryBuilder.orderByRaw(orderByClauses.join(", "))
981 } else {
982 innerQueryBuilder.orderBy(`${rootAlias}.id`, "ASC")
983 }
984
985 // Count query to estimate the number of results in parallel
986 let countQuery: Knex.Raw | undefined
987 if (hasCount) {
988 const estimateQuery = innerQueryBuilder.clone()
989 estimateQuery.clearSelect().select(1)
990 estimateQuery.clearOrder()
991 estimateQuery.clearCounters()
992
993 countQuery = this.knex.raw(
994 `SELECT count_estimate(?) AS estimate_count`,
995 estimateQuery.toQuery()
996 )
997 }
998
999 // Apply pagination to the inner query
1000 if (hasPagination) {
1001 innerQueryBuilder.limit(take_)
1002 if (skip_ > 0) {
1003 innerQueryBuilder.offset(skip_)
1004 }
1005 }
1006
1007 const innerQueryAlias = "paginated_ids"
1008
1009 outerQueryBuilder.from(
1010 `cat_${normalizeTableName(rootEntity)} AS ${this.getShortAlias(
1011 aliasMapping,
1012 rootKey
1013 )}`
1014 )
1015
1016 outerQueryBuilder.joinRaw(
1017 `INNER JOIN (${innerQueryBuilder.toQuery()}) AS ${innerQueryAlias} ON ${rootAlias}.id = ${innerQueryAlias}.id`
1018 )
1019
1020 this.parseWhere(aliasMapping, filter, outerQueryBuilder)
1021
1022 const joinPartsOuterQuery = this.buildQueryParts(
1023 rootStructure,
1024 "",
1025 entity as IndexTypes.SchemaObjectEntityRepresentation["parents"][0],
1026 rootKey,
1027 [],
1028 0,
1029 aliasMapping
1030 )
1031 joinPartsOuterQuery.forEach((joinPart) => {
1032 outerQueryBuilder.joinRaw(joinPart)
1033 })
1034
1035 const finalSelectParts = this.buildSelectParts(
1036 selectOnlyStructure[rootKey] as Select,
1037 rootKey,
1038 aliasMapping
1039 )
1040
1041 outerQueryBuilder.select(finalSelectParts)
1042
1043 const finalSql = outerQueryBuilder.toQuery()
1044
1045 return {
1046 sql: finalSql,
1047 sqlCount: countQuery?.toQuery?.(),
1048 }
1049 }
1050
1051 public buildObjectFromResultset(
1052 resultSet: Record<string, any>[]
1053 ): Record<string, any>[] {
1054 const structure = this.structure
1055 const rootKey = this.getStructureKeys(structure)[0]
1056
1057 const maps: { [key: string]: { [id: string]: Record<string, any> } } = {}
1058 const isListMap: { [path: string]: boolean } = {}
1059 const referenceMap: { [key: string]: any } = {}
1060 const pathDetails: {
1061 [key: string]: {
1062 property: string
1063 parents: string[]
1064 parentPath: string
1065 }
1066 } = {}
1067
1068 const initializeMaps = (structure: Select, path: string[]) => {
1069 const currentPath = path.join(".")
1070 const entity = this.getEntity(currentPath, false)
1071 if (!entity) {
1072 return
1073 }
1074
1075 maps[currentPath] = {}
1076
1077 if (path.length > 1) {
1078 const property = path[path.length - 1]
1079 const parents = path.slice(0, -1)
1080 const parentPath = parents.join(".")
1081
1082 // In the case of specific selection
1083 // We dont need to check if the property is a list
1084 const isSelectableField = this.allSchemaFields.has(property)
1085 if (isSelectableField) {
1086 pathDetails[currentPath] = { property, parents, parentPath }
1087 isListMap[currentPath] = false
1088 return
1089 }
1090
1091 isListMap[currentPath] = !!this.getEntity(
1092 currentPath,
1093 false
1094 )?.ref?.parents?.find((p) => p.targetProp === property)?.isList
1095
1096 pathDetails[currentPath] = { property, parents, parentPath }
1097 }
1098
1099 const children = this.getStructureKeys(structure)
1100 for (const key of children) {
1101 initializeMaps(structure[key] as Select, [...path, key])
1102 }
1103 }
1104 initializeMaps(structure[rootKey] as Select, [rootKey])
1105
1106 function buildReferenceKey(
1107 path: string[],
1108 id: string,
1109 row: Record<string, any>
1110 ) {
1111 let current = ""
1112 let key = ""
1113 for (const p of path) {
1114 current += `${p}`
1115 key += row[`${current}.id`] + "."
1116 current += "."
1117 }
1118 return key + id
1119 }
1120
1121 const columnMap = {}
1122 const columnNames = Object.keys(resultSet[0] ?? {})
1123 for (const property of columnNames) {
1124 const segments = property.split(".")
1125 const field = segments.pop()
1126 const parent = segments.join(".")
1127
1128 columnMap[parent] ??= []
1129 columnMap[parent].push({
1130 field,
1131 property,
1132 })
1133 }
1134
1135 resultSet.forEach((row) => {
1136 for (const path in maps) {
1137 const id = row[`${path}.id`]
1138
1139 // root level
1140 if (!pathDetails[path]) {
1141 if (!maps[path][id]) {
1142 maps[path][id] = row[path] || undefined
1143
1144 // If there is an id, but no object values, it means that specific fields were selected
1145 // so we recompose the object with all selected fields. (id will always be selected)
1146 if (!maps[path][id] && id) {
1147 maps[path][id] = {}
1148 for (const column of columnMap[path]) {
1149 maps[path][id][column.field] = row[column.property]
1150 }
1151 }
1152 }
1153 continue
1154 }
1155
1156 const { property, parents, parentPath } = pathDetails[path]
1157 const referenceKey = buildReferenceKey(parents, id, row)
1158
1159 if (referenceMap[referenceKey]) {
1160 continue
1161 }
1162
1163 maps[path][id] = row[path] || undefined
1164
1165 // If there is an id, but no object values, it means that specific fields were selected
1166 // so we recompose the object with all selected fields. (id will always be selected)
1167 if (!maps[path][id] && id) {
1168 maps[path][id] = {}
1169 for (const column of columnMap[path]) {
1170 maps[path][id][column.field] = row[column.property]
1171 }
1172 }
1173
1174 const parentObj = maps[parentPath][row[`${parentPath}.id`]]
1175
1176 if (!parentObj) {
1177 continue
1178 }
1179
1180 const isList = isListMap[parentPath + "." + property]
1181 if (isList && !Array.isArray(parentObj[property])) {
1182 parentObj[property] = []
1183 }
1184
1185 if (maps[path][id] !== undefined) {
1186 if (isList) {
1187 parentObj[property].push(maps[path][id])
1188 } else {
1189 parentObj[property] = maps[path][id]
1190 }
1191 }
1192
1193 referenceMap[referenceKey] = true
1194 }
1195 })
1196
1197 return Object.values(maps[rootKey] ?? {})
1198 }
1199 }