vapor / fluent-mysql-driver

🖋🐬 Swift ORM (queries, models, relations, etc) built on MySQL.
MIT License
78 stars 52 forks source link

Unable to INSERT a model with a property of type Data #167

Closed m-barthelemy closed 4 years ago

m-barthelemy commented 4 years ago

I have a Fairly basic model:

class JobModel: Model {    
    public static var schema = "jobs"

    @ID(key: .id)
    var id: UUID?

    @Field(key: "key")
    var key: String

    @Field(key: "data")
    var data: Data

    @Timestamp(key: "created_at", on: .create)
    var createdAt: Date?

    @Timestamp(key: "updated_at", on: .update)
    var updatedAt: Date?

    @Timestamp(key: "deleted_at", on: .delete)
    var deletedAt: Date?

    init(id: UUID, key: String, data: JobData) {
        self.id = id
        self.key = key
        self.data = try! JSONEncoder().encode(data)
    }
}

With the corresponding migration:

public struct JobModelMigrate: Migration {
    public init() {}

    public func prepare(on database: Database) -> EventLoopFuture<Void> {
        let model = FluentQueue.model
        return database.schema(JobModel.schema)
            .id()
            .field(model.$key.key,               .string,   .required)
            .field(model.$data.key,              .data,     .required)
            .field(model.$createdAt.path.first!, .datetime)
            .field(model.$updatedAt.path.first!, .datetime)
            .field(model.$deletedAt.path.first!, .datetime)
            .create()
    }

    public func revert(on database: Database) -> EventLoopFuture<Void> {
        return database.schema(JobModel.schema).delete()
    }
}

Every time I try to save a JobModel, my app crashes with the following message: Fatal error: Not enough bits to represent the passed value

Fluent creates the table with the following structure:


+------------+---------------+------+-----+---------+-------+
| Field      | Type          | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| id         | varbinary(16) | NO   | PRI | NULL    |       |
| key        | varchar(255)  | NO   |     | NULL    |       |
| data       | blob          | NO   |     | NULL    |       |
| created_at | datetime(6)   | YES  |     | NULL    |       |
| updated_at | datetime(6)   | YES  |     | NULL    |       |
| deleted_at | datetime(6)   | YES  |     | NULL    |       |
+------------+---------------+------+-----+---------+-------+

If I change my JobModel.data field to be an optional, re-create the table and try saving a model with a nil value, it works.

I'm using Vapor 4.0.0-rc3.12, Fluent 4.0.0-rc.1, Fluent MySQL driver 4.0.0-rc.1.1, mysqld 8.0.19. Im case it's of any help, this works fine with Postgres.

m-barthelemy commented 4 years ago

This is what Xcode looks like when the crash happens :)

Screen Shot 2020-04-07 at 11 19 10 AM
m-barthelemy commented 4 years ago

Fixed by https://github.com/vapor/mysql-nio/commit/2cc8433a39a0d2025d7252757b56c094c837ca5f