Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

javascript - Random string unique in database table

I need to generate a random string (8 digit alphanumeric code) and save it with my Tournament row into a database.

Problem is that this code needs to be unique in the whole table and random (not incremental) because I don't want it to be predictable (people using it to join tournament).

So I need something to genreate a code but when it already is in table then generate new one. One way is to generate code, then check database existance, then generate new in case of conflict. But this solution have many problems like it can run forever and its is slow.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer is to use a unique identifier that combines a "unique" part and a "random" part.

  • The "unique" part can be a monotonically increasing counter (such as the record or row number in a database), or it can be a number generated with a full-period linear congruential generator (which cycles pseudorandomly through all possible values in its period before repeating).
  • The "random" part is simply a random number generated with a cryptographic random number generator (which Node.js has; check the documentation). In general, the longer it is, the less predictable it will be.

Moreover, for the purposes of generating unique identifiers, there is little reason to limit yourself to 8-character alphanumeric identifiers as you're now doing.

Even if you expect end users to enter a "random" and "unique" ID at some point, there are techniques you can use to ease the task of entering IDs much longer than 8 characters; they include—

  • adding a "checksum" character to the ID,
  • dividing the ID into hyphen-separated chunks, and
  • employing a system similar to Bitcoin's BIP39, in which each ID is convertible to a sequence of memorable words.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...