Kotlin: Upsert data
- Primary keys should be included in the data payload in order for an update to work correctly.
- Primary keys must be natural, not surrogate. There are however, workarounds for surrogate primary keys.
- If you need to insert new data and update existing data at the same time, use Postgres triggers.
- When calling
insert
or update
, you have to provide a serializable value in the function parameter.
Examples
Upsert your data
val toUpsert = Message(id = 3, message = "foo", username = "supabot")
supabase.postgrest["messages"].insert(toUpsert, upsert = true)
Upserting into tables with constraints
let toUpsert = User(username = "supabot")
supabase.postgrest["users"].insert(toUpsert, upsert = true, onConflict = "username")
Return the exact number of rows
let toUpsert = User(username = "supabot")
val count = supabase.postgrest["users"].insert(toUpsert, upsert = true, onConflict = "username", count = Count.EXACT).count()