* Optimizes IN array expressions
( expression: BasicExpression, collection: CollectionLike<T, TKey>, )
| 734 | * Optimizes IN array expressions |
| 735 | */ |
| 736 | function optimizeInArrayExpression< |
| 737 | T extends object, |
| 738 | TKey extends string | number, |
| 739 | >( |
| 740 | expression: BasicExpression, |
| 741 | collection: CollectionLike<T, TKey>, |
| 742 | ): OptimizationResult<TKey> { |
| 743 | if (expression.type !== `func` || expression.args.length !== 2) { |
| 744 | return { canOptimize: false, matchingKeys: new Set(), isExact: false } |
| 745 | } |
| 746 | |
| 747 | const fieldArg = expression.args[0]! |
| 748 | const arrayArg = expression.args[1]! |
| 749 | |
| 750 | if ( |
| 751 | fieldArg.type === `ref` && |
| 752 | arrayArg.type === `val` && |
| 753 | Array.isArray((arrayArg as any).value) |
| 754 | ) { |
| 755 | const fieldPath = (fieldArg as any).path |
| 756 | const values = (arrayArg as any).value |
| 757 | const index = findIndexForField(collection, fieldPath) |
| 758 | |
| 759 | // A nullish or NaN member can never be matched by `IN` (a comparison |
| 760 | // against null/undefined/NaN is never true), but the index would still |
| 761 | // return rows with such an indexed value. When the list contains one of |
| 762 | // those the result is a superset that the caller must re-filter. |
| 763 | const isExact = values.every((value: any) => isExactComparisonValue(value)) |
| 764 | |
| 765 | if (index) { |
| 766 | // Check if the index supports IN operation |
| 767 | if (index.supports(`in`)) { |
| 768 | const matchingKeys = index.lookup(`in`, values) |
| 769 | return { canOptimize: true, matchingKeys, isExact } |
| 770 | } else if (index.supports(`eq`)) { |
| 771 | // Fallback to multiple equality lookups |
| 772 | const matchingKeys = new Set<TKey>() |
| 773 | for (const value of values) { |
| 774 | const keysForValue = index.lookup(`eq`, value) |
| 775 | for (const key of keysForValue) { |
| 776 | matchingKeys.add(key) |
| 777 | } |
| 778 | } |
| 779 | return { canOptimize: true, matchingKeys, isExact } |
| 780 | } |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | return { canOptimize: false, matchingKeys: new Set(), isExact: false } |
| 785 | } |
| 786 | |
| 787 | /** |
| 788 | * Checks if an IN array expression can be optimized |
no test coverage detected