Convert code to use dangerouslyOnDuplicateKeyUpdate #916
Answered
by
nakamura-to
Distractic
asked this question in
Q&A
-
Hello ! This is my old code : private suspend fun insertOrUpdateAll(
uuid: UUID,
friendIds: List<UUID>,
pending: Boolean
): Boolean {
val meta = _Friend.friend
val metaUUID = meta.uuid
val uuid1Name = metaUUID.uuid1.name
val uuid2Name = metaUUID.uuid2.name
val pendingName = meta.pending.name
val query = QueryDsl.executeTemplate(
"""
INSERT INTO ${meta.tableName()} ($uuid1Name, $uuid2Name, $pendingName)
VALUES ${friendIds.indices.joinToString(", ") { "(/*uuid*/'', /*uuid$it*/'', /*pending*/false)" }}
ON CONFLICT (GREATEST($uuid1Name, $uuid2Name), LEAST($uuid1Name, $uuid2Name))
DO UPDATE SET $pendingName = /*pending*/false WHERE ("${meta.tableName()}".$pendingName = true AND /*pending*/false = false)
""".trimIndent()
)
.bind("uuid", uuid)
.let {
friendIds.foldIndexed(it) { index, acc, friendId ->
acc.bind("uuid$index", friendId)
}
}
.bind("pending", pending)
return database.runQuery(query) > 0
} This is my converted code : private suspend fun insertOrUpdateAll(
uuid: UUID,
friendIds: List<UUID>,
pending: Boolean
): Boolean {
val meta = _Friend.friend
val metaUUID = meta.uuid
val uuid1Name = metaUUID.uuid1.name
val uuid2Name = metaUUID.uuid2.name
val metaPending = meta.pending
val friends = friendIds.map { friend ->
Friend(FriendId(uuid, friend), pending)
}
val query = QueryDsl.insert(meta)
.dangerouslyOnDuplicateKeyUpdate("(GREATEST($uuid1Name, $uuid2Name), LEAST($uuid1Name, $uuid2Name))")
.set {
metaPending eq pending
}
.where {
if(!pending) {
metaPending eq true
}
}
.multiple(friends)
return (database.runQuery(query) > 0)
} Some tests don't work as expected (some relation is always inserted/updated, etc.) |
Beta Was this translation helpful? Give feedback.
Answered by
nakamura-to
Mar 11, 2023
Replies: 1 comment 1 reply
-
Hello!
You can write as follows: .where {
metaPending eq true
literal(false) eq pending
} See also https://www.komapper.org/docs/reference/query/querydsl/expression/#literal. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
Distractic
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello!
You can write as follows:
See also https://www.komapper.org/docs/reference/query/querydsl/expression/#literal.