Swiftpack.co - Package - khanlou/SwiftgreSQL


This is a PostgreSQL library for Swift, generally designed to be used on the server with no dependencies. Queries are blocking.

It is forked from vapor-community/postgresql.


The PostgreSQL C driver must be installed in order to use this package. Follow the README of the cpostgresql repo to get started.

Installing PostgreSQL

import PackageDescription

let package = Package(
    name: "Project",
    dependencies: [
        .package(url: "https://github.com/khanlou/SwiftgresQL", from: "0.1.0"),
    exclude: [ ... ]


Connecting to the Database

import PostgreSQL

let postgreSQL =  PostgreSQL.Database(
    hostname: "localhost",
    database: "test",
    user: "root",
    password: ""


let version = try postgreSQL.execute("SELECT version()")

Prepared Statement

The second parameter to execute() is an array of PostgresDataType values.

let results = try postgreSQL.execute("SELECT * FROM users WHERE age >= $1", values: [.int(21)])

You can also pass in PostgresDataTypeConvertible values, which will create PostgresDataType values from common stdlib and Foundation types.

let results = try postgreSQL.execute("SELECT * FROM users WHERE age >= $1", [21])

Listen and Notify

try postgreSQL.listen(to: "test_channel") { notification in

// Allow set up time for LISTEN

try postgreSQL.notify(channel: "test_channel", payload: "test_payload")


Each call to execute() creates a new connection to the PostgreSQL database. This ensures thread safety since a single connection cannot be used on more than one thread.

If you would like to re-use a connection between calls to execute, create a reusable connection and pass it as the third parameter to execute().

let connection = try postgreSQL.makeConnection()
let result = try postgreSQL.execute("SELECT * FROM users WHERE age >= $1", [.int(21)]), connection)


Maintained by Soroush Khanlou, with thanks to the Vapor community for the original code..


Stars: 1

Used By

Total: 0