在 MariaDB 中保存一个 UUID 以便与 Vapor 一起使用

saving an UUID in MariaDB for use with Vapor

我想在 Vapor 中使用 FluentMySQL 来保存数据,但我无法正确读取 UUID。

如果我使用 MariaDB 提供的 UUID() 函数,一切都很好,但是如果我使用 FluentMySQL,UUID 就会乱码: (第一条记录:UUID()的用法,第二条记录:Vapor)

MariaDB [someDB]> select * from Poll;
+--------------------------------------+-------+---------+---------+--------+--------+
| id                                   | title | option1 | option2 | votes1 | votes2 |
+--------------------------------------+-------+---------+---------+--------+--------+
| 88a18a58-2fcd-11ea-9f62-e283e8014c79 | test  | bla     | bla     |      0 |      0 |
| 7??/.?E??*_P?v                     | bla   | option1 | option2 |      1 |      2 |
+--------------------------------------+-------+---------+---------+--------+--------+
2 rows in set (0.00 sec)

这是我的模型:

import Foundation
import FluentMySQL
import Vapor

struct Poll: Content, MySQLUUIDModel, Migration {
    typealias ID = UUID
    static let entity: String = "Poll"

    var id: UUID?
    var title: String
    var option1: String
    var option2: String
    var votes1: Int
    var votes2: Int
}

这是我的 table:

MariaDB [someDB]> describe Poll;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| id      | varchar(191) | YES  |     | NULL    |       |
| title   | varchar(191) | YES  |     | NULL    |       |
| option1 | varchar(191) | YES  |     | NULL    |       |
| option2 | varchar(191) | YES  |     | NULL    |       |
| votes1  | int(10)      | YES  |     | NULL    |       |
| votes2  | int(10)      | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

但是如果使用Vapor 来获取数据,似乎一切都很好。我做错了什么?

通过 curl 输出:

curl http://locurl http://localhost:8080/polls/list
[{"option1":"bla","id":"38386131-3861-3538-2D32-6663642D3131","title":"test","option2":"bla","votes1":0,"votes2":0},{"option1":"option1","id":"373F3F2F-2E3F-453F-3F0E-2A5F503F7607","title":"bla","option2":"option2","votes1":1,"votes2":2}]

感谢您的提前帮助。

如果您使用 Vapor 自己创建一个 UUID 字段,它会创建一个数据类型为 varbinary(16) 而不是 varchar(191) 的字段。这与 MariaDB/MySQL.

中 UUID 字段的默认格式一致

我假设这是一个遗留应用程序,其数据是在 Vapor 外部创建的?看起来您正在存储 UUID 值的字符串表示形式而不是底层二进制值。如果您假设这些值都是可打印的,那么在 varchar 字段中存储二进制值只会导致问题(正如您所发现的)。但是,在同一列中混合使用字符串和二进制格式值可能会导致问题。