Sqldelight 1.4 how insert filled data generated object without primarykey (id)
Asked Answered
Z

2

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

Zapata answered 23/1, 2021 at 20:17 Comment(0)
N
13

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"
)
Nils answered 23/2, 2021 at 5:50 Comment(2)
If I add AUTOINCREMENT to the .sqm file I get error ')', ',', <column constraint real>, ASC, DESC or ON expected, got 'AUTOINCREMENT'Glossator
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.Glossator
M
0

You can currently do this

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

insert:
INSERT INTO myTable(name)
VALUES(?);

Then call from your code

query.insert("ShortName")
Melanochroi answered 26/8 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.