Skip to content

Commit

Permalink
fix issue generating ids set to nil (#353)
Browse files Browse the repository at this point in the history
  • Loading branch information
tanner0101 authored Jul 15, 2020
1 parent 3eacd5a commit c181c80
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
6 changes: 3 additions & 3 deletions Sources/FluentBenchmark/Tests/IDTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ extension FluentBenchmarker {
let foo1 = Foo()
try foo1.save(on: self.database).wait()
XCTAssertNotNil(foo1.id)
let foo2 = Foo()
let foo2 = Foo(id: nil)
try foo2.save(on: self.database).wait()
XCTAssertNotNil(foo2.id)
XCTAssertNotEqual(foo1.id, foo2.id)
Expand All @@ -49,7 +49,7 @@ extension FluentBenchmarker {
let foo1 = AutoincrementingFoo()
try foo1.save(on: self.database).wait()
XCTAssertEqual(foo1.id, 1)
let foo2 = AutoincrementingFoo()
let foo2 = AutoincrementingFoo(id: nil)
try foo2.save(on: self.database).wait()
XCTAssertEqual(foo2.id, 2)
}
Expand All @@ -63,7 +63,7 @@ extension FluentBenchmarker {
let foo1 = CustomAutoincrementingFoo()
try foo1.save(on: self.database).wait()
XCTAssertEqual(foo1.id, 1)
let foo2 = CustomAutoincrementingFoo()
let foo2 = CustomAutoincrementingFoo(id: nil)
try foo2.save(on: self.database).wait()
XCTAssertEqual(foo2.id, 2)
}
Expand Down
21 changes: 20 additions & 1 deletion Sources/FluentKit/Properties/ID.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,17 @@ public final class IDProperty<Model, Value>
}

func generate() {
guard self.inputValue == nil else {
// Check if current value is nil.
switch self.inputValue {
case .none, .null:
break
case .bind(let value) where value.isNil:
break
default:
return
}

// If nil, generate a value.
switch self.generator {
case .database:
self.inputValue = .default
Expand Down Expand Up @@ -167,3 +175,14 @@ protocol AnyID {
var exists: Bool { get set }
var cachedOutput: DatabaseOutput? { get set }
}


private extension Encodable {
var isNil: Bool {
if let optional = self as? AnyOptionalType {
return optional.wrappedValue == nil
} else {
return false
}
}
}

0 comments on commit c181c80

Please sign in to comment.