Android
skaidb runs inside an Android app: the engine is a native library in your APK, the database is a directory in your app's private storage, and nothing listens on a socket. The same SQL, the same types and the same on-disk format as the server — a phone holds a local store your app owns, not a member of a cluster.
Use it to keep data on the device: a cache that is there before the network is, state that survives the process, queries the UI can observe.
Contents
- What you get
- Installing
- Opening a database
- Statements and values
- Transactions
- Observing a query
- Encryption
- Closing, crashes and memory
- Schema versions
- Errors
- What is not in the Android library
What you get
| Artifact | Holds |
|---|---|
org.skaidb:skaidb-android-core |
The engine (libskaidb_android.so) and a blocking API: EmbeddedDatabase. Callable from Java and Kotlin; depends only on the Kotlin standard library. |
org.skaidb:skaidb-android-kotlin |
Coroutines on top: SkaidbDatabase — suspending calls and Flow queries. Depends on core and kotlinx-coroutines-core. |
- Android 11 (API 30) and newer.
- ABIs:
arm64-v8a,armeabi-v7a,x86_64,x86. The 64-bit libraries are 16 KB page aligned. - The version is the skaidb release the library was built from; both artifacts and the native library always carry the same number.
- The native library adds 7 to 12 MB per ABI to an APK before compression
(
armeabi-v7a7 MB,arm64-v8a9 MB,x86_64andx8612 MB); ship only the ABIs you need withabiFiltersor app bundles.
Installing
The SDK is in the Maven repository at https://repo.dsys.org/maven:
// settings.gradle.kts
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url = uri("https://repo.dsys.org/maven") }
}
}
// app/build.gradle.kts
dependencies {
implementation("org.skaidb:skaidb-android-kotlin:<version>") // or skaidb-android-core
}
Nothing else is needed: the AAR carries the native libraries and its
R8 / ProGuard rules. A published version never changes and is never
removed, and every artifact has a detached signature (.asc) made with the
repository key (https://repo.dsys.org/pubkey.asc).
Each release also publishes skaidb-android-<version>.tar.gz at
https://repo.dsys.org/dl/skaidb/<version>/ (signed checksums beside it),
for a build that must not reach the network or wants the extras. It unpacks
to skaidb-android-<version>/, holding the same Maven artifacts (maven/ —
point a maven { url = uri("…/maven") } repository at the directory), the
native libraries with their symbols (symbols/) for symbolicating a native
crash, and DEPENDENCIES.txt — every crate linked into the native library
with its license, for your own notices.
Opening a database
A database is a directory. Give it one of its own inside your app's private
storage; one EmbeddedDatabase opens a directory at a time, in one process.
import org.skaidb.embedded.OpenOptions
import org.skaidb.embedded.ktx.SkaidbDatabase
val db = SkaidbDatabase.open(
directory = File(context.noBackupFilesDir, "store"),
options = OpenOptions(
memoryBudgetBytes = 64L * 1024 * 1024,
key = storeKey, // 32 bytes, or null for a plain store
schemaVersion = 1,
),
)
db.execute("CREATE TABLE IF NOT EXISTS messages (PRIMARY KEY (channel, ts))")
Opening never touches the network. A second open of the same directory —
from this process or another — fails with ErrorCode.BUSY.
SkaidbDatabase (coroutines) and EmbeddedDatabase (blocking) are two
faces of the same open: db.blocking gives the blocking one, and
embeddedDatabase.suspending() wraps it. The blocking calls must not run on
the main thread; the suspending ones may be called from anywhere — they run
on Dispatchers.IO unless you pass another dispatcher.
Reads run concurrently with each other; writes run one at a time.
Statements and values
db.update(
"INSERT INTO messages (channel, ts, sender, body) VALUES (?, ?, ?, ?)",
"C1", "1700000000.000100", "U7", "hello",
)
val recent = db.query(
"SELECT ts, sender, body FROM messages WHERE channel = ? ORDER BY ts DESC LIMIT 200",
"C1",
)
for (row in recent) {
row.getString("body")
}
queryanswers aResultSet(aList<Row>withcolumns) and only reads:SELECT,SHOW …,EXPLAIN. Anything else is refused before it runs.updateruns a write and answers the number of rows it changed (for… RETURNING, the rows returned).executeruns any statement and answers aQueryResult— use it for a write whoseRETURNINGrows you want.- Arrays and documents nest at most 128 levels.
- There is no
USE: name a table in another database asdb.table. ?placeholders bind in order. Always bind values rather than building SQL text.- A plain
INSERTof an existing primary key replaces the row. - Read large results in pages (
ORDER BY <pk> LIMIT n AFTER (…), see Deep pagination): a result set larger than a quarter of the memory budget fails withErrorCode.RESOURCE_LIMITinstead of being held.
Values bind and come back as plain Kotlin types — the same mapping as the Java driver:
| SQL | Kotlin |
|---|---|
| NULL | null |
| BOOL | Boolean |
| INT | Long (binds Byte, Short, Int, Long) |
| FLOAT | Double (binds Float, Double; NaN and infinities are refused) |
| DECIMAL | java.math.BigDecimal |
| STRING | String |
| BYTES | ByteArray |
| UUID | java.util.UUID |
| TIMESTAMP | java.time.Instant (millisecond precision) |
| ARRAY | List<Any?> |
| DOCUMENT | Map<String, Any?>, fields sorted by name |
A Row's typed getters (getString, getLong, …) return null for SQL
NULL and never convert: asking a string column for a number is an error. A
value stored as a string — a timestamp such as "1700000000.000100" — comes
back as exactly that string.
Transactions
db.transaction { txn ->
txn.update("DELETE FROM messages WHERE channel = ?", "C1")
for (m in page) txn.update("INSERT INTO messages (channel, ts, body) VALUES (?, ?, ?)", "C1", m.ts, m.body)
txn.update("INSERT INTO checkpoints (scope, token) VALUES (?, ?)", "C1", nextToken)
}
The block's writes are private to it until it returns; then they are
applied together — all of them survive a crash, or none. If the block
throws, or its coroutine is cancelled, nothing is applied. Statements run
through txn see the transaction's own writes; everyone else keeps reading
and writing committed data meanwhile.
BEGIN, COMMIT and ROLLBACK are not statements here (the database is
shared between threads): use transaction { }, or begin() /
commit() / close() on the blocking API.
Conflicts. A transaction takes no locks, and it never erases someone
else's change. If a row the transaction writes was changed by anything else
after the transaction began — a sync job writing while the UI edits, say —
the commit is refused with ErrorCode.CONFLICT and nothing is applied.
Ask for attempts and the block is run again, in a new transaction that
starts from the rows as they are now:
db.transaction(attempts = 3) { txn ->
val unread = txn.query("SELECT unread FROM channels WHERE id = ?", "C1").single().getLong("unread")
txn.update("UPDATE channels SET unread = ? WHERE id = ?", unread + 1, "C1")
}
The block runs once per attempt, so keep what it does outside the database
repeatable. Without attempts the block runs once and the conflict is
thrown to you. Only rows the transaction writes are checked, row by row: a
row it merely read may have changed by the time it commits, and a change to
another row of the same table is never a conflict.
DDL (CREATE TABLE, CREATE INDEX, …) inside a transaction takes effect
at once and is not undone by a rollback. Sequences are not transactional
either: a value handed out is not handed back. The full contract is under
Transactions.
Cancellation. A cancelled read (query, observe) is abandoned. A
write is never left half-told: a call made by a coroutine that is already
cancelled does not start, and once started, a statement that changes data,
and a commit, run to completion and report their outcome even if the
calling coroutine was cancelled meanwhile; the cancellation takes effect
at the caller's next suspension point. If a write call returned, the write
happened; if it threw, it did not. open and close behave the same way:
a cancelled open never leaves a database open that nobody holds, and
close runs even from a cancelled coroutine.
Observing a query
db.observe("SELECT ts, sender, body FROM messages WHERE channel = ? ORDER BY ts DESC LIMIT 200", channel)
.collect { rows -> render(rows) }
The flow emits the current rows when collected, then again whenever a write changed them. It re-runs the query after any committed write to the database and emits only when the result differs; a burst of writes is folded into one re-run. Nothing runs while nobody collects, and the flow completes when the database is closed.
Keep observed queries bounded (LIMIT): each is re-run in full.
On the blocking API the same signal is addChangeListener, called after
every write that may have changed stored data and once when the database
closes. A listener must not throw.
Encryption
Pass a 32-byte key and the store is encrypted at rest: every table and index file, and the write-ahead logs, are sealed — row contents, primary keys and indexed values never reach the disk in the clear.
val db = SkaidbDatabase.open(dir, OpenOptions(key = storeKey))
storeKey.fill(0) // the library has its own copy while the database is open
- A store is created encrypted or plain and stays that way. An encrypted
store needs its key at every open; a missing or wrong key is refused with
ErrorCode.KEYbefore any data is read. A plain store refuses a key. RESTORE FROMtakes only a backup protected the same way — made from a store with the same key, or plain into a plain store. The data it replaces is kept beside the store in<directory>.pre-restoreuntil you delete it; a logout that deletes the store must delete that too.- The key is yours to keep. The usual arrangement is a random key wrapped by an Android Keystore key, unwrapped when the user unlocks the app. The library holds its copy only while the database is open: close the database when the app locks.
- Not sealed:
catalog.json(the names and definitions of tables and indexes — no rows) and the smallEMBEDDEDidentity file (store format, a key check value, your schema version). Do not put secrets in table, column or index names.
Closing, crashes and memory
close() writes out what is in memory, so the next open replays nothing
and takes milliseconds. It waits for calls in flight and rolls back open
transactions.
A process that is killed without closing loses nothing that was
acknowledged — a write that returned is on disk. The next open replays what
had not been flushed: nothing at all when the database had been idle for a
few seconds before the kill (see below), and never more than the memory
budget allows. Always close the database when you are done with it: an
EmbeddedDatabase that is dropped without close() keeps its directory
until the process ends.
memoryBudgetBytes (default 64 MiB) sizes the database for the device: a
quarter is the block cache, a quarter bounds unflushed writes for the whole
database, and a quarter is the most one statement's result may hold. See
A memory budget.
Maintenance runs in the background. Flushing a write buffer to a file, and merging files, happen on two threads the database starts for itself — never inside your statements. The files are built without holding the database's lock, so queries and writes go on while one is being written; the threads sleep until a write wakes them, and an idle database runs nothing.
- A write that takes the unflushed writes past their share of the memory budget returns once the flush has brought them back under it: the writer waits, readers do not.
- A write that leaves a table with eight or more files waiting for a
merge returns once a merge has caught up — the writer waits, readers do
not. That bounds what every query has to look through, also for an app
that only ever opens the database for a moment. A statement that writes
nothing (your
CREATE TABLE IF NOT EXISTSat start-up) never waits. - Five seconds after the last write the database settles what
close()would, and writes out what is unflushed when that is at least a quarter of its ceiling (4 MiB with the default budget). An app that is killed in the background after that reopens with nothing to replay — or with the little that was under that mark, which is quicker to replay than a file for every few rows would be to write and merge. close()waits for a write buffer whose file is being built (one buffer's worth of work at most), then flushes what is left. It never waits for a merge: one in progress is given up and started again at the next open.- An app killed in the middle of a burst of writes reopens by replaying what was unflushed — at most a quarter of the memory budget — however long the burst was.
- A row and its index entries survive a power loss together: the open after one re-applies the index entries of the rows that made it to disk without them.
db.info() reports what the last open found: how long it took, how many
log records it replayed (0 after a clean close), whether the store is
encrypted.
Schema versions
The store carries one number for your application's schema. Ask for the version your build understands when opening, migrate, then record the new version:
val db = SkaidbDatabase.open(dir, OpenOptions(schemaVersion = 3))
when (db.info().schemaVersion) {
0 -> createSchema(db)
1, 2 -> migrate(db)
}
db.setSchemaVersion(3)
A store already at a higher version than the open asks for is refused with
ErrorCode.TOO_NEW: an older build of your app never writes into a newer
build's schema. Nothing is reset or deleted — that decision is yours.
Errors
Every failure is a SkaidbException with an errorCode:
| Code | Meaning |
|---|---|
INVALID_ARGUMENT |
A value that cannot be bound, the wrong number of parameters, a key of the wrong length |
SQL |
The statement does not parse or is not supported |
CONSTRAINT |
A unique, foreign-key, NOT NULL or CHECK violation, or the object already exists |
UNSUPPORTED_CAPABILITY |
The statement needs an engine this open does not offer |
BUSY |
The directory is already open |
KEY |
The key is missing, wrong, or given for a plain store |
CORRUPT |
A data file failed its integrity check |
DISK_FULL |
The device is out of space; nothing acknowledged was lost |
IO |
Any other I/O failure |
RESOURCE_LIMIT |
A statement passed a resource ceiling: page the read |
CLOSED |
The database or transaction is closed |
NOT_FOUND |
No such table, index or database |
TOO_NEW |
The store's format or schema version is newer than this open accepts |
INTERNAL |
A bug in the library; close the database and open it again |
CONFLICT |
A commit refused: a row the transaction writes was changed by someone else after it began. Nothing was applied; run the transaction again |
Nothing is ever wiped automatically — not on a wrong key, a newer schema or a damaged file.
What is not in the Android library
- No network, no replication. The library never connects anywhere. Moving data between a device and a server is your application's job; use a driver for the server side.
- No full-text search.
CREATE SEARCH INDEXis refused (UNSUPPORTED_CAPABILITY). - Time-series tables, vector indexes and geo indexes are off by
default.
OpenOptions(capabilities = …)turns one on. - No server surfaces: no REST or MQTT endpoint, no admin UI, no users or grants — the process that opens the store has all of it.
The engine underneath is the embedded library; its C ABI
(libskaidb_embedded) is what other language bindings link.