💽

[Server Side Swift] [Swift Records] PostgreSQLのORMで型安全に扱う

に公開1件

Swift Records

SwiftでPostgreSQLを型安全に扱えるORM「Swift Records」を紹介させていただきます。

Swift Recordsは同じ作者のswift-structured-queries-postgresを元に構築されていて、これ自体はPoint-Freeのswift-structured-queries for SQLiteをforkして、PostgreSQL用に改変されたものです。

大元のSQLの実行はVaporのPostgresNIOが使われています。

https://github.com/coenttb/swift-records

クエリの書き方

UsersテーブルとUserEmailテーブルをJOINして、UserIDとEmailを返すようなクエリを書く場合、以下のように定義、実行が可能です。

@Tableでテーブルの定義、@SelectionでJOINの結果をまとめたものを定義可能です。

@Table("users")
struct User: Codable, Identifiable, Hashable {
  var id: UUID
}

@Table("user_email")
struct UserEmail: Codable, Hashable {
  @Column("user_id") var userID: UUID
  var email: String
}

@Selection
struct UserProfile: Codable {
  var id: UUID
  var email: String?
}

func fetchProfile(userID: UUID) async throws -> UserProfile? {
  try await database.read { db in
    try await User
      .leftJoin(UserEmail.all) { $0.0.id.eq($0.1.userID) }
      .where { user, _ in user.id.eq(userID) }
      .select { UserProfile.Columns(id: $0.id, email: $1.email) }
      .limit(1)
      .fetchOne(db)
    }
}

他ツールの紹介

Coenさんは自身のリポジトリにも多くのライブラリをリリースされているのですが、
Swift Standardsというものも立ち上げており、いろんな規格(RFCなど)をSwiftで実装をしています。
執筆時点で75個のリポジトリがあります、その全てが1ヶ月程度で実装されています。

とんでもない数のライブラリを全て個人でやられていて尊敬です

Discussion