-2

I am developing an application using Room. The operation is simple, if the table has the same letter, the letterscore will increase by 1, otherwise it will be added and letterscore will be 0. In my Dao, I wrote a query as below to upsert the data, but it gives

compound operator>, LIMIT, ORDER, comma or semicolon expected, got 'ON'

error in the "ON" part:

@Dao
interface LetterDao {

    @Query("INSERT INTO letter_table(letter, letterScore) VALUES (:letter, :letterScore) ON CONFLICT(letter) DO UPDATE SET letterScore = letterScore + 1")
    suspend fun insertLetter(letter: String, letterScore: Int)
}

How can I fix this error or how can I do the upsert operation using Room ? Thanks for any help.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Hasan Cihad Altay
  • 171
  • 1
  • 4
  • 11
  • 2
    Probably you are running your app on a device with a version of SQLite older than 3.24.0 when UPSERT was introduced. – forpas Jul 18 '22 at 20:47

2 Answers2

0

For versions of SQLite that do not support UPSERT you need 2 separate statements.

First, try to update the table:

UPDATE letter_table SET letterScore = letterScore + 1 WHERE letter = :letter

If :letter does not exist in the table then nothing will happen.

Then, try to insert a new row:

INSERT OR IGNORE INTO letter_table(letter, letterScore) VALUES (:letter, 0) 

If :letter already exists in the table then nothing will happen.

forpas
  • 160,666
  • 10
  • 38
  • 76
0

I changed this part in my code:

@Query("INSERT INTO letter_table(letter, letterScore) VALUES (:letter, :letterScore) ON CONFLICT(letter) DO UPDATE SET letterScore = letterScore + 1")
        suspend fun insertLetter(letter: String, letterScore: Int)

with

@Query("INSERT OR REPLACE INTO letter_table(letter, letterScore) VALUES (:letter, COALESCE((SELECT letterScore + 1 FROM letter_table WHERE letter=:letter), 0))")
        suspend fun insertLetter(letter: String)

and it worked.

Hasan Cihad Altay
  • 171
  • 1
  • 4
  • 11
  • 1
    This is not equivalent to UPSERT. Read this: https://stackoverflow.com/a/4253806/10498828 – forpas Jul 21 '22 at 08:24