Skip to content
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

Add extra set method for DatabaseQuery.Value #468

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions Sources/FluentBenchmark/Tests/SetTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ extension FluentBenchmarker {
try self.testSet_multiple()
try self.testSet_optional()
try self.testSet_enum()
try self.testSet_queryValue()
}

private func testSet_multiple() throws {
Expand Down Expand Up @@ -43,6 +44,16 @@ extension FluentBenchmarker {
.update().wait()
}
}

private func testSet_queryValue() throws {
try runTest(#function, [
TestMigration(),
]) {
try Test.query(on: self.database)
.set(\.$intValue, to: .bind(1))
.update().wait()
}
}
}

private final class Test: Model {
Expand Down
18 changes: 15 additions & 3 deletions Sources/FluentKit/Query/Builder/QueryBuilder+Set.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,33 @@ extension QueryBuilder {
where
Field: QueryableProperty,
Field.Model == Model
{
return self.set(field, to: Field.queryValue(value))
}

@discardableResult
public func set<Field>(
_ field: KeyPath<Model, Field>,
to value: DatabaseQuery.Value
) -> Self
where
Field: QueryableProperty,
Field.Model == Model
{
if self.query.input.isEmpty {
self.query.input = [.dictionary([:])]
}

switch self.query.input[0] {
case .dictionary(var existing):
let path = Model.path(for: field)
assert(path.count == 1, "Set on nested properties is not yet supported.")
existing[path[0]] = Field.queryValue(value)
existing[path[0]] = value
self.query.input[0] = .dictionary(existing)
default:
fatalError()
}

return self
}
}