vapor / fluent

Vapor ORM (queries, models, and relations) for NoSQL and SQL databases
https://docs.vapor.codes/4.0/fluent/overview/
MIT License
1.32k stars 172 forks source link

saving and retrieving an array of arrays of a custom type is not possible. #713

Open abbasmousavi opened 3 years ago

abbasmousavi commented 3 years ago

Describe the bug

saving and retrieving an array of arrays of a custom type is not possible.

To Reproduce

I have a person struct like this

public struct Person: Codable {

    public let name: String
    public let id: String?
    public init(name: String, id: String? = nil) {
        self.name = name
        self.id = id
    }
}

and in my model I have a field like this

@Field(key: "teams")
    var teams: [[Person]]?

Expected behavior

I want to be able to save it in my Postgres database. I have used .field("teams", .array(of: .json)) and .field("teams", .json) and

.field("teams", .array(of:.array(of: .json)))

as the field definition in my migration but none of them work.

Environment

0xTim commented 3 years ago

I suspect you'll need .field("teams", .json) if you want it to work, but what errors are you getting?

abbasmousavi commented 3 years ago

If I use .field("teams", .json) it ends up on line 37 ofpostgres-nio/Sources/PostgresNIO/Data/PostgresData+Array.swift with this fatal error:

fatalError("No array type for \(elementType)")

Fatal error: No array type for JSONB[]

0xTim commented 3 years ago

Is that after the save or before save? It's it's after the save, what does the JSON look like in the database?

abbasmousavi commented 3 years ago

It is before save. It does not save to database.

abbasmousavi commented 3 years ago

@0xTim if I wrap it in a class like

class TeamWrapper: Codable {
 let team: [[Person]]
}

It will work without any problem, but the unwrapped double array causes the problem.