(collection: any)
| 55 | } |
| 56 | |
| 57 | export function createIndexUsageTracker(collection: any): { |
| 58 | stats: IndexUsageStats |
| 59 | restore: () => void |
| 60 | } { |
| 61 | const stats: IndexUsageStats = { |
| 62 | rangeQueryCalls: 0, |
| 63 | fullScanCalls: 0, |
| 64 | indexesUsed: [], |
| 65 | queriesExecuted: [], |
| 66 | } |
| 67 | |
| 68 | // Track index method calls by patching all existing indexes |
| 69 | const originalMethods = new Map() |
| 70 | |
| 71 | for (const [indexId, index] of collection.indexes) { |
| 72 | // Track lookup calls (new unified method) |
| 73 | const originalLookup = index.lookup.bind(index) |
| 74 | index.lookup = function (operation: any, value: any) { |
| 75 | // Only track non-range operations to avoid double counting |
| 76 | // Range operations (gt, gte, lt, lte) are handled by rangeQuery tracking |
| 77 | if (![`gt`, `gte`, `lt`, `lte`].includes(operation)) { |
| 78 | stats.rangeQueryCalls++ |
| 79 | stats.indexesUsed.push(String(indexId)) |
| 80 | stats.queriesExecuted.push({ |
| 81 | type: `index`, |
| 82 | operation, |
| 83 | field: index.expression?.path?.join(`.`), |
| 84 | value, |
| 85 | }) |
| 86 | } |
| 87 | return originalLookup(operation, value) |
| 88 | } |
| 89 | |
| 90 | // Track rangeQuery calls (for compound range queries) |
| 91 | if (index.rangeQuery) { |
| 92 | const originalRangeQuery = index.rangeQuery.bind(index) |
| 93 | index.rangeQuery = function (options: any) { |
| 94 | stats.rangeQueryCalls++ |
| 95 | stats.indexesUsed.push(String(indexId)) |
| 96 | |
| 97 | // Determine the actual operations from the options |
| 98 | const operations: Array<string> = [] |
| 99 | if (options.from !== undefined) { |
| 100 | operations.push(options.fromInclusive ? `gte` : `gt`) |
| 101 | } |
| 102 | if (options.to !== undefined) { |
| 103 | operations.push(options.toInclusive ? `lte` : `lt`) |
| 104 | } |
| 105 | |
| 106 | stats.queriesExecuted.push({ |
| 107 | type: `index`, |
| 108 | operation: operations.join(` AND `), |
| 109 | field: index.expression?.path?.join(`.`), |
| 110 | value: options, |
| 111 | }) |
| 112 | return originalRangeQuery(options) |
| 113 | } |
| 114 | } |
no test coverage detected