pgkn

Kotlin Experimental CI GitHub license Maven Central Kotlin

pgkn

PostgreSQL Kotlin/Native Driver

Usage

implementation("io.github.moreirasantos:pgkn:1.2.0")
fun main() {
    val driver = PostgresDriver(
        host = "host.docker.internal",
        port = 5432,
        user = "postgres",
        database = "postgres",
        password = "postgres",
    )

    driver.execute("CREATE TABLE my_table(id serial primary key)")
    val list = driver.execute("SELECT * FROM users") {
        mapOf(
            "id" to it.getLong(0),
            "name" to it.getString(1),
            "email" to it.getString(2),
            "bool" to it.getBoolean(3),
            "short" to it.getShort(4),
            "int" to it.getInt(5),
            "float" to it.getFloat(6),
            "double" to it.getDouble(7),
            "bytea" to it.getBytes(8),
            "date" to it.getDate(9),
            "time" to it.getTime(10),
            "timestamp" to it.getLocalDateTime(11),
            "timestamp with time zone" to it.getInstant(12),
        )
    }
}

Features

Connection Pool

PGKN has a connection pool, its size being configurable in PostgresDriver() - 20 by default.
It will refresh connection units if the query fails fatally, but it still needs more fine-grained status checks.

Named Parameters

driver.execute(
    "select name from my_table where name = :one OR email = :other",
    mapOf("one" to "your_name", "other" to "your@email.com")
) { it.getString(0) }

Named Parameters provides an alternative to the traditional syntax using ? to specify parameters. Under the hood, it substitutes the named parameters to a query placeholder.

In JDBC, the placeholder would be ? but with libpq, we will pass $1, $2, etc as stated here: 31.3.1. Main Functions - PQexecParams

This feature implementation tries to follow Spring’s NamedParameterJdbcTemplate as close as possible. NamedParameterJdbcTemplate

Development

Local Build

By default, this project will attempt to build for all targets. If you have a linux machine and only want to build the linuxX64 and linuxArm64 targets, you can do:

./gradlew build -Ptargets=linuxX64,linuxArm64

Prebuilds

This project uses prebuilds to compile for each target, so no libpq installation is needed.
These prebuilds were pulled from brew. Currently, we’re using version 16 of libpq.

FAQ