Ruby on Rails Monday, January 31, 2011

Karl Smith wrote in post #978730:
> I need to generate a unique serial number in numerical order, but only
> unique for each user.
> For example, each user can create a new credit card and each new credit
> card
> must start at a predetermined number and increment by 1 for each new
> credit
> card for that user. Thus, credit card numbers are unique for a user but
> not
> unique for the CreditCard table. And yes, it is absolutely critical that
> credit card numbers are always unique for each user.

I hope this "credit card" scenario is a contrived example. It seems to
me that it would be critical for the credit card number to be unique
across ALL users.

> I'm using PostgreSQL.
> Looking through the docs it doesn't appear that I can use either
> pessimistic
> locking or optimistic locking. Maybe I'm wrong?

You are correct. Row level locking is useless to prevent the duplication
of values between rows due to the race condition during a SQL INSERT.

A unique index (possibly across multiple fields) would prevent such

> Is my only option to lock the table, find the highest credit card
> number,
> add 1, update the new credit card number, save, and release the table
> lock?

It might be possible for you to use a sequence. But, in your case you
would need a separate sequence for each user if I understand you
correctly. Although this might work it may not be appropriate in your

My concern about locking the entire table would be that if something
went wrong then you might end up in a state where your entire table is
stuck in a locked state. I don't know for sure if that's an issue with
PostgreSQL, but something to consider.

There may also be other considerations if you ever have a need to use
more that one database backend for the purposes of scaling.

I would also try to avoid having to use a "max value" query every time
you needed to find the next number in sequence. You could instead create
a table that contains a foreign key to your users table with the next
sequence value stored there. You would then increment that value for
each insert similar to how database sequences work. This way you should
only have to be concerned about concurrent access to the table used for

Good luck, I hope this helps at least a little.

Posted via

You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

No comments:

Post a Comment