GRDB inserted row is not accessible

I have a table defined as:

try db.create(table: "availablePlayer") {table in
table.autoIncrementedPrimaryKey("playerId")
table.column("name"), .text).notNull()

In my testing, I am selecting 9 rows from one table and inserting those rows into this "availablePlayer" table. This works. When I query the "availablePlayer" table, I have playerId's from 301 to 309. I then attempt to add a new player to the "availablePlayer" table. The trace show this statement as

INSERT INTO availablePlayer (name) VALUES('Smith').

After the insert, I execute

let lastRow = db.lastInsertedRowID

which returns a value of 310. This all makes sense. But when I use DB Browser for SQLite to view the rows in the "availablePlayer" table, there is no row with a playerId of 310 and a name of "Smith". Also, when I query sqlite_sequence, it show the seq column as having a value of 310.
If I then delete all of the rows in the "availablePlayer" table and rerun my app, the 9 rows get inserted. And the rows have playerId's of 311 to 318

I am not getting any errors.

As a follow up. I commented out the code where I deleted the existing rows in "availablePlayer" and then populate it. So now when I added a new player, the table was empty. The new player was added successfully. I have move my delete into its own {db in ...} and instead of doing all of my inserts in a loop within a single {db in ...} structure, I have moved the loop outside of the {db in ... }. But none of this has had a positive affect on the outcome. I just am at a loss.

Not familiar with GRDB, but could it be that some kind of flush-to-db op is needed for the data to be eventually written to the permanent store?

Hello @warrenpettit,

As suggested above, make sure your changes are persisted on disk by proceeding to the end of the database transaction:

try dbQueue.write { db in
  // Inserts, deletes and updates
  // are NOT committed to disk...
}
// <- until the transaction is completed. 

Take also care of not deleting the inserted rows before checking your assumptions in DB Browser for SQLite. You'll see exactly what your app is doing by enabling the SQL trace.

I am trying to learn SwiftUI and I am having a hard time with when SwiftUI fires off events. A that was the problem here. The code that cleared my table and repopulated it was executed. Then later, I executed the code to add the new player. But as it turns out, the clearing the table and the repopulation was fired a second time. Hence, the added player doesn't show up. So it had nothing to do with GRDB.

1 Like

I'm glad you could find the origin of the issue. Don't hesitate using the debugging tools, such as tracing SQL statements: they can answer many questions. There is also a FAQ in the main README that can help when troubleshooting. In all cases, it's always ok to ask questions :+1: