Closed 4np closed 6 years ago
I added PostgreSQLEnumType
to make this a bit easier (see the commit referenced above).
As long as the enum is RawRepresentable
(backed by a string, int, etc) and the raw value is also a PostgreSQL-compatible type (all strings, integers, floats, bool, etc are) then implementation will be concise.
Here's what the models can look like:
enum PetType: Int, PostgreSQLEnumType {
static let keyString: TupleMap = (.cat, .dog)
case cat = 1
case dog = 2
}
struct Pet: PostgreSQLModel, Migration {
var id: Int?
var type: PetType
var name: String
}
Some example usage with expected return:
_ = try Pet(id: nil, type: .cat, name: "Ziz").save(on: conn).wait()
_ = try Pet(id: nil, type: .dog, name: "Spud").save(on: conn).wait()
let cats = try Pet.query(on: conn).filter(\.type == .cat).all().wait()
let dogs = try Pet.query(on: conn).filter(\.type == .dog).all().wait()
XCTAssertEqual(cats.count, 1)
XCTAssertEqual(cats.first?.name, "Ziz")
XCTAssertEqual(dogs.count, 1)
XCTAssertEqual(dogs.first?.name, "Spud")
Still trying to work out a way to make static let keyString: TupleMap
not required, but for now we must have knowledge of two distinct values for each nested type for Fluent to work properly.
Let me know if that looks good. Thanks!
When I extend the User / Pet model to store
PetType
andUserType
integer backed enums, PostgreSQL will fail on theUserType
property onUser
:Extended User / Pet model:
Changing the
enum
types fromInteger
backed toString
backed does not matter:Note that
PetType
is not being used in the above code other than that it's part of the nestedJSONB
forPet