vapor / fluent-postgres-driver

🐘 PostgreSQL driver for Fluent.
MIT License
149 stars 53 forks source link

PostgreSQLRawEnum does not filter properly #93

Closed lukenewman closed 6 years ago

lukenewman commented 6 years ago

I have a Session model which has an entry and exit timestamp. Sessions are .active when the exit timestamp is nil and .finished otherwise:

final class Session: PostgreSQLModel {
    var entryTimestamp: Date
    var exitTimestamp: Date?
    ...
}

public enum SessionState: UInt8, PostgreSQLRawEnum {
    public static var allCases: [SessionState] = [.active, .finished]

    case active, finished
}

extension Session {
    var state: SessionState {
        return exitTimestamp == nil ? .active : .finished
    }
}

I then want to filter based on state:

func listActive(_ req: Request) throws -> Future<[Session]> {
    return Session.query(on: req).filter(\.state == .active).all()
}

func listInactive(_ req: Request) throws -> Future<[Session]> {
    return Session.query(on: req).filter(\.state == .finished).all()
}

For testing, I have only one Session in the database, and it has a nil exitTimestamp. listActive returns nothing, but listInactive returns said Session, opposite my expectations.

I understand this issue is very anecdotal -- and it very well may be that the error lies in my code -- but it also may lie in the intricacies of Postgre or this package.

This is one of many approaches I've taken to filtering based on an Optional property's existence. Attempts to filter by other means (.filter(\.exitTimestamp == nil), .filter(\.isActive)) were not fruitful.

Please let me know what other information I can provide. Thanks!

lukenewman commented 6 years ago

Closing because you can't query on a computed property. The correct approach here is to filter by == nil. My anecdotal issue was tied to an incorrectly-set-up relationship. Make sure you're getting your children based on the correct ID!