Skip to content
Source
Sign inSign up
TanStack/db

Should AND and OR operators support 0 or more arguments (instead of 2 or more) #506

Send to my agent
Openkevin-dp(GitHub profile, opens in a new tab) opened this issue 5 comments

It makes sense to turn the and and or operators into vararg functions. That would simplify their usage, as shown by this code snippet from this issue:

let conditions = [];
for (const key of filters) {
  conditions.push(eq(product.id, key));
}
return or(...conditions);

This is currently not possible because or expects exactly two arguments. This should be the behavior of or:

  • if 0 arguments provided: evaluates to true
  • if 1 predicate provided: returns that predicate
  • if 2 predicates provided: ors them together
  • if 3 or more predicates provided: nested ors
  1. Or already have this behavior that only a typescript error

  2. and/or already partially have this behavior. This is a snippet from the query builder implementation:

    export function and(
      left: ExpressionLike,
      right: ExpressionLike
    ): BasicExpression<boolean>
    export function and(
      left: ExpressionLike,
      right: ExpressionLike,
      ...rest: Array<ExpressionLike>
    ): BasicExpression<boolean>
    export function and(
      left: ExpressionLike,
      right: ExpressionLike,
      ...rest: Array<ExpressionLike>
    ): BasicExpression<boolean> {
      const allArgs = [left, right, ...rest]
      return new Func(
        `and`,
        allArgs.map((arg) => toExpression(arg))
      )
    }

    They require at least 2 arguments which does make sense. We could extend it to support 0 and 1 arguments as i was suggesting but perhaps that's overkill (cc @samwillis).

  3. My query works with 0 or 1 arguments there's only typescript complaining

  4. My query works with 0 or 1 arguments there's only typescript complaining

    Yes, because at runtime you are spreading an array that contains 3 elements so it will work. But Typescript doesn't know that your array always contains 3 elements. So Typescript complains because it thinks it may be empty or contain only a single element. If you want to further discuss your particular case let's do it on your issue instead of this one. This issue is proposing a modification of the and/or functions to support any number of arguments (instead of 2 or more).

  5. Implementation note: supporting 0 arguments means we should just return true but ts/db currently doesn't support .where(_q => true) so we will have to add support for that too.

Sign in to join this conversation.