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

Enum type on MySQL #669

Closed TKNgu closed 4 years ago

TKNgu commented 4 years ago

I build simple model:

import Vapor
import FluentMySQL

enum Language: String, Codable, ReflectionDecodable {
    case vi
    case en

    public static func reflectDecoded() throws -> (Language, Language) {
        return (.vi, .en)
    }
}

final class BotServer: MySQLModel {
    var id: Int?
    var name: String
    var url: String
    var token: String?
    var language: Language

    init(id: Int? = nil, name: String, url: String, token: String,
        language: Language = Language.vi) {
        self.id = id
        self.name = name
        self.url = url
        self.token = token
        self.language = language
    }
}

extension BotServer: Migration {}

extension BotServer: Content {}

extension BotServer: Parameter {}

log:

[mysql] [2020-03-29 22:39:24 +0000] CREATE TABLE `BotServer` (`id` BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `url` VARCHAR(255) NOT NULL, `token` VARCHAR(255) , `language` JSON NOT NULL) []

On SQL language is type JSON. But when iinsert type is string.

[mysql] [2020-03-29 22:40:59 +0000] INSERT INTO `BotServer` (`url`, `token`, `name`, `language`) VALUES (?, ?, ?, ?) [string("Lala"), string("Gaga"), string("Test"), string("vi")]

How I can fix it ?

tanner0101 commented 4 years ago

Writing a custom migration will fix this. The auto migration (from BotServer: Migration {}) is not able to correctly detect that language is really a String. It sees it as a custom type and wants to store is as JSON.

TKNgu commented 4 years ago

Thank for help. But why when create table and insert it not work same ? Sorry for my English.

tanner0101 commented 4 years ago

I'm not sure how to explain it better beyond my original answer, sorry. You'll need to write the migration manually.