I have looked around for the solution to my problem a lot and haven't found anything. The problem is with inserting a new record into a database table that has an auto increment primary key. Below is the different scenarios and behaviors that I'm getting. Sample code.
model = QSqlTableModel(db = db, table = 'table')
record = model.record()
record.setGenerated('id', False)
record.setValue('name', 'a_name')
model.insertRecord(-1, record)
Scenario 1: Pre-populated table with some rows.
| id | name |
|----|------|
| 1 | name1|
| 2 | name2|
behavior 1: insertRecord does not add a new record to the table. If I remove the setGenerated flag and manually specify an id [record.setValue('id', 3)] I can insert a new record.
Scenario 2: Pre-populated table with some rows and first id not starting at 1.
| id | name |
|----|------|
| 3 | name1|
| 4 | name2|
behavior 2: first insertRecord adds a new record with id = 1, the second insertRecord adds another record with id = 2 . After that insertRecord does not add any new records. It will try to add a new record with id = 3, but id = 3 already exist and it won't jump to the next available id (id = 5). Again if I remove the setGenerated flag and manually specify the next available id [record.setValue('id', 5)] it works.
Scenario 3:
| id | name |
|----|------|
behavior 3: Empty table without any rows. insertRecord will start at id = 1 and continues to add new records with no problem.
How can I fix this problem without having to manually specify an auto incremented id?