( fromPredicate: BasicExpression<boolean> | undefined, subtractPredicate: BasicExpression<boolean> | undefined, )
| 338 | * @returns The simplified difference, or null if cannot be simplified |
| 339 | */ |
| 340 | export function minusWherePredicates( |
| 341 | fromPredicate: BasicExpression<boolean> | undefined, |
| 342 | subtractPredicate: BasicExpression<boolean> | undefined, |
| 343 | ): BasicExpression<boolean> | null { |
| 344 | // If nothing to subtract, return the original |
| 345 | if (subtractPredicate === undefined) { |
| 346 | return ( |
| 347 | fromPredicate ?? |
| 348 | ({ type: `val`, value: true } as BasicExpression<boolean>) |
| 349 | ) |
| 350 | } |
| 351 | |
| 352 | // If from is undefined then we are asking for all data |
| 353 | // so we need to load all data minus what we already loaded |
| 354 | // i.e. we need to load NOT(subtractPredicate) |
| 355 | if (fromPredicate === undefined) { |
| 356 | return { |
| 357 | type: `func`, |
| 358 | name: `not`, |
| 359 | args: [subtractPredicate], |
| 360 | } as BasicExpression<boolean> |
| 361 | } |
| 362 | |
| 363 | // Check if fromPredicate is entirely contained in subtractPredicate |
| 364 | // In that case, fromPredicate AND NOT(subtractPredicate) = empty set |
| 365 | if (isWhereSubset(fromPredicate, subtractPredicate)) { |
| 366 | return { type: `val`, value: false } as BasicExpression<boolean> |
| 367 | } |
| 368 | |
| 369 | // Try to detect and handle common conditions |
| 370 | const commonConditions = findCommonConditions( |
| 371 | fromPredicate, |
| 372 | subtractPredicate, |
| 373 | ) |
| 374 | if (commonConditions.length > 0) { |
| 375 | // Extract predicates without common conditions |
| 376 | const fromWithoutCommon = removeConditions(fromPredicate, commonConditions) |
| 377 | const subtractWithoutCommon = removeConditions( |
| 378 | subtractPredicate, |
| 379 | commonConditions, |
| 380 | ) |
| 381 | |
| 382 | // Recursively compute difference on simplified predicates |
| 383 | const simplifiedDifference = minusWherePredicates( |
| 384 | fromWithoutCommon, |
| 385 | subtractWithoutCommon, |
| 386 | ) |
| 387 | |
| 388 | if (simplifiedDifference !== null) { |
| 389 | // Combine the simplified difference with common conditions |
| 390 | return combineConditions([...commonConditions, simplifiedDifference]) |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | // Check if they are on the same field - if so, we can try to simplify |
| 395 | if (fromPredicate.type === `func` && subtractPredicate.type === `func`) { |
| 396 | const result = minusSameFieldPredicates(fromPredicate, subtractPredicate) |
| 397 | if (result !== null) { |
no test coverage detected