8

I have problem with saving data to sqldelight 1.4 in Android app.

I created table:

CREATE TABLE myTable(
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    name TEXT
);

In repo class I have insert function with myTable object as an argument

fun insert(item: myTable) {
     myTableQueries.insert( 
        name = item.name
     )
}

And in some action i try to create new object Table with name but without id, as id is auto incremented. I had not found any info how to do that. Which is the best solution?

  1. Create a new class (myTablexpress) with the same parameters as the data class (myTable), use this object in the argument of the insert function in the repo class, and use these parameters?
  2. Not create a new myTable instance in action class, but use insert function and put string value as parameter?
myTableViewModel.insert(name)
  1. Create new class myTable without id
@Parcelize
class myTable(val name: String) : Parcelable

and in viewmodel use params?

  1. none of them

Thanks

mlody92
  • 83
  • 1
  • 6

1 Answers1

11

This topic is already discusssed in sqldelight issue here: https://github.com/cashapp/sqldelight/issues/1284

You can define your sqlite insert statement in your .sq file using ? parameters for all the variables, as the doc of sqldelight states: https://cashapp.github.io/sqldelight/android_sqlite/

Example:

CREATE TABLE hockeyPlayer (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  player_number INTEGER NOT NULL,
  full_name TEXT NOT NULL
);

insert:
INSERT INTO hockeyPlayer
VALUES (?, ?, ?);

And from your Kotlin code you can pass null for its id, which makes auto-incrementation work:

query.insert(
  id = null,
  player_number = 100,
  full_name = "name"
)
shoheikawano
  • 1,092
  • 3
  • 14
  • 31
  • If I add AUTOINCREMENT to the .sqm file I get error `')', ',', , ASC, DESC or ON expected, got 'AUTOINCREMENT'` – tonisives Apr 13 '22 at 00:23
  • If I have the ` id INTEGER PRIMARY KEY` there is error when inserting null: `Null can not be a value of a non-null type Int`. Maybe its because I'm using postgres. – tonisives Apr 13 '22 at 00:24
  • Primary key can not be null, that why you had that error. – mlody92 Sep 14 '22 at 17:46