[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Random string generator function in SQL - better than random()::text ?




for use in  (and other places where we generate passwords)
branches/1.3/sql/upgrade/1.2-1.3.sql


CREATE OR REPLACE FUNCTION random_string(INTEGER)
RETURNS TEXT AS
$BODY$
SELECT array_to_string(
    ARRAY (
        SELECT substring(

'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#&()?[]'
            FROM (ceil(random()*70))::int FOR 1
        )
        FROM generate_series(1, $1)
    ),
    ''
)
$BODY$
LANGUAGE sql VOLATILE;

Test:

$=> select random_string(12);
 random_string
---------------
 LAw)hNFnwciy
(1 row)

$=> select random_string(12) from generate_series(1,15);
 random_string
---------------
 6A[s[u]jAcNI
 1NcZEJ#ZUpW3
 4lr!GRrMcq7b
 c6CnjZ?lxZC4
 t5dFv1Jzn2s)
 TcI[KQZxWmc7
 EZt31?7v2l3x
 nMpSOaOs4hrP
 ]IEW?qeBIPFK
 MM8P0BFnY?8w
 XXhb6Q!6j6cg
 x8r8Y[TvLbCM
 nS2DPA1whjPo
 1IulOOJEX3M[
 2qtOJ?k[QmBp


Can we replace random()::text  with random_string ?
We could make the long '012345......' as a variable or make several selectable variants. (by example exclude characters like I, 1 and l because they look too similar or other variants).


--
Håvard Sørli - http:/www.anix.no