Skip to content

Outdooractive/PostgresConnectionPool

Repository files navigation

PostgresConnectionPool

A connection pool on top of PostgresNIO and PostgresKit.

Requirements

Swift 6.3 or higher (Xcode 16+), macOS 15+ or Linux.

Installation

dependencies: [
    .package(url: "https://github.com/Outdooractive/PostgresConnectionPool.git", from: "1.0.0"),
],
targets: [
    .target(name: "MyTarget", dependencies: [
        .product(name: "PostgresConnectionPool", package: "PostgresConnectionPool"),
    ]),
]

Features

  • Configurable pool size — set the maximum number of open connections
  • Health checksSELECT 1 before returning a connection to a caller (configurable via onReturnConnection)
  • Idle connection culling — automatically close excess idle connections over a 60-second rolling window
  • Query timeout — set statement_timeout per connection
  • Connection retry — configurable retry interval for transient failures
  • Batch cancellation — abort all pending queries for a batch ID
  • Diagnostics — per-connection query tracking, usage counters, runtime info
  • PostgresKit integration — use connection.sql() for the SQLDatabase API
  • Listen/Notify supportaddListener() and listen(on:consume:)

Usage

import PostgresConnectionPool
import PostgresNIO

let postgresConfiguration = PostgresConnection.Configuration(
    host: "localhost",
    port: 5432,
    username: "testuser",
    password: "testpassword",
    database: "test",
    tls: .disable)

let configuration = PoolConfiguration(
    applicationName: "MyApp",
    postgresConfiguration: postgresConfiguration,
    connectTimeout: 10.0,
    queryTimeout: 60.0,
    poolSize: 5,
    maxIdleConnections: 1)

let pool = PostgresConnectionPool(configuration: configuration)

// Run a query
try await pool.connection { connection in
    try await connection.query("SELECT 1", logger: logger)
}

// Use PostgresKit's SQLDatabase API
let users = try await pool.connection { connection in
    try await connection.sql().raw("SELECT * FROM users").all(decoding: User.self)
}

// Inspect pool state
let info = await pool.poolInfo()
print(info)

// Shutdown when done
await pool.shutdown()

See also

License

MIT

Author

Thomas Rasch, Outdooractive

About

A simple connection pool on top of PostgresNIO written in Swift.

Topics

Resources

License

Stars

3 stars

Watchers

5 watching

Forks

Contributors

Languages