使用 Xcode 项目时
使用 Swift Package Manager 清单时
选择包版本
1.0.0-rc.4.6.1
master
🐘 纯 SwifQL+NIO 到 Postgres 的桥接
通过 SwifQL 及其纯 NIO 驱动程序与 Postgres 交互。
.package(url: "https://github.com/SwifQL/PostgresBridge.git", from:"1.0.0-rc"),
.package(url: "https://github.com/SwifQL/VaporBridges.git", from:"1.0.0-rc"),
.target(name: "App", dependencies: [
.product(name: "Vapor", package: "vapor"),
.product(name: "PostgresBridge", package: "PostgresBridge"),
.product(name: "VaporBridges", package: "VaporBridges")
]),
更多信息请查看 Bridges
仓库。
如果想使用自定义标识符,这些标识符在底层存储任何类型的核心 Swift 数据类型,例如 Int
、String
、UUID
等。如果这些标识符不符合 PostgresDataConvertible
协议,它们将无法从 PostgreSQL 表中解码。
以下是 这篇博客文章 中描述的标识符实现的示例,并添加了 Encodable 协议的遵循。
struct IdentifierType<T, KeyType: Codable>: Codable, PostgresDataConvertible where KeyType: PostgresDataConvertible {
let wrappedValue: KeyType
// PostgresDataConvertible requirement
public static var postgresDataType: PostgresDataType {
KeyType.postgresDataType
}
// PostgresDataConvertible requirement
public init?(postgresData: PostgresData) {
guard let wrappedValue = KeyType.init(postgresData: postgresData) else { return nil }
self.init(wrappedValue)
}
// PostgresDataConvertible requirement
public var postgresData: PostgresData? {
wrappedValue.postgresData
}
init(_ wrappedValue: KeyType) {
self.wrappedValue = wrappedValue
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.wrappedValue = try container.decode(KeyType.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(wrappedValue)
}
}
struct Author: Codable {
typealias Identifier = IdentifierType<Author, UUID>
let id: Identifier
// ...
}
struct Category: Codable {
typealias Identifier = IdentifierType<Category, UUID>
let id: Identifier
// ...
}
struct Book: Codable {
typealias Identifier = IdentifierType<Book, UUID>
let id: Identifier
// ...
let categoryID: Category.Identifier
let authorIds: [Author.Identifier]
}
通过这样的实现,categoryID
和 authorIds
都可以被正确解码以形成 Book
对象。 如果没有这样的添加,只有 categoryID
能够被正确解码。