Skip to content

Add comparison operators for optional columns #52

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from

Conversation

seanmrich
Copy link

Consider a table defined as:

@Table
struct Value {
  var a: Int?
}

If you want to fetch all Values with a < 10, you might try this:

Value
  .where { $0.a < 10 }

By adding the new overloads, this request now compiles.

Consider a table defined as:
```
@table
struct Value {
  var a: Int?
}
```

If you want to fetch all `Value`s with `a` < 10, you might try this:
```
Value
  .where { $0.a < 10 }
```

By adding the new overloads, this request now compiles.
@stephencelis
Copy link
Member

@seanmrich Thanks for taking the time to explore and submit this. We've considered overloads here in the past but are a bit worried about type checking times and general number of overloads required. Here you've added the overloads for T? < T, but there's also T < T? to consider.

Our current workaround is to suggest an explicit #sql string:

Value
  .where { #sql("\($0.a) < 10") }

While slightly unfortunate, it does make it explicit that we are working with a comparison that would not work in the Swift type system, but we know what we're doing.

We'll think on it a bit more, though. Thanks for bringing it up!

@stephencelis
Copy link
Member

@seanmrich We discussed this and for now are worried about the slippery slope nature of the thing, where more and more operators need optional overloads. We're open to revisit in the future, but want to hold off on such functionality for now. Thanks again for taking the time, though! You should be able to maintain these overloads in your own projects should you find them useful, and maybe with more real world use you can start a discussion here in the future with motivating examples.

@seanmrich
Copy link
Author

Thanks for looking into it. I spent some time trying to work out a generic approach that improves the ergonomics here, but nothing practical came out of it.

For now, there's a couple ways to make it more readable.

.where { $0.a < Int?.some(10) } retains some type information that the #sql approach erases.

Another quickie that worked for me was this extension:

extension QueryExpression {
  public var optional: some QueryExpression<Optional<QueryValue>> {
    SQLQueryExpression(self.queryFragment, as: Optional<QueryValue>.self)
  }
}

This yields a more readable .where { $0.a < 10.optional }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants