Re: Random-looking primary keys in the range 100000..999999 - Mailing list pgsql-general

From Martijn van Oosterhout
Subject Re: Random-looking primary keys in the range 100000..999999
Date
Msg-id 20140705083552.GF415@svana.org
Whole thread Raw
In response to Random-looking primary keys in the range 100000..999999  (Kynn Jones <kynnjo@gmail.com>)
Responses Re: Random-looking primary keys in the range 100000..999999  (Kynn Jones <kynnjo@gmail.com>)
List pgsql-general
On Fri, Jul 04, 2014 at 09:24:31AM -0400, Kynn Jones wrote:
> I'm looking for a way to implement pseudorandom primary keys in the range
> 100000..999999.
>
> The randomization scheme does not need to be cryptographically strong.  As
> long as it is not easy to figure out in a few minutes it's good enough.

Well, a trick that produces a not too easy to guess sequence is:

X(n) = p^n mod q

where q is prime. Pick the largest prime that will fit, in this case
899981 (I beleive) and some random p, say 2345.

Then 100000 + (2345^n) mod 899981

should be a sequence fitting your purpose. Unfortunatly, the pow()
function in Postgres can't be used here (too slow and it overflows),
but python has a helpful function:

In [113]: len( set( pow(2345, n, 899981) for n in range(899981)  ) )
Out[113]: 899980

You could probably write an equivalent function in Postgres if
necessary.

Hope this helps,
--
Martijn van Oosterhout   <kleptog@svana.org>   http://svana.org/kleptog/
> He who writes carelessly confesses thereby at the very outset that he does
> not attach much importance to his own thoughts.
   -- Arthur Schopenhauer

Attachment

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: pg_dump slower than pg_restore
Next
From: Michael Paquier
Date:
Subject: Re: memory leak while trying to update/alter column in postgresql