Jump to content

Thread Safe InnoDB Insert


barneyf

Recommended Posts

I am looking for suggestions on implementing a thread safe way to insert a new row into a WorkOrder table.  The table will be InnoDB with an AutoIncrement UID primary key. But the WorkOrder field is based on 4 alpha-numeric characters (format specified by the user) and will be unique for each row.  The field is alpha-numeric, so I can’t use a simple AutoIncrement integer value.  The rate of inserts will be very low, about 20 per day.  Queries to the table will be several thousand per day.

 

Since I must read the latest WorkOrder field in order to create the next one, I have to prevent concurrent threads from reading the same last WorkOrder value at the same time and generating duplicate WorkOrder values.  Can I use the InnoDB row locking to prevent duplicates, do I lock the whole table, or is there a better way (ie a PHP analog to JSP synchronized) to ensure thread safety?

 

Thanks,

Barney

Link to comment
Share on other sites

Looks good.  Since I want to base the new work order number on the last one stored in the table, I guess the basic process (excluding error handling) is:

 

Table: WorkOrders
Fields: id     AutoIncrement integer & primary key
         wo    User defined work order UUID


SET AUTOCOMMIT = 0
BEGIN
SELECT * FROM WorkOrders ORDER BY id DESC LIMIT 1 FOR UPDATE
   /* extract wo value from data set, increment, and assign to a variable $next_wo */
INSERT INTO WorkOrders (wo) VALUES ('$next_wo')
COMMIT

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.