groue / GRDB.swift

A toolkit for SQLite databases, with a focus on application development
MIT License
6.73k stars 696 forks source link

Record Enum Columns cannot be queried by filter.fetchAll(db) #1573

Closed csd998aaa closed 2 months ago

csd998aaa commented 2 months ago

What did you do?

Record Enum Columns cannot be queried byfilter.fetchAll(db) throw error!!! How should I do it?

image
struct TicketSchema: Codable {

  var id: Int64?

  var ticketType: TicketType

}

extension TicketSchema: FetchableRecord, MutablePersistableRecord {

  static let databaseTableName: String = "ticket"

  enum Columns: String, ColumnExpression {
    case id, ticketType,  createdTime, updatedTime
  }

  mutating func didInsert(_ inserted: InsertionSuccess) {
    id = inserted.rowID
  }

  private mutating func didUpdate(_ updated: PersistenceSuccess) {
    updatedTime = Date()
  }
}

enum TicketType: String, Codable, CaseIterable {
  case movieTicket
  case trainTicket
}

I tried the following code, but it seems not working either.

extension TicketType: DatabaseValueConvertible {
  var databaseValue: DatabaseValue {
    return rawValue.databaseValue
  }

  static func fromDatabaseValue(_ dbValue: DatabaseValue) -> TicketType? {
    guard let rawValue = String.fromDatabaseValue(dbValue) else {
      return nil
    }
    return TicketType(rawValue: rawValue)
  }
}
migrator.registerMigration("app_v1_20240711") { db in
      try db.create(table: "ticket") { t in
        t.autoIncrementedPrimaryKey("id")
        t.column("ticketType", .text).notNull()
        t.column("createdTime", .datetime)
        t.column("updatedTime", .datetime)
      }
    }

What did you expect to happen?

What happened instead?

Environment

GRDB flavor(s): (GRDB, SQLCipher, Custom SQLite build?) GRDB version: 6.28.0 Installation method: (CocoaPods, SPM, manual?) Xcode version: 15.2 Swift version: 6 Platform(s) running GRDB: (iOS, macOS, watchOS?) iOS macOS version running Xcode: 13.6.3

Demo Project

groue commented 2 months ago

Hello @csd998aaa,

I guess you solved your issue. The line that was missing is:

extension TicketType: DatabaseValueConvertible { }