* Optimizes compound range queries on the same field * Example: WHERE age > 5 AND age < 10
( expression: BasicExpression, collection: CollectionLike<T, TKey>, )
| 276 | * Example: WHERE age > 5 AND age < 10 |
| 277 | */ |
| 278 | function optimizeCompoundRangeQuery< |
| 279 | T extends object, |
| 280 | TKey extends string | number, |
| 281 | >( |
| 282 | expression: BasicExpression, |
| 283 | collection: CollectionLike<T, TKey>, |
| 284 | ): CompoundRangeResult<TKey> { |
| 285 | if (expression.type !== `func` || expression.args.length < 2) { |
| 286 | return { |
| 287 | canOptimize: false, |
| 288 | matchingKeys: new Set(), |
| 289 | isExact: false, |
| 290 | coveredArgIndices: new Set(), |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | // Group range operations by field |
| 295 | const fieldOperations = new Map< |
| 296 | string, |
| 297 | Array<{ |
| 298 | operation: `gt` | `gte` | `lt` | `lte` |
| 299 | value: any |
| 300 | argIndex: number |
| 301 | }> |
| 302 | >() |
| 303 | |
| 304 | // Collect all range operations from AND arguments |
| 305 | for (const [argIndex, arg] of expression.args.entries()) { |
| 306 | if (arg.type === `func` && [`gt`, `gte`, `lt`, `lte`].includes(arg.name)) { |
| 307 | const rangeOp = arg as any |
| 308 | if (rangeOp.args.length === 2) { |
| 309 | const leftArg = rangeOp.args[0]! |
| 310 | const rightArg = rangeOp.args[1]! |
| 311 | |
| 312 | // Check both directions: field op value AND value op field |
| 313 | let fieldArg: BasicExpression | null = null |
| 314 | let valueArg: BasicExpression | null = null |
| 315 | let operation = rangeOp.name as `gt` | `gte` | `lt` | `lte` |
| 316 | |
| 317 | if (leftArg.type === `ref` && rightArg.type === `val`) { |
| 318 | // field op value |
| 319 | fieldArg = leftArg |
| 320 | valueArg = rightArg |
| 321 | } else if (leftArg.type === `val` && rightArg.type === `ref`) { |
| 322 | // value op field - need to flip the operation |
| 323 | fieldArg = rightArg |
| 324 | valueArg = leftArg |
| 325 | |
| 326 | // Flip the operation for reverse comparison |
| 327 | switch (operation) { |
| 328 | case `gt`: |
| 329 | operation = `lt` |
| 330 | break |
| 331 | case `gte`: |
| 332 | operation = `lte` |
| 333 | break |
| 334 | case `lt`: |
| 335 | operation = `gt` |
no test coverage detected