Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
20 changes: 1 addition & 19 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion Sources/StructuredQueriesCore/Optional.swift
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,11 @@ extension QueryExpression where QueryValue: _OptionalProtocol {
public func map<T>(
_ transform: (SQLQueryExpression<QueryValue.Wrapped>) -> some QueryExpression<T>
) -> some QueryExpression<T?> {
SQLQueryExpression(transform(SQLQueryExpression(queryFragment)).queryFragment)
SQLQueryExpression(
"""
IIF(\(self), \(transform(SQLQueryExpression(queryFragment))), NULL)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I hoped I could use CASE/WHEN/THEN here to be SQL compatible, but apparently the cases are not lazy. They are evaluated even if their conditions are false. IIF on the other hand is lazy, and so we really can avoid invoking the transform if it is NULL.

"""
)
}

/// Creates a new optional expression from this one by applying an unwrapped version of this
Expand Down
54 changes: 54 additions & 0 deletions Tests/StructuredQueriesTests/MapTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Dependencies
import Foundation
import InlineSnapshotTesting
import SQLite3
import StructuredQueries
import StructuredQueriesSQLite
import StructuredQueriesTestSupport
import Testing
import _StructuredQueriesSQLite

extension SnapshotTests {
@Suite struct MapTests {
@Dependency(\.defaultDatabase) var database

@Test func mapWithDatabaseFunction() throws {
$increment.install(database.handle)
try database.execute("""
CREATE TABLE "optionalIntegers" (
"value" INTEGER
) STRICT
""")
try database.execute("""
INSERT INTO "optionalIntegers" ("value") VALUES (1), (NULL), (3)
""")

assertQuery(
OptionalInteger.select {
$0.value.map { $increment($0) }
}
) {
"""
SELECT IIF("optionalIntegers"."value", "increment"("optionalIntegers"."value"), NULL)
FROM "optionalIntegers"
"""
} results: {
"""
┌─────┐
│ 2 │
│ nil │
│ 4 │
└─────┘
"""
}
}
}
}

@Table struct OptionalInteger {
let value: Int?
}
@DatabaseFunction(isDeterministic: true)
private func increment(_ value: Int) -> Int {
value + 1
}
Loading