Skip to content

Commit 4bcd5a4

Browse files
committed
Support 'exists' on tables.
1 parent 073c8ae commit 4bcd5a4

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Sources/StructuredQueriesCore/Statements/Select.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,13 @@ extension Table {
294294
) -> Select<Int, Self, ()> {
295295
Where().count(filter: filter)
296296
}
297+
298+
/// A select statement for if this table contains any rows.
299+
///
300+
/// - Returns: A select statement that selects `exists()`.
301+
public static func exists() -> some PartialSelectStatement<Bool> {
302+
ExistsSelect<Self, _>(statement: all)
303+
}
297304
}
298305

299306
public struct _SelectClauses: Sendable {
@@ -1525,3 +1532,13 @@ private struct CopyOnWrite<Value> {
15251532
extension CopyOnWrite: Sendable where Value: Sendable {}
15261533

15271534
extension CopyOnWrite.Storage: @unchecked Sendable where Value: Sendable {}
1535+
1536+
private struct ExistsSelect<T: Table, S: Statement>: SelectStatement {
1537+
typealias From = T
1538+
typealias QueryValue = Bool
1539+
let statement: S
1540+
1541+
var query: QueryFragment {
1542+
"SELECT EXISTS\(statement)"
1543+
}
1544+
}

Tests/StructuredQueriesTests/SelectTests.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1214,6 +1214,23 @@ extension SnapshotTests {
12141214
}
12151215
}
12161216
}
1217+
1218+
@Test func exists() {
1219+
assertQuery(Reminder.exists()) {
1220+
"""
1221+
SELECT EXISTS(
1222+
SELECT "reminders"."id", "reminders"."assignedUserID", "reminders"."dueDate", "reminders"."isCompleted", "reminders"."isFlagged", "reminders"."notes", "reminders"."priority", "reminders"."remindersListID", "reminders"."title"
1223+
FROM "reminders"
1224+
)
1225+
"""
1226+
}results: {
1227+
"""
1228+
┌──────┐
1229+
│ true │
1230+
└──────┘
1231+
"""
1232+
}
1233+
}
12171234
}
12181235
}
12191236

0 commit comments

Comments
 (0)