Hildebrandt Tobias
02/20/2024, 1:21 PMye olden code
is there no better
way to do this in exposed?
fun upsertTelegramFilter(filter: IbisTelegramFilterDTO) = transaction {
val exists = TelegramFilterTable
.select { TelegramFilterTable.id eq filter.id }
.singleOrNull() != null
if(exists)
TelegramFilterTable.update {
it[this.companyId] = filter.companyId
it[this.name] = filter.name
it[this.type] = filter.type
it[this.text] = filter.text
}
else
TelegramFilterTable.insert {
it[this.companyId] = filter.companyId
it[this.name] = filter.name
it[this.type] = filter.type
it[this.text] = filter.text
}
}
Ruckus
02/20/2024, 5:17 PMupdate
requires 2 arguments, and neither your insert
nor your update
use the filter.id
, so exists
would always be false.
If I am correct in guessing what I think you're trying to do, exposed has an upsert
function:
fun upsertTelegramFilter(filter: IbisTelegramFilterDTO) = transaction {
TelegramFilterTable.upsert {
it[id] = filter.id
it[companyId] = filter.companyId
it[name] = filter.name
it[type] = filter.type
it[text] = fitler.text
}
}
Hildebrandt Tobias
02/20/2024, 6:59 PMHildebrandt Tobias
02/20/2024, 7:03 PMauto_increment
.
Which makes me wonder, what is the behavior of your upsert
on non-existing ids? Does it just omit the given ID and use the one according to the counter? Or does the ID for "inserts with upsert" must be 0 or something?Ruckus
02/20/2024, 7:39 PMupsert
on non-existing ids?
Can you clarify what you mean by non-existing? Generally the way upsert
works (at least as far as I understand it), the database will attempt to insert the record, but if it would cause a duplicate key exception, it instead updates the existing record with the duplicate key to match the given record. In your case, if the ID doesn't exist, then there's no duplicate record, and it's inserted as is.
This does now raise a question as to what filter.id
is set to before it has been inserted into the database. If it always defaults to a "new record" sentinel value, you can just include that logic in the upsert:
fun upsertTelegramFilter(filter: IbisTelegramFilterDTO) = transaction {
val inserted = TelegramFilterTable.upsert {
if (filter.id != NEW_RECORD) it[id] = filter.id
it[companyId] = filter.companyId
it[name] = filter.name
it[type] = filter.type
it[text] = fitler.text
}
filter.id = inserted[TelegramFilterTable.id]
}
Then I assume it would just insert the record with the appropriate auto-incremented ID. You may then need to ensure you update the fitler
to use that new ID.Ruckus
02/20/2024, 7:40 PMHildebrandt Tobias
02/21/2024, 5:28 PMRuckus
02/21/2024, 6:10 PMnull
as the sentinel), different models for values that have or haven't been added, etc.). It's just a matter of how you translate your data representation to/from the exposed representation of the same concepts.Hildebrandt Tobias
02/21/2024, 6:31 PMRuckus
02/21/2024, 6:44 PMAxel
04/02/2024, 9:59 AM