🐘 用于 PostgreSQL 的非阻塞、事件驱动的 Swift 客户端。
使用 SPM 字符串可以轻松地将依赖项包含在您的 Package.swift
文件中。
.package(url: "https://github.com/vapor/postgres-kit.git", from: "2.0.0")
PostgresKit 支持以下平台
PostgresKit 是一个用于 PostgreSQL 客户端的 SQLKit 驱动程序。它支持构建和序列化 Postgres 方言的 SQL 查询。 PostgresKit 使用 PostgresNIO 异步连接并与数据库服务器通信。 AsyncKit 用于提供连接池。
重要提示
强烈建议直接使用 PostgresKit 的用户(例如,没有 Fluent ORM 层)利用 PostgresNIO 的 PostgresClient API 进行连接管理,而不是依赖于传统的 AsyncKit API。
数据库连接选项和凭据使用 PostgresConfiguration
结构体指定。
import PostgresKit
let configuration = PostgresConfiguration(
hostname: "localhost",
username: "vapor_username",
password: "vapor_password",
database: "vapor_database"
)
也支持基于 URL 字符串的配置。
guard let configuration = PostgresConfiguration(url: "postgres://...") else {
...
}
要通过 unix 域套接字连接,请使用 unixDomainSocketPath
代替 hostname
和 port
。
let configuration = PostgresConfiguration(
unixDomainSocketPath: "/path/to/socket",
username: "vapor_username",
password: "vapor_password",
database: "vapor_database"
)
一旦您有了 PostgresConfiguration
,您就可以使用它来创建连接源和连接池。
let eventLoopGroup: EventLoopGroup = ...
defer { try! eventLoopGroup.syncShutdown() }
let pools = EventLoopGroupConnectionPool(
source: PostgresConnectionSource(configuration: configuration),
on: eventLoopGroup
)
defer { pools.shutdown() }
首先使用配置结构体创建一个 PostgresConnectionSource
。 此类型负责根据需要创建与您的数据库服务器的新连接。
接下来,使用连接源创建一个 EventLoopGroupConnectionPool
。 您还需要传递一个 EventLoopGroup
。 有关创建 EventLoopGroup
的更多信息,请访问 SwiftNIO 的 文档。 确保在连接池取消初始化之前关闭连接池。
EventLoopGroupConnectionPool
是每个事件循环的池的集合。 直接使用 EventLoopGroupConnectionPool
时,将根据需要随机选择事件循环。
pools.withConnection { conn
print(conn) // PostgresConnection on randomly chosen event loop
}
要获取特定事件循环的池,请使用 pool(for:)
。 这将返回一个 EventLoopConnectionPool
。
let eventLoop: EventLoop = ...
let pool = pools.pool(for: eventLoop)
pool.withConnection { conn
print(conn) // PostgresConnection on eventLoop
}
EventLoopGroupConnectionPool
和 EventLoopConnectionPool
都可以用于创建 PostgresDatabase
的实例。
let postgres = pool.database(logger: ...) // PostgresDatabase
let rows = try postgres.simpleQuery("SELECT version();").wait()
访问 PostgresNIO 的文档,了解有关使用 PostgresDatabase
的更多信息。
一个 PostgresDatabase
可以用来创建一个 SQLDatabase
的实例。
let sql = postgres.sql() // SQLDatabase
let planets = try sql.select().column("*").from("planets").all().wait()
访问 SQLKit 的文档,了解有关使用 SQLDatabase
的更多信息。