Coming from supabase-kt¶
A call written against supabase.from(table) compiles against supabase.offline.from(table) with
only the receiver changed and the accessor imported. Writes return a MutationOutcome instead of
the server's result, and a few call shapes need an edit, listed below.
The swap¶
val open =
supabase.offline.from("todos").select { filter { eq("done", false) } }.decodeList<Todo>()
supabase.offline.from("todos").insert(todo)
supabase.offline.from("todos").update({ set("done", true) }) { filter { eq("id", todo.id) } }
supabase.offline.from("todos").delete { filter { eq("id", todo.id) } }
Import io.github.nesfeder.supabase.offline.offline. Storage works the same way:
supabase.storage.from(bucket) becomes supabase.offline.storage.from(bucket).
What stays the same¶
- The verbs and their overloads.
select,selectAsFlow,insert,upsert,updateanddelete, with JSON bodies, typed values and lists, and the update DSL (set,setTo,setToNull). Typed values are encoded by your PostgREST plugin's serializer, as supabase-kt encodes them. - The request DSL. Filters,
order,range,limit,select()on a write,onConflict,ignoreDuplicatesanddefaultToNull, andcount. - The schema.
from(schema, table)and the request'sschemawork as in supabase-kt. - Storage. Every
BucketApioperation is there under its name; downloads are cached. - The errors. When the server refuses a request, or a request cannot be sent and the library
does not answer it from the cache or the queue, you get supabase-kt's own exception
(
PostgrestRestException,RestException,HttpRequestException) unchanged. A write sent at once that the server refuses throws, as it does in supabase-kt. The library adds three of its own:MutationNotQueueableException, for a write the queue cannot hold that cannot be sent (itscauseis supabase-kt's connectivity failure);NetworkDisabledException, while network access is off; andIllegalArgumentException, for an empty pattern list, or aninelement or group value holding"or\and none of,.:(), which supabase-kt would send escaped but unquoted (Filters the library refuses). Test for being offline withisNetworkOrConnectivityFailure(), not by catchingHttpRequestException.
The offline choices are named parameters with defaults, placed before the trailing lambda:
readStrategy on reads, mutationStrategy on writes. You add them only where you want something
other than the default.
What a write returns¶
A write returns MutationOutcome: Applied(result) when the server applied it,
Queued(pendingMutation) when it waits in the mutation queue, with no answer from the server yet.
Ignore it (a screen built on a live read shows the write either way, at once), take the result if
there is one with resultOrNull(), or match both cases with an exhaustive when.
Call shapes that need an edit¶
supabase-kt's verbs are inline; these are not, because the library keeps the request lambda and
runs it again: to learn the read's shape, to queue a write and to replay it. That, and the return
type, make these call shapes differ:
| Call | What to change |
|---|---|
A write whose result is read, as in insert(row) { select() }.decodeSingle<Row>() |
Read it through resultOrNull(), and decide what to show while the write is queued |
A suspending call, or an early return, inside a request lambda |
Make the call, or return, before the verb; use its result inside the lambda |
A request lambda inside the parentheses, as in insert(row, { select() }) |
The second parameter is mutationStrategy (the first, for delete): name the lambda request = { … }, or move it after the parentheses |
Realtime's selectAsFlow(…) on a table |
The builder's own selectAsFlow is the offline one, and it follows the server once the table is named in realtime { }; keep broadcast and presence calls on supabase-kt's channels |
The typed rpc(function, parameters) |
Import io.github.nesfeder.supabase.offline.rpc in place of io.github.jan.supabase.postgrest.rpc |
Bucket management (createBucket, listBuckets, emptyBucket and the rest) |
Keep it on supabase.storage |
A write whose result is read:
A suspending call inside a request lambda:
// supabase-kt: the verb is inline, so the lambda may suspend
supabase.from("todos").delete { filter { eq("id", currentTodoId()) } }
// supabase-offline-kt: make the call first, then use its result in the lambda
val id = currentTodoId()
supabase.offline.from("todos").delete { filter { eq("id", id) } }
A request lambda inside the parentheses:
// supabase-kt: the second parameter is the request
supabase.from("todos").insert(todo, { select() })
// supabase-offline-kt: the second parameter is mutationStrategy, so name the lambda
supabase.offline.from("todos").insert(todo, request = { select() })
// or move it after the parentheses
supabase.offline.from("todos").insert(todo) { select() }
The typed rpc, with the library's rpc imported:
supabase.postgrest.rpc("archive_done", ArchiveDone(before = "2026-10-01"))
supabase.offline.rpc("archive_done", ArchiveDone(before = "2026-10-01"))
The request lambda must build the same request every time. A read runs it once to learn its shape and once for each request it sends; a write that may be queued runs it up to three times. Keep side effects out of it, and read no clock or counter inside it.
Filters the library refuses¶
Two filters reach the server as something other than what the call says, so the library refuses
them with an IllegalArgumentException, before anything is sent or queued, for reads, updates and
deletes:
- An
inelement, or a comparison value inside anor { }orand { }group, holding"or\and none of,.:(). supabase-kt escapes the quote or backslash but leaves the value unquoted, so the server reads the escapes as part of the value and matches nothing. Filter on such a value with a single top-level filter, which is sent as written. - An empty pattern list given to
likeAll,likeAny,ilikeAllorilikeAny. supabase-kt sends it as no pattern at all, andlikeAllover it matches every row.
From the samples: OfflineTaskRepository.kt
/**
* Try it: an `in` list whose element holds a double quote. supabase-kt escapes the quote but
* leaves the element unquoted, so the server would read the backslash as part of the title and
* match nothing; the library refuses the read before anything is sent, online and offline
* alike.
*/
override suspend fun readWithQuotedValueInList() {
read {
offline.from(Tables.TASKS).select {
filter {
// refused: filter on such a title with a single `eq` outside any list
isIn(TITLE, listOf("Say \"hi\"", "Buy milk"))
}
}
}
}
Two top-level filters on one column, such as filter { gte("age", 1); lte("age", 10) }, are sent
whole: the server joins them as AND, and the library caches, queues and replays them like any other
filters. One case the library cannot see: a second top-level or { } group replaces the first, so
only the last is sent. Combine such groups into one.
What is never cached or queued¶
The library caches PostgREST lists and Storage downloads, and queues PostgREST writes; everything
else goes to the server as supabase-kt sends it, and offline fails as there. That is rpc (a
function may change data, so it is neither cached nor queued), Auth and Functions, Realtime's
broadcast and presence (the tables realtime { } names are kept current by the plugin, and another
channel's records go into the cache with applyServerRecord),
Storage writes, and reads of another shape (a count, head, csv(), geojson(),
stripNulls(), explain(); single() is cached as its list, one row long). The samples' two
database functions say so offline: Mark all done takes no parameters, the Sync tab's Server
section takes them typed and as JSON, and a function's changes reach the device's lists as another
device's do, through Realtime or the next read:
From the samples: OfflineTaskRepository.kt · TaskRepository+Server.swift
/**
* Mark all done: one database function, on the server. Its changes reach the device's lists as
* any other device's do: through Live updates, or the next refresh.
*/
override suspend fun markAllDone(): Int = read {
offline.rpc("complete_all_tasks").decodeAs<Int>() // how many it changed
}
/** The Server section: a count, and a database function called with its parameters twice. */
override suspend fun serverCounts(): ServerCounts = read {
val since = recentWindow(clock.now()).from
ServerCounts(
// Typed parameters, encoded by the client's serializer; null counts every task.
done =
offline
.rpc("tasks_done_count", DoneCountParameters(createdSince = null))
.decodeAs(),
total = countTasks(),
// The same function with parameters as JSON.
doneThisWeek =
offline
.rpc(
"tasks_done_count",
buildJsonObject { put("created_since", since.toString()) },
)
.decodeAs(),
)
}
/// Marks every task of the user done, in one call to the database function
/// `complete_all_tasks()`. The device's lists learn of it when they are read again, or from
/// Realtime when Live updates is on.
func markAllDone() async throws {
try await client.rpc("complete_all_tasks").execute()
}
/// How many of the user's tasks the server holds as done, in all and among those created
/// since `since`, from the database function `tasks_done_count`, each decoded as the number it
/// returns: its parameters once typed, once as JSON values.
func serverDoneCounts(since: Date) async throws -> (all: Int, since: Int) {
// A typed value, encoded as JSON; a nil date counts every task.
let all = try await client.rpc("tasks_done_count", params: DoneCountParameters(createdSince: nil))
.execute(Int.self)
.value
// The same function, its parameter written as a JSON value.
let recent = try await client.rpc("tasks_done_count", params: ["created_since": .string(since.formatted(.iso8601))])
.execute(Int.self)
.value
return (all, recent)
}
The full table is Supported features.
Behavior to expect¶
select falls back by default: NetworkFirst reads as supabase-kt does online and serves the
cached rows offline instead of throwing. A write made while an earlier one of the same user waits is
queued behind it, online too, returns Queued, and is sent a moment later. A queued write the
server refuses on replay is not thrown but goes to the rejected list for your app to show (Failures
and the rejected list). The client holds a database: one client per
process, and clearLocalData() on sign-out.
supabase-kt sends a write when you call it, and the last write to reach the server wins. Here a
write made offline reaches the server later, so name a version column for the tables where that
matters (Conflicts and merging): a queued update or delete of one
cached row then replays with one more filter, updated_at=eq.<the version the device saw>, and
select= the key, the version and the columns it sets, with Prefer: return=representation. A
replayed request therefore needs SELECT on those columns, and its row must pass the table's SELECT
policy, as a supabase-kt write with select() does. The request sent at once, while nothing waits
ahead of it, is still exactly the one you built.
Checklist¶
- Add the dependency and install the plugin last (Project setup).
- Import
io.github.nesfeder.supabase.offline.offline, and swapsupabase.fromforsupabase.offline.fromwhere a read or write should work offline. - Fix the call shapes above; the compiler finds each one.
- Make new rows' ids on the device.
- Call
clearLocalData()when a user signs out. - Show the sync status and the rejected list somewhere in the app.
- For a table several devices edit, name its version column, and show the conflicted list too.