How vapor/fluent-postgres-driver works
Project Type and Purpose
• This is an open-source Swift package implementing a Fluent ORM driver for PostgreSQL.
• It acts as an adapter layer between FluentKit (the ORM) and the PostgreSQL database, leveraging PostgresKit/SQLKit, PostgresNIO, and AsyncKit.
Main Architectural Components
a. Consumer (FluentKit ORM)
• Sends high-level CRUD queries and schema operations.
b. FluentPostgresDriver Library
• Configuration: FluentPostgresConfiguration.swift
• Driver entry point: FluentPostgresDriver.swift
• Database wrapper: FluentPostgresDatabase.swift
• Converter delegate: PostgresConverterDelegate.swift
• Row mapping & error handling: PostgresRow+Database.swift, PostgresError+Database.swift
c. SQLKit Driver Layer (PostgresKit)
• Implements SQLDatabase protocols, builds SQL statements.
d. Low-Level Connection (PostgresNIO + AsyncKit)
• Handles TCP connection, protocol frames, pooling.
e. External Service
• PostgreSQL Server (database instance)
Relationships and Data Flow
• Directional flow:
FluentKit ORM → FluentPostgresDriver → PostgresKit/SQLKit → PostgresNIO → PostgreSQL
• Connection Pooling: AsyncKit provides pool between driver and PostgresNIO.
• Converter Delegate: Translates Fluent data types ↔ SQL literals.
• Error Surface: Database errors bubble up through driver into ORM.
Architectural Patterns and Principles
• Adapter Pattern: Driver implements FluentKit’s DatabaseDriver interface.
• Layered Architecture:
• Presentation (ORM)
• Driver/Adapter
• SQL Builder
• Protocol/IO
• External database
• Asynchronous, non-blocking I/O via Swift NIO.
• Separation of concerns: configuration, SQL building, connection management, error mapping.