'How to know last inserted id, if the database is not availiable?
I have a system that writes records in a database. If the database is down however, the system fails-over and writes data to csv files (one file per table).
The question is how to permanently store last inserted order id, such that if the database is not available on application load, I will know from what Id to resume writing? I am concerned about ruining the SSD from constantly updating a number in a file.
Further details on the problem:
The data that need to be saved in the database:
struct Order{
int id;
string date;
string clientName;
vector<OrderItem> items;
}
The database has an Orders table and an OrderItems table. OrderItems has a foreign key to Order.id
I want to be able to bulk insert in the database. For example if the average order has 5 items. Inserting 1000 records in Orders followed by 5000 records in OrderItems.
From experimenting I found that I can't use bulk-insert and also be given the lastInsert id for each of the inserted rows. I need to know the Order.id because its a foreign key in OrderItems.
So I am left with the option that OrderId must be a number assigned to and maintained by my application and not the database.
Further more, my application has to be able to switch to writing to CSV files, which can be imported to the database later when it becomes available.
Let's say the application has written in the database upto OrderId 12345. Then the application crashes, and the db is offline. The application restarts, and I can't connect to the database. How will the application know the last inserted Id, so that I can write proper ids to the Orders.csv and OrderItems.csv files?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
