Java Clean Architecture Masterclass

Java Clean Architecture Masterclass28-29 May

Join

sqlx4k

Build Maven Central GitHub License GitHub commit activity GitHub issues Kotlin

A coroutine-first SQL toolkit with compile-time query validations for Kotlin Multiplatform. PostgreSQL, MySQL/MariaDB, and SQLite are supported.


sqlx4k is not an ORM. Instead, it provides a comprehensive toolkit of primitives and utilities to communicate directly with your database. The focus is on giving you control while catching errors early through compile-time query validation—preventing runtime surprises before they happen (see SQL syntax validation (compile-time) and SQL schema validation (compile-time) for more details).

The library is designed to be extensible, with a growing ecosystem of tools and extensions like PGMQ (PostgreSQL Message Queue), SQLDelight integration, and more.

đź“– Documentation

🏠 Homepage (under construction)

đź“° Articles

Short deep‑dive posts covering Kotlin/Native, FFI, and Rust ↔ Kotlin interop used in sqlx4k:

Features

Next Steps (contributions are welcome)

Supported Databases

Async-io

The driver is designed with full support for non-blocking I/O, enabling seamless integration with modern, high-performance applications. By leveraging asynchronous, non-blocking operations, it ensures efficient resource management, reduces latency, and improves scalability.

Connection Pool

Connection Pool Settings

The driver allows you to configure connection pool settings directly from its constructor, giving you fine-grained control over how database connections are managed. These settings are designed to optimize performance and resource utilization for your specific application requirements.

Key Configuration Options:

By adjusting these parameters, you can fine-tune the driver's behavior to match the specific needs of your application, whether you're optimizing for low-latency responses, high-throughput workloads, or efficient resource utilization.

// Additionally, you can set minConnections, acquireTimeout, idleTimeout, etc. 
val options = Driver.Pool.Options.builder()
    .maxConnections(10)
    .build()

/**
 * The following urls are supported:
 *  postgresql://
 *  postgresql://localhost
 *  postgresql://localhost:5433
 *  postgresql://localhost/mydb
 *
 * Additionally, you can use the `postgreSQL` function, if you are working in a multiplatform setup.
 */
val db = PostgreSQL(
    url = "postgresql://localhost:15432/test",
    username = "postgres",
    password = "postgres",
    options = options
)

/**
 *  The connection URL should follow the nex pattern,
 *  as described by [MySQL](https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-jdbc-url-format.html).
 *  The generic format of the connection URL:
 *  mysql://[host][/database][?properties]
 */
val db = MySQL(
    url = "mysql://localhost:13306/test",
    username = "mysql",
    password = "mysql"
)

/**
 * The following urls are supported:
 * `sqlite::memory:`            | Open an in-memory database.
 * `sqlite:data.db`             | Open the file `data.db` in the current directory.
 * `sqlite://data.db`           | Open the file `data.db` in the current directory.
 * `sqlite:///data.db`          | Open the file `data.db` from the root (`/`) directory.
 * `sqlite://data.db?mode=ro`   | Open the file `data.db` for read-only access.
 */
val db = SQLite(
    url = "sqlite://test.db", // If the `test.db` file is not found, a new db will be created.
    options = options
)

/**
 * Encrypted SQLite via SQLCipher (the `sqlx4k-sqlite-cipher` module). Same URL forms as SQLite,
 * but every target — native (FFI) and JVM/Android (JNI) — is backed by the same Rust `sqlx` +
 * SQLCipher core. The `password` is applied as the SQLCipher `PRAGMA key`, and the database file
 * is created encrypted on first use.
 *
 * In a multiplatform setup use the `sqliteCipher(...)` function instead; on Android it additionally
 * takes a `Context` (to resolve a relative database filename into the app's private storage).
 */
val db = SQLiteCipher(
    url = "sqlite://test.db", // If not found, a new (encrypted) db will be created.
    password = "a-strong-passphrase",
    options = options
)

Acquiring and using connections

The driver provides two complementary ways to run queries:

Notes:

Examples (PostgreSQL shown, similar to MySQL/SQLite):

// Manual connection acquisition (remember to release)
val conn: Connection = db.acquire().getOrThrow()
try {
    conn.execute("insert into users(id, name) values (2, 'Bob');").getOrThrow()
    val rs = conn.fetchAll("select * from users;").getOrThrow()
    // ...
} finally {
    conn.close().getOrThrow() // Return to pool
}

Setting Transaction Isolation Level

You can set the transaction isolation level on a connection to control the degree of visibility between concurrent transactions.

val conn: Connection = db.acquire().getOrThrow()
// Set the isolation level before starting operations
conn.setTransactionIsolationLevel(Transaction.IsolationLevel.Serializable).getOrThrow()

Running Queries

All database interactions go through the QueryExecutor interface, which provides a consistent, coroutine-based API for executing SQL statements. This interface is implemented by:

The QueryExecutor interface provides two primary methods for running queries:

execute() - For SQL statements that modify data

Returns the number of affected rows (INSERT, UPDATE, DELETE, DDL statements):

// With raw SQL string
val affected: Long = db.execute("insert into users(id, name) values (1, 'Alice');").getOrThrow()

fetchAll() - For queries that return data

Returns a ResultSet containing all rows (SELECT queries):

// With raw SQL string
val result: ResultSet = db.fetchAll("select * from users;").getOrThrow()

Prepared Statements

// With named parameters:
val st1 = Statement
    .create("select * from sqlx4k where id = :id")
    .bind("id", 65)

db.fetchAll(st1).getOrThrow().map {
    val id: ResultSet.Row.Column = it.get("id")
    Test(id = id.asInt())
}

// With positional parameters:
val st2 = Statement
    .create("select * from sqlx4k where id = ?")
    .bind(0, 65)

db.fetchAll(st2).getOrThrow().map {
    val id: ResultSet.Row.Column = it.get("id")
    Test(id = id.asInt())
}

RowMapper(s)

object Sqlx4kRowMapper : RowMapper<Sqlx4k> {
    override fun map(row: ResultSet.Row, converters: ValueEncoderRegistry): Sqlx4k {
        val id: ResultSet.Row.Column = row.get(0)
        val test: ResultSet.Row.Column = row.get(1)
        // Use built-in mapping methods to map the values to the corresponding type.
        return Sqlx4k(id = id.asInt(), test = test.asString())
    }
}

val res: List<Sqlx4k> = db.fetchAll("select * from sqlx4k limit 100;", Sqlx4kRowMapper).getOrThrow()

Custom Value Converters

For custom types that don't have builtin decoders, you can register custom ValueEncoder implementations. A ValueEncoder provides bidirectional conversion between your custom type and the database representation.

Creating a Custom Encoder:

// Define your custom type
data class Money(val amount: BigDecimal, val currency: String) {
    override fun toString(): String = "$amount $currency"

    companion object {
        fun parse(value: String): Money {
            val parts = value.split(" ")
            return Money(BigDecimal(parts[0]), parts[1])
        }
    }
}

// Create a ValueEncoder for your type
object MoneyEncoder : ValueEncoder<Money> {
    override fun encode(value: Money): Any = value.toString()
    override fun decode(value: ResultSet.Row.Column): Money = Money.parse(value.asString())
}

Registering and Using Custom Encoders:

// Create a registry and register your encoder
val registry = ValueEncoderRegistry()
    .register<Money>(MoneyEncoder)

// Use the registry when mapping rows
val mapper = Sqlx4kAutoRowMapper
val entity = mapper.map(row, registry)

Transactions

val tx1: Transaction = db.begin().getOrThrow()
tx1.execute("delete from sqlx4k;").getOrThrow()
tx1.fetchAll("select * from sqlx4k;").getOrThrow().forEach { println(it) }
tx1.commit().getOrThrow()

You can also execute entire blocks in a transaction scope.

db.transaction {
    execute("delete from sqlx4k;").getOrThrow()
    fetchAll("select * from sqlx4k;").getOrThrow().forEach { println(it) }
    // At the end of the block will auto commit the transaction.
    // If any error occurs, it will automatically trigger the rollback method.
}

TransactionContext (coroutines)

When using coroutines, you can propagate a transaction through the coroutine context using TransactionContext. This allows you to write small, composable suspend functions that either:

val db = PostgreSQL(
    url = "postgresql://localhost:15432/test",
    username = "postgres",
    password = "postgres",
    options = options
)

fun main() = runBlocking {
    TransactionContext.new(db) {
        // `this` is a TransactionContext and also a Transaction (delegation),
        // so you can call query methods directly:
        execute("insert into sqlx4k (id, test) values (66, 'test');").getOrThrow()

        // In deeper code, fetch the same context and keep using the same tx
        doBusinessLogic()
        doMoreBusinessLogic()
        doExtraBusinessLogic()
    }
}

suspend fun doBusinessLogic() {
    // Get the active transaction from the coroutine context
    val tx = TransactionContext.current()
    // Continue operating within the same database transaction
    tx.execute("update sqlx4k set test = 'updated' where id = 66;").getOrThrow()
}

// Or you can use the `withCurrent` method to get the transaction and execute the block in an ongoing transaction.
suspend fun doMoreBusinessLogic(): Unit = TransactionContext.withCurrent {
    // Continue operating within the same database transaction
}

// You can also pass the db instance to `withCurrent`.
// If a transaction is already active, the block runs within it; otherwise, a new transaction is started for the block.
suspend fun doExtraBusinessLogic(): Unit = TransactionContext.withCurrent(db) {
    // Continue operating within the same database transaction
}

Code-Generation, CRUD and @Repository Implementations

For this operation you will need to include the KSP plugin to your project.

plugins {
    alias(libs.plugins.ksp)
}

// Then you need to configure the processor (it will generate the necessary code files).
ksp {
    // Optional: pick the SQL dialect for CRUD generation from @Table classes.
    // Supported dialects:
    // arg("dialect", "mysql")
    // arg("dialect", "postgresql")
    // arg("dialect", "sqlite")

    // Required: where to place the generated sources.
    arg("output-package", "io.github.smyrgeorge.sqlx4k.examples.postgres")

    // Compile-time SQL syntax checking for @Query methods (default = true).
    // Set to "false" to turn it off if you use vendor-specific syntax not understood by the parser.
    // arg("validate-sql-syntax", "false")
}

dependencies {
    // Will generate code for macosArm64. Add more targets if you want.
    add("kspMacosArm64", implementation("io.github.smyrgeorge:sqlx4k-codegen:x.y.z"))
}

Then create your data class that will be mapped to a table:

@Table("sqlx4k")
data class Sqlx4k(
    @Id(insert = true) // Will be included in the insert query.
    val id: Int,
    val test: String
)

@Repository
interface Sqlx4kRepository : CrudRepository<Sqlx4k> {
    // The processor will validate the SQL syntax in the @Query methods.
    // If you want to disable this validation, you can set the "validate-sql-syntax" arg to "false".
    @Query("SELECT * FROM sqlx4k WHERE id = :id")
    suspend fun findOneById(context: QueryExecutor, id: Int): Result<Sqlx4k?>

    @Query("SELECT * FROM sqlx4k")
    suspend fun findAll(context: QueryExecutor): Result<List<Sqlx4k>>

    @Query("SELECT count(*) FROM sqlx4k")
    suspend fun countAll(context: QueryExecutor): Result<Long>

    @Query("SELECT * FROM sqlx4k WHERE id = :id")
    suspend fun existsById(context: QueryExecutor, id: Int): Result<Boolean>
}

[!NOTE] A @Query method's name prefix determines its shape and expected return type: findAll/findAllBy… → Result<List<T>>, findOneBy… → Result<T?>, countAll/countBy… → Result<Long>, existsBy… → Result<Boolean>, deleteAll/deleteBy… and execute… → Result<Long> (affected rows).

[!NOTE] Besides your @Query methods, because your interface extends CrudRepository<T>, the generator also adds the CRUD helper methods automatically: insert, update, delete, and save.

[!NOTE] By default, the code generator automatically uses the auto-generated RowMapper for your entity (e.g., Sqlx4kAutoRowMapper). You can override this behavior by explicitly providing a custom mapper: @Repository(mapper = CustomRowMapper::class).

Then in your code you can use it like:

// Insert a new record.
val record = Sqlx4k(id = 1, test = "test")
val res: Sqlx4k = Sqlx4kRepositoryImpl.insert(db, record).getOrThrow()
// Execute a generated query.
val res: List<Sqlx4k> = Sqlx4kRepositoryImpl.selectAll(db).getOrThrow()

For more details, take a look at the examples.

Customizing columns with @Column

You can use the @Column annotation to override the column name a property is mapped to, and to control how the property participates in the generated INSERT and UPDATE statements. The latter is useful for database-generated or read-only columns that should be excluded from write operations but still retrieved afterwards (via the RETURNING clause).

Property Effect
name = "..." Overrides the column name used in all generated SQL and the generated RowMapper
insert = false Excluded from the INSERT's column list, included in the INSERT's RETURNING clause
update = false Excluded from the UPDATE's SET clause, included in the UPDATE's RETURNING clause

By default — when name is empty, or when the property has no @Column annotation at all — the column name is derived from the property name using snake_case conversion (e.g., createdAt → created_at). Providing an explicit name is useful for legacy or non-conventional schemas:

@Table("legacy_users")
data class LegacyUser(
    @Id
    val id: Long,
    // Maps to the legacy "USER_NAME" column instead of the derived "user_name".
    @Column(name = "USER_NAME")
    val userName: String,
    // A custom name can be combined with the insert/update flags.
    @Column(name = "mail_address", update = false)
    val email: String,
    // No @Column: maps to "is_active" (default snake_case conversion).
    val isActive: Boolean
)

[!NOTE] An explicit name must be a plain (unquoted) SQL identifier ([A-Za-z_][A-Za-z0-9_]*) and is used verbatim in the generated SQL and when reading result columns by name — so it must match the column name as reported by the database. PostgreSQL folds unquoted identifiers to lowercase, so for PostgreSQL use the lowercase form unless the column was created with a quoted (case-sensitive) name.

@Table("articles")
data class Article(
    @Id
    val id: Long,
    val title: String,
    val content: String,
    // Set only on INSERT by a DB default, never modified afterwards.
    @Column(insert = false, update = false)
    val createdAt: LocalDateTime,
    // Auto-updated by a DB trigger on every write.
    @Column(insert = false, update = false)
    val updatedAt: LocalDateTime
)

@Table("comments")
data class Comment(
    @Id
    val id: Long,
    val content: String,
    // Set on INSERT but never updated.
    @Column(update = false)
    val createdAt: LocalDateTime
)
Excluding properties with @Transient

Use the @Transient annotation for derived, computed, or cached properties that have no corresponding database column. Unlike @Column(insert = false, update = false) — which still maps the property from query results — a @Transient property is treated as if it were not a column at all. It is excluded from INSERT/UPDATE statements, from the RETURNING clause, and is not read by the generated RowMapper.

If the annotated property is a primary-constructor parameter, it must declare a default value (the generated RowMapper omits it and relies on the default). Properties declared in the class body (e.g. by lazy or computed get()) need no default.

@Table("accounts")
data class Account(
    @Id
    val id: Long,
    val email: String,
    // Transient constructor parameter — requires a default value.
    @Transient
    val displayName: String = email.substringBefore('@')
) {
    // Transient body property — derived lazily, no default required.
    @Transient
    val domain: String by lazy { email.substringAfter('@') }
}

Auto-Generated RowMapper

When you annotate a class with @Table, the code generator automatically creates a RowMapper implementation for mapping database rows to your entity. The mapper is named {ClassName}AutoRowMapper and is generated in the same file as your CRUD queries.

For example, for a class named Sqlx4k, the generator creates Sqlx4kAutoRowMapper:

object Sqlx4kAutoRowMapper : RowMapper<Sqlx4k> {
    override fun map(row: ResultSet.Row, converters: ValueEncoderRegistry): Sqlx4k {
        val id = row.get("id").asInt()
        val test = row.get("test").asString()
        return Sqlx4k(id = id, test = test)
    }
}

Dialect-Specific Decoders:

When using PostgreSQL, set the dialect in your KSP configuration to enable PostgreSQL-specific decoders:

ksp {
    arg("dialect", "postgresql")  // Enables PostgreSQL array decoders
    arg("output-package", "io.github.smyrgeorge.sqlx4k.examples.postgres")
}

Supported dialects:

Batch Operations

The code generator creates batch INSERT and UPDATE operations for efficiently processing multiple entities in a single database round-trip. These operations use multi-row SQL statements with RETURNING clauses to retrieve database-generated values.

Batch Insert:

// Insert multiple entities at once
val users = listOf(
    User(name = "Alice", email = "alice@example.com"),
    User(name = "Bob", email = "bob@example.com"),
    User(name = "Charlie", email = "charlie@example.com")
)

// Returns all inserted entities with generated IDs
val insertedUsers: Result<List<User>> = userRepository.batchInsert(db, users)

Batch Update:

// Update multiple entities at once
val updatedUsers = users.map { it.copy(status = "active") }

// Returns all updated entities with any DB-modified values
val result: Result<List<User>> = userRepository.batchUpdate(db, updatedUsers)

Database Support:

Operation PostgreSQL SQLite MySQL Generic
batchInsert ✅ ✅ ❌ ✅
batchUpdate ✅ ✅ ❌ ✅

[!NOTE] For unsupported operations, the generated repository methods throw UnsupportedOperationException at runtime. The generated code includes documentation indicating which dialects support each operation.

Property-Level Converters (@Converter)

For custom types, you can use the @Converter annotation to specify a ValueEncoder directly on the property. This provides compile-time type safety, avoids runtime registry lookups, and eliminates object instantiation overhead.

Defining a Custom Encoder:

// Define your custom type
data class Money(val amount: Double, val currency: String) {
    override fun toString(): String = "$amount:$currency"

    companion object {
        fun parse(value: String): Money {
            val parts = value.split(":")
            return Money(parts[0].toDouble(), parts[1])
        }
    }
}

// Create a ValueEncoder as an object (singleton) - NOT a class
object MoneyEncoder : ValueEncoder<Money> {
    override fun encode(value: Money): Any = value.toString()
    override fun decode(value: ResultSet.Row.Column): Money = Money.parse(value.asString())
}

Using @Converter on Properties:

@Table("invoices")
data class Invoice(
    @Id
    val id: Long,
    val description: String,
    @Converter(MoneyEncoder::class)
    val totalAmount: Money
)

[!NOTE] When using @Converter, you don't need to register the encoder in a ValueEncoderRegistry. The encoder object is referenced directly in the generated code, avoiding any instantiation overhead.

Context-Parameters

Optional: Using ContextCrudRepository with context-parameters.

You can opt in to generated repositories that use Kotlin context-parameters instead of passing a QueryExecutor parameter to every method. This switches your repository to ContextCrudRepository and makes all generated CRUD and @Query methods require an ambient QueryExecutor provided via a context-parameter.

To enable this mode:

Repository interface example with context receivers:

@Repository
interface Sqlx4kRepository : ContextCrudRepository<Sqlx4k> {
    @Query("SELECT * FROM sqlx4k WHERE id = :id")
    context(context: QueryExecutor)
    suspend fun findOneById(id: Int): Result<Sqlx4k?>

    @Query("SELECT * FROM sqlx4k")
    context(context: QueryExecutor)
    suspend fun findAll(): Result<List<Sqlx4k>>
}

Usage with a context-parameter (no explicit db parameter on each call):

val record = Sqlx4k(id = 1, test = "test")
with(db) {
    val inserted = Sqlx4kRepositoryImpl.insert(record).getOrThrow()
    val one = Sqlx4kRepositoryImpl.findOneById(1).getOrThrow()
}

If you prefer the explicit-parameter style, keep CrudRepository and do not set enable-context-parameters. In that case, each generated method takes a QueryExecutor (e.g., db or transaction) as the first argument.

Repository Hooks

The repository system provides powerful hooks to implement cross-cutting concerns like metrics, tracing, logging, and monitoring across all database operations. All repository interfaces extend CrudRepositoryHooks<T>, which provides the following hooks:

Entity-Level Hooks:

Query-Level Hook:

The aroundQuery hook is particularly powerful as it wraps all database operations (both @Query methods and CRUD operations), giving you a single interception point for implementing metrics, distributed tracing, query logging, and other observability features.

List of Repository interfaces

SQL syntax validation (compile-time)

Example of a build error you might see if your query is malformed:

> Task :compileKotlin
Invalid SQL in function findAllBy: Encountered "FROMM" at line 1, column 15

Tip: keep it enabled to catch typos early; if you rely heavily on vendor-specific syntax not yet supported by the parser, turn it off either globally or just for a specific method:

ksp { arg("validate-sql-syntax", "false") }
@Repository
interface UserRepository {
    @Query("select * from users where id = :id", checkSyntax = false)
    suspend fun findOneById(context: QueryExecutor, id: Int): Result<User?>
}

SQL schema validation (compile-time)

[!NOTE] Experimental Feature: SQL schema validation is currently in early development and may have limitations.

Enable module-wide schema validation by adding KSP args in your build.gradle.kts:

ksp {
    arg("validate-sql-schema", "true")
    // Path to your migration .sql files (processed in ascending file version order)
    arg("schema-migrations-path", "./db/migrations")
}

You can also disable schema checks for a specific query:

@Repository
interface UserRepository {
    @Query("select * from users where id = :id", checkSchema = false)
    suspend fun findOneById(context: QueryExecutor, id: Int): Result<User?>
}

Query validations and optimizations

Beyond syntax and schema checks, the processor runs a set of extra compile-time checks and codegen rewrites over each @Query (and the entity it maps to). Each is controlled by a global KSP option and enabled by default. They fall into two groups: validations that fail the build when a @Query or entity looks wrong, and optimizations that rewrite the generated SQL for efficiency without changing its result.

Validations

Compile-time safeguards that fail the build when a @Query — or the entity it maps to — is inconsistent (an unknown column or table, the wrong statement kind, an unsupported key shape, …). They never change the generated SQL.

KSP option Default What it does
reject-stacked-statements true Fails the build if a single @Query contains more than one SQL statement (a stacked-query guard).
validate-sql-columns true Fails the build if a @Query references a column that does not exist on the entity — across the SELECT list, WHERE, GROUP BY, HAVING, ORDER BY, and UPDATE ... SET. Applies to single-table queries only (joins/subselects/other tables are skipped).
validate-sql-table true Fails the build if a single-table @Query targets a table other than the entity's own (@Table). Skips subselect FROM clauses.
validate-count-projection true Fails the build if a count* method does not select a single count(...) aggregate.
validate-statement-kind true Fails the build if a @Query's statement kind doesn't match its prefix: find*/count*/exists* must be a SELECT, delete* a DELETE, and execute* a write (INSERT/UPDATE/DELETE).
validate-projection true Fails the build if a find* method bound by the generated row mapper selects only some columns (which would leave the mapper without a column at runtime). Requires SELECT * or every entity column. Skipped when a custom @Repository(mapper = ...) is used.
validate-returning-columns true Fails the build if a RETURNING clause references a column that does not exist on the entity.
reject-grouping-in-scalar true Fails the build if a count*, findOne*, or exists* method's @Query contains a GROUP BY/HAVING clause. A grouped query returns one row per group, but these methods read only the first row — so the result would be wrong.
validate-single-id true Fails the build if the repository entity declares more than one @Id property. Zero (a keyless entity) and one are both allowed; composite primary keys are not supported by the CRUD generator.

Disable any of them module-wide in your build.gradle.kts:

ksp {
    // arg("reject-stacked-statements", "false")
    // arg("validate-sql-columns", "false")
    // arg("validate-sql-table", "false")
    // arg("validate-count-projection", "false")
    // arg("validate-statement-kind", "false")
    // arg("validate-projection", "false")
    // arg("validate-returning-columns", "false")
    // arg("reject-grouping-in-scalar", "false")
    // arg("validate-single-id", "false")
}
Optimizations

Codegen rewrites that make the generated SQL more efficient. They never fail the build; a query that doesn't fit the rewrite is emitted unchanged.

KSP option Default What it does
expand-select-star true Rewrites a bare SELECT * over the entity's table into the entity's explicit columns in the generated statement (e.g. select * from users → select id, name, email from users). Leaves count(*), joins, and explicit column lists untouched.
findone-limit true Appends LIMIT 2 to findOne* queries so the driver fetches at most two rows — it still detects a multi-row result, but transfers far less on wide tables. Skips queries that already declare a LIMIT.
expand-returning-star true Rewrites a bare RETURNING * on a write over the entity's table into the entity's explicit columns (mirrors expand-select-star). Leaves an explicit RETURNING list, or a write against a different table, untouched.
drop-redundant-order-by true Strips a meaningless ORDER BY from exists*/count* queries — their result is a single scalar, so ordering only costs the database a sort. Leaves queries with no ORDER BY untouched.

Disable any of them module-wide in your build.gradle.kts:

ksp {
    // arg("expand-select-star", "false")
    // arg("findone-limit", "false")
    // arg("expand-returning-star", "false")
    // arg("drop-redundant-order-by", "false")
}

[!NOTE] Column/table validation and SELECT * expansion map columns back to properties using the same rules as the CRUD generator (snake_case, or an explicit @Column(name = "...")), so they always stay consistent with the generated SQL.

In-memory repositories (for unit testing)

[!NOTE] Experimental Feature: in-memory repository generation is currently in early development; its behavior and the generated API may change in future releases.

The companion sqlx4k-codegen-test module generates a thread-safe, in-memory implementation of every @Repository interface, so you can unit-test the code that depends on your repositories without a real database. For a repository named Sqlx4kRepository, it generates a class named InMemorySqlx4kRepository.

It is a separate module from sqlx4k-codegen, so in-memory generation is opt-in per dependency — add it only to the KSP configuration that processes your repositories:

ksp {
    // The generated implementations are emitted into this package (same option used by sqlx4k-codegen).
    arg("output-package", "io.github.smyrgeorge.sqlx4k.examples.postgres")
}

dependencies {
    // Real @Repository implementations (production).
    add("kspMacosArm64", implementation("io.github.smyrgeorge:sqlx4k-codegen:x.y.z"))
    // In-memory implementations for unit tests.
    add("kspMacosArm64Test", "io.github.smyrgeorge:sqlx4k-codegen-test:x.y.z")
}

Given the Sqlx4kRepository from the examples above, use the generated implementation directly in your tests:

val repo = InMemorySqlx4kRepository()

// A QueryExecutor is still accepted to match the interface, but it is never touched —
// it works entirely in memory, so any instance (even a no-op fake) will do.
val saved = repo.insert(db, Sqlx4k(id = 1, test = "test")).getOrThrow()
val all = repo.findAll(db).getOrThrow()

What the generated implementation provides:

Anything the generator cannot translate — a WHERE it doesn't understand (e.g. LIKE, IN, subqueries, function calls), or an execute* that isn't a plain UPDATE/DELETE — is emitted as a stub that throws NotImplementedError. The generated class is open, so provide the behavior yourself by subclassing and overriding just those methods. Use the withStore { } helper for thread-safe access to the backing map (the MutableMap is the lambda receiver):

class TestSqlx4kRepository : InMemorySqlx4kRepository() {
    // A method whose WHERE the generator could not translate (e.g. LIKE), so it was left as a stub.
    override suspend fun findAllByTestLike(context: QueryExecutor, pattern: String): Result<List<Sqlx4k>> =
        withStore {
            val prefix = pattern.removeSuffix("%")
            runCatching { values.filter { it.test.startsWith(prefix) } }
        }
}

Database Migrations

Run any pending migrations against the database; and validate previously applied migrations against the current migration source to detect accidental changes in previously applied migrations.

val res = db.migrate(
    path = "./db/migrations",
    table = "_sqlx4k_migrations",
    afterFileMigration = { m, d -> println("Migration of file: $m, took $d") }
).getOrThrow()
println("Migration completed. $res")

This process will create a table with name _sqlx4k_migrations. For more information, take a look at the examples.

Extensions

sqlx4k provides several extensions to enhance functionality:

PostgreSQL Listen/Notify

db.listen("chan0") { notification: Postgres.Notification ->
    println(notification)
}

(1..10).forEach {
    db.notify("chan0", "Hello $it")
    delay(1000)
}

PostgreSQL Message Queue (PGMQ)

A Kotlin Multiplatform client for building reliable, asynchronous message queues using PostgreSQL and the PGMQ extension.

Features:

Installation:

implementation("io.github.smyrgeorge:sqlx4k-postgres-pgmq:x.y.z")

Quick Example:

// Create PGMQ client
val pgmq = PgmqClient(
    pg = PgmqDbAdapterImpl(db),
    options = PgmqClient.Options(autoInstall = true)
)

// Create a queue and send messages
pgmq.create(PgmqClient.Queue(name = "my_queue")).getOrThrow()
pgmq.send("my_queue", """{"order": 123}""").getOrThrow()

// High-level consumer with automatic retry
val consumer = PgmqConsumer(
    pgmq = pgmq,
    options = PgmqConsumer.Options(queue = "my_queue"),
    onMessage = { message -> processMessage(message) }
)

For complete documentation, see sqlx4k-postgres-pgmq/README.md

SQLDelight

SQLDelight integration for type-safe SQL queries with sqlx4k.

Repository: https://github.com/smyrgeorge/sqlx4k-sqldelight

Supported Targets

Usage

implementation("io.github.smyrgeorge:sqlx4k-postgres:x.y.z")
// or for MySQL
implementation("io.github.smyrgeorge:sqlx4k-mysql:x.y.z")
// or for SQLite
implementation("io.github.smyrgeorge:sqlx4k-sqlite:x.y.z")

Windows

If you are building your project on Windows, for target mingwX64, and you encounter the following error:

lld-link: error: -exclude-symbols:___chkstk_ms is not allowed in .drectve

Please look at this issue: #18

Compilation

You will need the Rust toolchain to build this project. Check here: https://rustup.rs/

[!NOTE]
By default, the project will build only for your system architecture-os (e.g. macosArm64, linuxArm64, etc.)

Also, make sure that you have installed all the necessary targets (only if you want to build for all targets):

rustup target add aarch64-apple-ios-sim
rustup target add x86_64-linux-android
rustup target add aarch64-linux-android
rustup target add aarch64-apple-darwin
rustup target add aarch64-unknown-linux-gnu
rustup target add x86_64-unknown-linux-gnu
rustup target add x86_64-pc-windows-gnu

Then, run the build.

# will build only for the current target
./gradlew build

You can also build for specific targets.

./gradlew build -Ptargets=macosArm64

To build for all available targets, run:

./gradlew build -Ptargets=all

Publishing

./gradlew publishAllPublicationsToMavenCentralRepository -Ptargets=all

Run

First, you need to run start-up the postgres instance.

docker compose up -d

And then run the examples.

# For macosArm64
./examples/postgres/build/bin/macosArm64/releaseExecutable/postgres.kexe
./examples/mysql/build/bin/macosArm64/releaseExecutable/mysql.kexe
./examples/sqlite/build/bin/macosArm64/releaseExecutable/sqlite.kexe
# If you run in another platform consider running the correct tartge.

Examples

Here are small, self‑contained snippets for the most common tasks. For full runnable apps, see the modules under:

Checking for memory leaks

macOS (using 'leaks' tool)

Check for memory leaks with the leaks tool. First, sign the binary:

codesign -s - -v -f --entitlements =(echo -n '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd"\>
<plist version="1.0">
    <dict>
        <key>com.apple.security.get-task-allow</key>
        <true/>
    </dict>
</plist>') ./bench/postgres-sqlx4k/build/bin/macosArm64/releaseExecutable/postgres-sqlx4k.kexe

Then run the tool:

leaks -atExit -- ./bench/postgres-sqlx4k/build/bin/macosArm64/releaseExecutable/postgres-sqlx4k.kexe

Acknowledgements

sqlx4k stands on the shoulders of excellent open-source projects:

Huge thanks to the maintainers and contributors of these projects.

License

MIT — see LICENSE.

Join libs.tech

...and unlock some superpowers

GitHub

We won't share your data with anyone else.