var productId: Int64? = getProductIdIfExisted() // 1 ..... id or nil
var product = Product(id: productId, name: "NAME") // 2
try product.insert(db) // 3
var order = Order(id: nil, productId: product.id, createdAt: Date())
try order.insert(db)
So both product and order entities has auto-increment primary key. On line "1" I try to find if the product is existed before. If the product does not exist, I insert it . if exists, I replace it. Then I insert order. However I have a problem because new order is not inserted and replaced previous, but I do not set id for order.
For example if I have empty tables and run this method in the first time everything is OK.
However when I run more than one time with product id = 1 I expect that a new order to be inserted. But I always see the id of the previous order updated. So after ten approaches there will be something like this
However when I run more than one time with product id = 1 I expect that a new order to be inserted. But I always see the id of the previous order updated.
An insert that updates? This is a consequence of .primaryKey(onConflict: .replace) policy on the product table.
It looks like you don't know what the ON CONFLICT clause is. Probably you do not need it. And it prevents you from understanding why your program is misbehaving.
So update your migration as below (remove the onConflict argument):
Then erase your application so that the migrator can rebuild the database from scratch, and run your application again.
You should then better understand what is wrong. You will have to read error messages. Yes, do read them! Get ready for learning a little bit about SQLite! That's how you'll make progress. Hold on, and you'll fix your issue.
Firstly I want to pay my respect for you! Yes, I basically did not know it before. So it was helpful.
How did I solve my problem? I removed onConflict: .replace then replaced product.insert(db) by product.save(db). So I had another problem. When I "saved" existed record GRDB always tried to perform inserting instead of updating, because it could not find the primary key despite I passed it.
However when I replaced container[.rowID] = id by container["id"] = id it started working as I wanted.