SqlBuilder

sealed interface SqlBuilder(source)

DSL scope for building SQL.

Add SQL fragments with add or String.unaryPlus; the fragments are joined with line breaks to form the final statement. Thanks to the Kuery Client compiler plugin, any value interpolated into those fragments ($value) is bound as a named parameter instead of being embedded in the SQL text, which prevents SQL injection.

client.sql {
+"SELECT * FROM users"
+"WHERE user_id = $userId"
}

For dynamic SQL that cannot go through the compiler plugin (e.g. helper extension functions that assemble fragments programmatically), use addUnsafe together with bind.

This interface is sealed because the compiler plugin assumes the receiver is the library's internal implementation; a user implementation (e.g. a test fake) would fail with ClassCastException at runtime.

Functions

Link copied to clipboard
abstract fun add(sql: String)

Adds a SQL fragment to the statement being built.

Link copied to clipboard

Adds a SQL fragment to the statement being built, WITHOUT rewriting string interpolation into bind parameters.

Link copied to clipboard
abstract fun bind(parameter: Any?): String

Binds parameter as a named parameter and returns the placeholder string (e.g. :p0) to embed in the SQL fragment.

Link copied to clipboard
abstract operator fun String.unaryPlus()

Adds a SQL fragment to the statement being built. Operator shorthand for add.

Link copied to clipboard
fun SqlBuilder.values(input: List<List<Any?>>)

Add a VALUES (...), (...) clause, binding every element as a parameter.

fun <T> SqlBuilder.values(input: List<T>, transformer: (T) -> List<Any?>)

Add a VALUES (...), (...) clause, converting each element of input into a row using transformer.