Replacing sequence with random number

前端 未结 6 1571
被撕碎了的回忆
被撕碎了的回忆 2020-12-28 19:28

I would like to replace some of the sequences I use for id\'s in my postgresql db with my own custom made id generator. The generator would produce a random number with a ch

6条回答
  •  攒了一身酷
    2020-12-28 20:07

    How you generate the random and unique ids is a useful question - but you seem to be making a counter productive assumption about when to generate them!

    My point is that you do not need to generate these id's at the time of creating your rows, because they are essentially independent of the data being inserted.

    What I do is pre-generate random id's for future use, that way I can take my own sweet time and absolutely guarantee they are unique, and there's no processing to be done at the time of the insert.

    For example I have an orders table with order_id in it. This id is generated on the fly when the user enters the order, incrementally 1,2,3 etc forever. The user does not need to see this internal id.

    Then I have another table - random_ids with (order_id, random_id). I have a routine that runs every night which pre-loads this table with enough rows to more than cover the orders that might be inserted in the next 24 hours. (If I ever get 10000 orders in one day I'll have a problem - but that would be a good problem to have!)

    This approach guarantees uniqueness and takes any processing load away from the insert transaction and into the batch routine, where it does not affect the user.

提交回复
热议问题