How vapor/postgres-kit works
Project Type and Purpose
• This is an open-source Swift package (library) named PostgresKit.
• It provides a non-blocking, event-driven client for PostgreSQL, built on top of SwiftNIO for async I/O and AsyncKit for connection pooling.
• It implements the SQLKit driver protocol to translate and serialize SQL queries in the Postgres dialect.
Main Components
a. PostgresKit Library
• Sources/PostgresKit: primary driver code
• Sub-packages:
• Connection and pooling (PostgresConnectionSource.swift, ConnectionPool+Postgres.swift)
• SQL translation (PostgresDataTranslation.swift, PostgresDialect.swift, PostgresRow+SQL.swift)
• Deprecations (legacy API shims)
• Exports.swift (public API surface)
• Docs.docc: embedded documentation
b. External Dependencies
• PostgresNIO: low-level PostgreSQL client over SwiftNIO
• AsyncKit: event-loop-based connection pooling abstractions
• SQLKit: generic SQL driver protocol
c. Runtime Entities
• EventLoopGroup: thread-pool of event loops
• EventLoopGroupConnectionPool: manages pools of connections per event loop
• EventLoopConnectionPool: pool for a single event loop
• PostgresConnection: actual TCP/UNIX-socket connection to Postgres server
• PostgresDatabase / SQLDatabase: high-level query execution interfaces
d. PostgreSQL Server
• External database server (self-hosted or cloud)
Relationships and Data Flow
• Configuration ⇒ PostgresConnectionSource
• ConnectionSource + EventLoopGroup ⇒ EventLoopGroupConnectionPool
• EventLoopGroupConnectionPool ⇒ multiple EventLoopConnectionPool instances
• On query execution:
EventLoop[User Code] → asks Pool.for(eventLoop) → acquires PostgresConnection → executes SQL → returns Row objects → hands back to calling EventLoop
• Interactions with PostgresNIO occur inside PostgresConnection to manage the wire protocol
• SQLKit adapter sits on top of PostgresDatabase to provide the fluent SQL DSL
Architectural Patterns and Design Principles
• Asynchronous, non-blocking I/O via SwiftNIO
• Connection pooling per event loop (sharding for performance)
• Adapter pattern: SQLKit protocol implemented by PostgresDatabase
• Separation of concerns:
• Transport layer (PostgresNIO)
• Connection management (AsyncKit)
• SQL generation (SQLKit + PostgresKit translator)
• Deprecation pathways: maintain legacy APIs under Deprecations module