# vapor/postgres-nio architecture

> Architecture diagram of the GitHub repository vapor/postgres-nio, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-07-15). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/vapor/postgres-nio
- Repository: https://github.com/vapor/postgres-nio

## Overview

##### Project type and purpose
- This is a Swift library (not an end-user application) that provides a non-blocking, event-driven PostgreSQL client built on SwiftNIO.
- It exposes two primary abstraction layers:
- PostgresNIO: the low-level connection, message encoder/decoder, and state machines
- PostgresClient (in PostgresNIO/Pool): a connection-pooling, async/await front end for user code

##### File structure
- Top-level:
- Sources/ConnectionPoolModule: generic pool state machine, request queuing, connection lifecycle
- Sources/PostgresNIO: the core library split into subfolders (Connection, Data, Message, New, Utilities, Docs)
- Benchmarks, Snippets: example code and performance tests
- Tests: unit/integration suites for both modules
- Config and CI:
- .github/workflows: tests, docs generation
- Package.swift, docker-compose.yml, dev scripts

##### Key architecture elements (to show
a. External Systems
- PostgreSQL Server (over TCP or Unix Domain Socket)
- Logging (SwiftLog) & ServiceLifecycle hooks (optional)
b. SwiftNIO Layer
- EventLoopGroup
- ChannelPipeline with
– PostgresFrontendMessageEncoder
– PostgresChannelHandler
– PostgresBackendMessageDecoder
c. Connection State Machine (in New/Connection State Machine)
- Manages authentication, query, extended query, row streaming, listen, close
d. Data Model & Wire Format
- PostgresDataConvertible, PostgresData, PostgresRow, PostgresRowSequence
- ExpressibleByStringInterpolation → PostgresQuery → parameter binding
e. PostgresConnection API (in Connection/PostgresConnection.swift)
- (), query(), prepare(), decode(), execute()
f. ConnectionPoolModule
- ConnectionPool: acquires/releases PostgresConnection instances
- ConnectionRequest, PoolStateMachine, ConnectionIDGenerator, observability hooks
g. PostgresClient (in PostgresNIO/Pool)
- user-facing pool wrapper with async/await run() and query(…) methods

##### Relationships & data flow
1. User code calls PostgresClient.query(…).
2. PostgresClient delegates to ConnectionPool → acquires a PostgresConnection.
3. PostgresConnection builds a PostgresQuery, encodes via the ChannelPipeline.
4. SwiftNIO writes framed bytes to PostgreSQL server.
5. Server responses arrive as bytes → go through BackendMessageDecoder.
6. Messages are fed into the Connection State Machine → assembled into rows.
7. PostgresRowSequence yields decoded Swift types to user code.
8. On completion or error, connection is returned to the pool (or closed).

##### Architectural patterns & principles
- Non-blocking reactor pattern via SwiftNIO EventLoopGroup
- Finite State Machines for protocol stages
- AsyncSequence for streaming row results with backpressure
- Separation of concerns:
- Wire encoding/decoding
- Protocol state transitions
- Connection pooling
- High-level async API

## Diagram (Mermaid)

```mermaid
flowchart TB
    %% External Systems
    subgraph "External Systems"
        PostgreSQL["PostgreSQL Server"]:::external
        SwiftLog["Logging (SwiftLog) & ServiceLifecycle"]:::external
    end

    %% SwiftNIO Layer
    subgraph "SwiftNIO Layer"
        EventLoopGroup["EventLoopGroup"]:::nio
        subgraph "ChannelPipeline"
            Encoder["PostgresFrontendMessageEncoder"]:::nio
            Handler["PostgresChannelHandler"]:::nio
            Decoder["PostgresBackendMessageDecoder"]:::nio
        end
    end

    %% Protocol & State Machines
    subgraph "Protocol & State Machines"
        StateMachine["Connection State Machines"]:::protocol
        Query["PostgresQuery"]:::protocol
    end

    %% Raw Client API
    subgraph "Raw Client API"
        PostgresConnection["PostgresConnection API"]:::userApi
    end

    %% Connection Pool
    subgraph "Connection Pool"
        ConnectionPool["ConnectionPool"]:::userApi
    end

    %% User-facing API
    subgraph "User-facing API"
        PostgresClient["PostgresClient"]:::userApi
    end

    %% Data Conversion
    subgraph "Data Conversion"
        PDConv["PostgresDataConvertible"]:::data
        PData["PostgresData"]:::data
        PRow["PostgresRow"]:::data
        PSeq["PostgresRowSequence"]:::data
    end

    %% Utilities
    subgraph "Utilities"
        NIOUtils["NIO Utils & Extensions"]:::nio
    end

    %% Examples & Tests
    subgraph "Examples & Tests"
        Snippets["Snippets/PostgresClient.swift"]:::external
        Benchmarks["ConnectionPoolBenchmarks"]:::external
        Tests["Test Suites"]:::external
    end

    %% Connections
    PostgresClient -->|"calls run()/query()"| ConnectionPool
    ConnectionPool -->|"acquire/release"| PostgresConnection
    PostgresConnection -->|"builds & encodes PostgresQuery"| Query
    Query -->|"parameter binding"| Encoder
    Encoder -->|"ByteBuffer"| Handler
    Handler -->|"ByteBuffer"| Decoder
    Decoder -->|"Message"| StateMachine
    StateMachine -->|"PostgresRowSequence"| PSeq
    PSeq -->|"decoded rows"| PostgresClient

    Encoder -->|"TCP"| PostgreSQL
    PostgreSQL -->|"TCP"| Decoder

    PostgresConnection -->|"uses"| EventLoopGroup
    PostgresConnection -->|"uses"| Handler

    PDConv -->|"protocol"| PData
    PData -->|"protocol"| PRow
    PRow -->|"stream"| PSeq

    NIOUtils -->|"extends"| Encoder
    NIOUtils -->|"extends"| Decoder

    Snippets -->|"example"| PostgresClient
    Benchmarks -->|"benchmark"| ConnectionPool
    Tests -->|"validate"| StateMachine
    Tests -->|"validate"| ConnectionPool

    %% Click Events
    click Encoder "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/New/PostgresFrontendMessageEncoder.swift"
    click Decoder "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/New/PostgresBackendMessageDecoder.swift"
    click Handler "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/New/PostgresChannelHandler.swift"
    click StateMachine "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/New/Connection State Machine/ConnectionStateMachine.swift"
    click PDConv "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/Data/PostgresDataConvertible.swift"
    click PData "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/Data/PostgresData.swift"
    click PRow "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/Data/PostgresRow.swift"
    click PSeq "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/New/PostgresRowSequence.swift"
    click Query "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/New/PostgresQuery.swift"
    click PostgresConnection "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/Connection/PostgresConnection.swift"
    click ConnectionPool "https://github.com/vapor/postgres-nio/blob/main/Sources/ConnectionPoolModule/ConnectionPool.swift"
    click PostgresClient "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/Pool/PostgresClient.swift"
    click NIOUtils "https://github.com/vapor/postgres-nio/blob/main/Sources/PostgresNIO/Utilities/NIOUtils.swift"
    click Snippets "https://github.com/vapor/postgres-nio/blob/main/Snippets/PostgresClient.swift"
    click Benchmarks "https://github.com/vapor/postgres-nio/blob/main/Benchmarks/Benchmarks/ConnectionPoolBenchmarks/ConnectionPoolBenchmarks.swift"

    %% Styles
    classDef external fill:#cccccc,stroke:#333,stroke-width:1px;
    classDef nio fill:#ffcc66,stroke:#333,stroke-width:1px;
    classDef protocol fill:#66ccff,stroke:#333,stroke-width:1px;
    classDef userApi fill:#a3e635,stroke:#333,stroke-width:1px;
    classDef data fill:#d8b4fe,stroke:#333,stroke-width:1px;
```
