Skip to content
caffeine-mgnPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Language: English | Русский

klmdb — LMDB for Kotlin Multiplatform

LMDB (Lightning Memory-Mapped Database) for Kotlin Multiplatform, built from source with the kn-clang Gradle plugin. One C implementation, two delivery paths: statically linked into native binaries via cinterop, and a JNI shared library for JVM/Android.

LMDB 1.0.2 — the current on-disk format (0.9 files are not readable; see Upgrading).

Installation

Published to Maven Central, group pw.binom.db.

repositories {
    mavenCentral()
}

dependencies {
    // Core client — environment, transactions, named databases, cursors.
    implementation("pw.binom.db:lmdb:0.1.0")

    // Optional: row storage and indexes over LMDB (no SQL).
    implementation("pw.binom.db:lmdb-kdatabase:0.1.0")

    // Optional: ORM over lmdb-kdatabase, metadata from korm.
    implementation("pw.binom.db:lmdb-korm:0.1.0")
}

Target-specific artifacts (-jvm, -android, -linuxx64, -linuxarm64, -macosx64, -macosarm64, -iosarm64, -iossimulatorarm64, -mingwx64, -androidnative*, -tvos*, -watchos*) resolve from the metadata artifact — do not declare them by hand.

Current version is 0.1.0; the list lives in the registry:

curl -s "https://repo1.maven.org/maven2/pw/binom/db/lmdb/maven-metadata.xml" | tail -12

What gets pulled in, and what does not

pw.binom.db:lmdb depends on nothing — no coroutines, no serialization. A project that only needs the key-value store gets exactly that.

The optional layers add their own dependencies, and the adapters pull the upstream libraries transitively:

Your dependency Brings with it
pw.binom.db:lmdb-kdatabase pw.binom.db:kdatabase (pool and contracts)
pw.binom.db:lmdb-korm pw.binom.db:korm → pw.binom.db:kdatabase

All three live in Maven Central under the same group, so mavenCentral() alone is enough. Release order upstream is kdatabase → korm → klmdb; if you pin a version of lmdb-korm whose korm is not yet in Central, resolution fails.

If you use the adapters, nothing else is required — LmdbTableStore and LmdbOrm are used directly, without a driver underneath:

implementation("pw.binom.db:lmdb-korm:0.1.0")

That single line is enough for the full stack: LMDB core, row storage with indexes, and the ORM.

Native libraries travel inside the artifacts

You do not ship or configure anything. The JVM jar carries /<konan_target>/libklmdb.so|.dylib|.dll and extracts the right one at runtime (SHA-256 verified, ~/.cache/klmdb/<version>/). The Android AAR carries jni/<abi>/libklmdb.so for all four ABIs.

Quick start

import pw.binom.db.klmdb.LmdbEnv

// All parameters are passed directly; the defaults cover the common case.
LmdbEnv.open(path = "/var/lib/myapp/db", mapSize = 4L * 1024 * 1024 * 1024).use { env ->
    val users = env.database("users")

    env.write { txn ->
        txn.put(users, "porfiry".encodeToByteArray(), "investigator".encodeToByteArray())
    }

    val value = env.read { txn -> txn.get(users, "porfiry".encodeToByteArray()) }
    println(value?.decodeToString()) // investigator
}

API shape

Environment

LmdbEnv.open(path, mapSize, maxDbs, maxReaders, pageSize, mode, readOnly, noSubdir, writeMap, noSync, noTls) — creates the directory (with parents) and opens the environment. Every parameter except path has a default, so named arguments are the norm:

// Read-only mount, everything else default.
LmdbEnv.open(path = "/data/db", readOnly = true)

// One file instead of a directory, no fsync.
LmdbEnv.open(path = "/tmp/cache.db", noSubdir = true, noSync = true)

mapSize is a ceiling, not a current size: LMDB reserves address space, so exhausting it gives MDB_MAP_FULL, not "disk full".

read { txn -> } and write { txn -> } wrap a transaction with guaranteed completion: exception in write rolls back.

One writer, many readers

LMDB allows one writing transaction per environment and any number of readers. Readers never block and never see partial writes — they hold a snapshot from the moment their transaction began. The cost of a long read is that freed pages cannot be reused while the snapshot lives, so avoid holding read transactions open longer than the read itself.

Writers are serialised by LMDB itself, not by this library.

Cursors

get only does exact key lookup. Everything else — ordered iteration, ranges, duplicates — goes through LmdbCursor:

env.read { txn ->
    txn.cursor(db).use { cur ->
        var entry = cur.seekRange("bravo".encodeToByteArray())
        while (entry != null && entry.key.decodeToString() <= "delta") {
            println(entry.key.decodeToString())
            entry = cur.next()
        }
    }
}

Keys in LMDB are always sorted (byte order, or numeric with integerKeys = true), which is what makes range scans cheap.

Rows and indexes (lmdb-kdatabase)

LmdbTableStore maps a relational-shaped table onto key-value: primary key is the LMDB key, the serialized row is the value, each index is its own tree with the compound key uint32be(len(value)) || value || primaryKey. The length prefix means values containing 0x00 cannot break a range boundary.

LmdbConnection implements kdatabase.Connection for pool compatibility and fails loudly on prepare(sql) — LMDB does not execute SQL, and pretending otherwise would be worse than refusing.

ORM (lmdb-korm)

LmdbOrm reads entity metadata from korm (@TableName, @Id, @ColumnName, @Index) and stores rows through lmdb-kdatabase:

val orm = LmdbOrm.of(env)
orm.createSchema(User.serializer())
orm.insert(User.serializer(), User(id = "u1", name = "Porfiry", city = "Magnitogorsk"))

val found = orm.findById(User.serializer(), "u1")
val sameCity = orm.findByIndex(User.serializer(), "city_idx", "Magnitogorsk")

Integer keys are encoded big-endian fixed-width, so byte order matches numeric order (9 before 10, not after).

Not supported by design: @AutoGenerated keys (LMDB has no autoincrement — generate the id yourself), nested entities and collections (the table is flat, and a clear error is raised rather than silently dropping fields).

Supported targets

Target Native library Tests run
jvm JNI .so/.dylib/.dll in jar ✅
androidTarget (AAR) jni/<abi>/libklmdb.so ×4 build only
linuxX64 cinterop ✅
linuxArm64 cinterop build only
macosX64 / macosArm64 cinterop ✅ arm64
iosArm64 / iosX64 / iosSimulatorArm64 cinterop build only
tvos* / watchos* (без watchosDeviceArm64) cinterop build only
mingwX64 JNI .dll in jar build only
androidNativeArm32/Arm64/X86/X64 cinterop build only

JS/Wasm are deliberately absent. LMDB is mmap plus a filesystem; a browser has neither. An empty klib that fails on first call would be worse than a missing artifact.

32-bit targets compile with -DMDB_VL32: without it pgno_t is size_t and the map is capped by the 2 GB address space.

Why watchosDeviceArm64 is absent

arm64_32 (Apple Watch) is not declared, same as in ksqlite: kn-clang cannot fetch the watchOS sysroot for arm64_32, and the build dies on sys/types.h not found even though the Xcode SDK ships that header. Declaring a target that cannot be built would break assemble for everyone.

Upgrading from 0.9

LMDB 1.0 changed the on-disk format. 0.9 and 1.0 files are mutually incompatible. To migrate: export with a 0.9 mdb_dump, import with a 1.0 mdb_load. This library bundles 1.0.2 and cannot open 0.9 files.

Building

./gradlew :lmdb:jvmTest :lmdb:linuxX64Test     # run tests
./gradlew :lmdb:assemble                       # all artifacts, all targets
./gradlew :lmdb:buildJvmNative                 # JNI lib for the current host only
./gradlew :lmdb:verifyLmdbVersion :lmdb:verifyLmdbConstants # C constants vs Kotlin

Requirements: JDK 17+, cc for constant verification, Android SDK (local.properties → sdk.dir) for the AAR. Kotlin/Native distribution is downloaded automatically.

Apple artifacts are built on macOS: Apple clang cannot cross-compile to Linux/Windows from Darwin without SDK hacking, and Apple klibs are not reproducible from a Linux host.

Releasing

One GitHub Actions job on macos-latest builds every target and publishes to Maven Central in a single Sonatype deploy. A tag N.N.N triggers it; the tag becomes the published version.

Release order is not optional. The adapters depend on upstream artifacts, so releasing out of order fails on resolution:

# 1. contracts and pool (no dependencies)
cd kdatabase && git tag 0.1.0 && git push --tags

# 2. ORM (depends on kdatabase)
cd korm && git tag 0.1.0 && git push --tags

# 3. this repository (adapters depend on both)
cd LMDB && git tag 0.1.0 && git push --tags

The LMDB workflow probes Maven Central before building and fails with the order spelled out if steps 1–2 have not landed. Maven Central is immutable: a published version cannot be replaced, only superseded. Test with ./gradlew publishToMavenLocal -Pversion=X.Y.Z -PskipSigning=true before tagging.

Required repository secrets: GPG_PRIVATE_KEY, GPG_PASSWORD, GPG_KEY_ID, CENTRAL_USERNAME, CENTRAL_PASSWORD. Signing switches to the system gpg via -PsigningUseGpg=true, so the key must be imported into the runner keyring — the workflow does that in its first steps.

Verification

Constants in LmdbConstants.kt are generated from third_party/lmdb/lmdb.h by third_party/lmdb/gen_constants.py and cross-checked against a compiled C program by verify_constants.py. A shifted error code means the wrong remedy at runtime ("key not found" treated as "map full"), so the numbers come from the header, never from memory.

License

Kotlin sources: Apache License 2.0 — see LICENSE.

Bundled LMDB sources in third_party/lmdb/ (mdb.c, midl.c, midl.h, lmdb.h) are copyright Howard Chu, Symas Corp., licensed under the OpenLDAP Public License 2.8 — see third_party/lmdb/LICENSE and third_party/lmdb/COPYRIGHT. That license is not Apache; redistributing binaries requires reproducing its copyright notice and including the license text, which is why both files ship in this repository and inside the artifacts.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages