Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Sources/StructuredQueriesCore/Statements/Where.swift
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,8 @@ extension Where: SelectStatement {
/// - Parameter other: Another where clause.
/// - Returns: A where clause that `AND`s the given where clauses together.
public func and(_ other: Self) -> Self {
guard !predicates.isEmpty else { return other }
guard !other.predicates.isEmpty else { return self }
var `where` = self
`where`.predicates = [
"""
Expand All @@ -373,6 +375,8 @@ extension Where: SelectStatement {
/// - Parameter other: Another where clause.
/// - Returns: A where clause that `OR`s the given where clauses together.
public func or(_ other: Self) -> Self {
guard !predicates.isEmpty else { return other }
guard !other.predicates.isEmpty else { return self }
var `where` = self
`where`.predicates = [
"""
Expand All @@ -389,7 +393,9 @@ extension Where: SelectStatement {
/// - Returns: A where clause that `NOT`s this where clause.
public func not() -> Self {
var `where` = self
`where`.predicates = ["NOT (\(`where`.predicates.joined(separator: " AND ")))"]
`where`.predicates = [
"NOT (\(predicates.isEmpty ? "1" : predicates.joined(separator: " AND ")))"
]
return `where`
}

Expand Down
75 changes: 75 additions & 0 deletions Tests/StructuredQueriesTests/WhereTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,36 @@ extension SnapshotTests {
└───┘
"""
}
assertQuery(
Reminder.all.and(Reminder.where(\.isFlagged)).count()
) {
"""
SELECT count(*)
FROM "reminders"
WHERE "reminders"."isFlagged"
"""
} results: {
"""
┌───┐
│ 2 │
└───┘
"""
}
assertQuery(
Reminder.where(\.isFlagged).and(Reminder.all).count()
) {
"""
SELECT count(*)
FROM "reminders"
WHERE "reminders"."isFlagged"
"""
} results: {
"""
┌───┐
│ 2 │
└───┘
"""
}
}

@Test(.snapshots(record: .never)) func emptyResults() {
Expand Down Expand Up @@ -93,6 +123,36 @@ extension SnapshotTests {
└───┘
"""
}
assertQuery(
Reminder.all.or(Reminder.where(\.isFlagged)).count()
) {
"""
SELECT count(*)
FROM "reminders"
WHERE "reminders"."isFlagged"
"""
}results: {
"""
┌───┐
│ 2 │
└───┘
"""
}
assertQuery(
Reminder.where(\.isFlagged).or(Reminder.all).count()
) {
"""
SELECT count(*)
FROM "reminders"
WHERE "reminders"."isFlagged"
"""
}results: {
"""
┌───┐
│ 2 │
└───┘
"""
}
}

@Test func not() {
Expand Down Expand Up @@ -128,6 +188,21 @@ extension SnapshotTests {
└───┘
"""
}
assertQuery(
Reminder.all.not().count()
) {
"""
SELECT count(*)
FROM "reminders"
WHERE NOT (1)
"""
} results: {
"""
┌───┐
│ 0 │
└───┘
"""
}
}

@Test func optionalBoolean() throws {
Expand Down