Re: Generating random values.

From: Chris Travers <chris(at)travelamericas(dot)com>
To: Fernando Lujan <flujan(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Generating random values.
Date: 2005-08-17 18:16:34
Message-ID: 43037F02.7010501@travelamericas.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi Fernando;

I think that PL/Perl would be the easiest language to use in this case.
However, you could use PL/PGSQL and do something like:
1) Generate a random number (RANDOM()) and multiply it by a base value,
and add something to it to bring it within a certain range.
2) Look up the ASCII character associated with the random number. I
forget the function name, but it is listed, I think, under string
functions in the docs.
3) Concatenate this onto the end of your string. The operator is ||.

Doing this with a fixed-length password would be extremely easy. If you
have to do it with a variable length password, then the logic will need
to be a loop. THis is probably the cleanest way to do it. You could
probably even do this with ANSI SQL functions with a clever case
statement (I am assuming that a function is allowed to call itself).

Something like:

create function random_string(int, varchar) returns varchar AS '
select
CASE WHEN length($2) < $1 THEN random_string($2 || chr((random() *
(ascii_max - ascii_min))::int + ascii_min), $1)
ELSE $2
END
' LANGUAGE SQL;

Of course replace ascii_max and ascii_min with the maximum and minimum
ascii values you want it to use.

You can then create another function like this:
CREATE FUNCTION random_string(int) returns varchar AS '
SELECT random_string($1, '''');
' LANGUAGE SQL;

This becomes much harder when working with Unicode, I think....

Best Wishes,
Chris Travers
Metatron Technology Consulting

Fernando Lujan wrote:

>Hi folks,
>
>I have a table wich contains my users... I want to insert to each user
>a random password, so I need a random function. Is there such function
>in Postgres? I just found the RANDOM which generates values between
>0.0 and 1.0.
>
>Any help or suggestion will be appreciated. :)
>
>Fernando Lujan
>
>---------------------------(end of broadcast)---------------------------
>TIP 9: In versions below 8.0, the planner will ignore your desire to
> choose an index scan if your joining column's datatypes do not
> match
>
>
>
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Dr NoName 2005-08-17 18:26:10 COMMIT in ps output
Previous Message Jonathan Villa 2005-08-17 18:14:43 Re: Adding contrib modules