Update
UPDATE statements with setParams, exclusions, and returning
The update statement is similar to the insert statement. You can use the set function to set the values of the columns you want to update, and typically you will use param to set SQL placeholders for runtime values. Use a .where clause to filter your update query.
val joeName = "Joe"
val joeAge = 44
val joeId = 123
val q =
sql {
update<Person> {
set(name to param(joeName), age to param(joeAge))
.where { id == param(joeId) }
}
}
q.buildFor.Postgres().runOn(myDatabase)
// > UPDATE Person SET name = ?, age = ?, companyId = ? WHERE id = 1
Similar to INSERT, you can use setParams to set columns from the entire person object. Combine this with excluding to exclude the primary key column from the update statement and use the where clause to filter your update query.
val person = Person(id = 1, "Joe", 44, 123)
val q =
sql {
update<Person> { setParams(person).excluding(id) }
.where { id == param(joeId) }
}
q.buildFor.Postgres().runOn(myDatabase)
//> UPDATE Person SET name = ?, age = ?, companyId = ? WHERE id = 1
Update with Returning
You can also use a returning clause to return the updated row if your database supports it.
val person = Person(id = 1, "Joe", 44, 123)
val q =
sql {
update<Person> { setParams(person).excluding(id) }
.where { id == param(joeId) }
.returning { p -> p.id }
}
q.buildFor.Postgres().runOn(myDatabase) // Also works with SQLite
//> UPDATE Person SET name = ?, age = ?, companyId = ? WHERE id = ? RETURNING id
q.buildFor.SqlServer().runOn(myDatabase)
//> UPDATE Person SET name = ?, age = ?, companyId = ? OUTPUT INSERTED.id WHERE id = ?