引言:Swift 生态系统中的数据库
Swift 早已超越了简单的移动应用开发范畴。随着 Vapor 和 Perfect 等服务端框架的出现,该语言已成为构建后端的完整工具。然而,在 Swift 中处理数据库有其特殊性。与 Python 或 JavaScript 不同,这里没有内置驱动程序——一切都需要通过第三方包来解决。
在本文中,我们将探讨如何连接到两种流行的数据库管理系统:关系型 PostgreSQL 和文档型 MongoDB。您将了解使用哪些库、如何配置连接以及如何执行基本的 CRUD 操作。示例针对 iOS/macOS,但代码同样适用于服务端环境。
Swift 中的 PostgreSQL:通过 Vapor 和 Fluent 实现经典方案
选择库
在 Swift 中处理 PostgreSQL 的事实标准是 Fluent——来自 Vapor 框架的 ORM。Fluent 支持 PostgreSQL、MySQL、SQLite 和 MongoDB(通过单独的驱动程序)。如果您需要在不使用 Vapor 的情况下工作,请使用 PostgresClientKit——一个底层驱动程序。
配置连接
在 Package.swift 中添加依赖:
.package(url: "https://github.com/vapor/fluent-postgres-driver.git", from: "2.0.0")在 configure.swift 中的基本配置:
import Fluentimport FluentPostgresDriverimport Vapor
public func configure(_ app: Application) throws { app.databases.use(.postgres( hostname: "localhost", port: 5432, username: "swift_user", password: "secret", database: "swift_db" ), as: .psql) // 添加迁移 app.migrations.add(CreateUser())}以 User 模型为例的 CRUD 操作
创建模型和迁移:
final class User: Model, Content { static let schema = "users" @ID(key: .id) var id: UUID? @Field(key: "name") var name: String @Field(key: "email") var email: String init() { } init(id: UUID? = nil, name: String, email: String) { self.id = id self.name = name self.email = email }}
struct CreateUser: Migration { func prepare(on database: Database) -> EventLoopFuture<Void> { database.schema("users") .id() .field("name", .string, .required) .field("email", .string, .required) .create() } func revert(on database: Database) -> EventLoopFuture<Void> { database.schema("users").delete() }}控制器中的查询示例:
// 创建用户let user = User(name: "Алексей", email: "alex@example.com")try await user.save(on: req.db)
// 查询所有用户let users = try await User.query(on: req.db).all()
// 按 email 过滤let filtered = try await User.query(on: req.db) .filter(\\.$email == "alex@example.com") .first()重要提示: Fluent 通过 EventLoopFuture 或 async/await(从 Vapor 4.60+ 开始)使用异步机制。请确保您的环境支持 Swift 5.5+。
Swift 中的 MongoDB:使用 MongoKitten 实现文档灵活性
选择驱动程序
对于 MongoDB,主要的库是 MongoKitten。它支持所有现代版本的 MongoDB,包括 Atlas(云版本)。替代方案是 MongoDB Inc. 的 MongoSwift,但 MongoKitten 在风格上被认为更“Swift 化”。
连接到数据库
在 Package.swift 中添加:
.package(url: "https://github.com/OpenKitten/MongoKitten.git", from: "7.0.0")连接示例(适用于 iOS/macOS):
```