Skip to content

Instantly share code, notes, and snippets.

@seanwoodward
Created July 2, 2025 15:53
Show Gist options
  • Save seanwoodward/0d46ec6ac4634514374299b918c1788e to your computer and use it in GitHub Desktop.
Save seanwoodward/0d46ec6ac4634514374299b918c1788e to your computer and use it in GitHub Desktop.
StructuredQueries TableColumn contains
import StructuredQueries
extension TableColumn where Value == String {
public func contains(collate collation: Collation? = nil, all searchTerms: String...) -> any QueryExpression<Bool> {
contains(collate: collation, all: searchTerms)
}
public func contains(collate collation: Collation? = nil, all searchTerms: some Collection<String>) -> any QueryExpression<Bool> {
func makeExpression(for term: String, collation: Collation?) -> any QueryExpression<Bool> {
collation.map { self.collate($0).contains(term) } ?? self.contains(term)
}
guard let firstExpression = searchTerms.first.map({ makeExpression(for: $0, collation: collation) })
else { return SQLQueryExpression(false) }
return searchTerms
.dropFirst()
.reduce(firstExpression) { expression, term in
expression.and(makeExpression(for: term, collation: collation))
}
}
public func contains(collate collation: Collation? = nil, any searchTerms: String...) -> any QueryExpression<Bool> {
contains(collate: collation, any: searchTerms)
}
public func contains(collate collation: Collation? = nil, any searchTerms: some Collection<String>) -> any QueryExpression<Bool> {
func makeExpression(for term: String, collation: Collation?) -> any QueryExpression<Bool> {
collation.map { self.collate($0).contains(term) } ?? self.contains(term)
}
guard let firstExpression = searchTerms.first.map({ makeExpression(for: $0, collation: collation) })
else { return SQLQueryExpression(false) }
return searchTerms
.dropFirst()
.reduce(firstExpression) { expression, term in
expression.or(makeExpression(for: term, collation: collation))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment