Querying Polypheny from Kotlin

A Kotlin/JVM application connects to Polypheny through the JDBC driver. Use Kotlin’s use function to close connections, statements, and result sets.

Set up the project

Use JDK 17, Gradle 8.10, and a running Polypheny instance with the Prism 2.2 query interface enabled. The examples use port 20590 and the local default credentials pa with an empty password.

In a new project directory, create an empty settings.gradle.kts. Add the project configuration below to build.gradle.kts.

plugins {
    kotlin("jvm") version "2.2.21"
    application
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.polypheny:polypheny-jdbc-driver:3.1")
}

application {
    mainClass.set("PolyphenyExampleKt")
}

Run SQL and read metadata

Save the following as src/main/kotlin/PolyphenyExample.kt.

import java.sql.DriverManager

fun main() {
    val url = "jdbc:polypheny://localhost:20590/"
    DriverManager.getConnection(url, "pa", "").use { connection ->
        connection.prepareStatement("SELECT CAST(? AS VARCHAR(32)) AS product").use { statement ->
            statement.setString(1, "Keyboard")
            statement.executeQuery().use { rows ->
                while (rows.next()) {
                    println(rows.getString("product"))
                }
            }
        }

        connection.metaData.schemas.use { schemas ->
            while (schemas.next()) {
                println(schemas.getString("TABLE_SCHEM"))
            }
        }
    }
}

Run it from the project directory.

gradle run

The example prints Keyboard and the schema names visible on the connection. Bind user-supplied values with setString or another typed setter. JDBC parameter positions start at 1.

Query a document collection

Create a document namespace named docs_jdbc_catalog. In a MongoQL console for that namespace, create the collection and add a document.

db.createCollection("products");
db.products.insertOne({name: "Keyboard", inStock: true});

Replace src/main/kotlin/PolyphenyExample.kt with this program and run gradle run again.

import java.sql.DriverManager
import org.polypheny.jdbc.PolyConnection
import org.polypheny.jdbc.multimodel.DocumentResult

fun main() {
    val url = "jdbc:polypheny://localhost:20590/"
    DriverManager.getConnection(url, "pa", "").use { connection ->
        val statement = connection.unwrap(PolyConnection::class.java).createPolyStatement()
        val result = statement.execute(
            "docs_jdbc_catalog", "mongo", "db.products.find({inStock: true})"
        ) as DocumentResult
        for (document in result) {
            println(document["name"]?.asString())
        }
    }
}

Consume the result while the connection is open. See the JDBC multi-model extensions for the other result types.

© Polypheny GmbH. All Rights Reserved.