Nonemoticoner
Nonemoticoner

Reputation: 648

How to reattempt inserting into database if there was already such unique value stored

I searched for any existing patterns but didn't happen to find anything.

So, the thing is I want to store in my MySQL database some key value which would be unique. I generate it on server side like that:

var pc = require('password-creator');
var key = pc.create(20); //  "f9Wp>=\qJqx]rwwbbiQ8

Then I send it to database:

 connection.query(db_query, function (err, rows, fields) {
    if(err){
        if(err.code == "ER_DUP_ENTRY"){
            // here I could attempt again with newly generated key by
            // calling another query to database but this is giving me 
            // a limited amount of such attempts
        }
    }
    else{
        // there was no duplicate
    }
});

So everything seems fine but there is a slight possibility to get ER_DUP_ENTRY. And now is my question:

How to solve such situation the right way? I mean that I always want to input some key value in database. I thought of loops but this feels stupid because it's an asynchronous query to database. I'm basically looking for the right approach in such situations.

Upvotes: 0

Views: 42

Answers (1)

Koder
Koder

Reputation: 474

This should be as simple as wrapping your generate-unique-value-and-insert code block into a function you can re-call if duplicate key occurs:

function tryToStoreUnique()
{
    var db_query = buildDbQuery(pc.create(20));
    connection.query(db_query, function (err, rows, fields) {
    if(err) {
        if(err.code == "ER_DUP_ENTRY"){
           // you can add counter to avoid lock if most of unique space is occupied
           tryToStoreUnique();
        }
    }
    else{
        // there was no duplicate
    }
  });
}

Upvotes: 2

Related Questions