asleepingpanda
06/02/2022, 2:05 PMeTsiE3tmnI4
for example).
The function is run as the default value on a column in my dB
I'm getting some kind of syntax error, but there are little to no details in the error. Does anybody see anything wrong with it?? Thanks!!
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
CREATE OR REPLACE FUNCTION generate_shortkey()
RETURNS TEXT AS
$$
DECLARE
gkey TEXT;
key TEXT;
qry TEXT;
found TEXT;
BEGIN
-- generate the first part of a query as a string with safely
-- escaped table name, using || to concat the parts
qry := 'SELECT shortkey FROM ' || quote_ident(TG_TABLE_NAME) || ' WHERE shortkey=';
LOOP
-- 8 bytes gives a collision p = .5 after 5.1 x 10^9 values
gkey := encode(gen_random_bytes(8), 'base64');
gkey := replace(gkey, '/', '_'); -- url safe replacement
gkey := replace(gkey, '+', '-'); -- url safe replacement
key := rtrim(gkey, '='); -- cut off padding
-- Concat the generated key (safely quoted) with the generated query
-- and run it.
-- SELECT id FROM "test" WHERE id='blahblah' INTO found
-- Now "found" will be the duplicated id or NULL.
EXECUTE qry || quote_literal(key) INTO found;
-- Check to see if found is NULL.
-- If we checked to see if found = NULL it would always be FALSE
-- because (NULL = NULL) is always FALSE.
IF found IS NULL THEN
-- If we didn't find a collision then leave the LOOP.
EXIT;
END IF;
-- We haven't EXITed yet, so return to the top of the LOOP
-- and try again.
END LOOP;
RETURN key
END
$$ language 'plpgsql';
garyaustin
06/02/2022, 2:16 PMasleepingpanda
06/02/2022, 3:08 PMsyntax error at end of input
and the postgres logs say the samegaryaustin
06/02/2022, 3:14 PMasleepingpanda
06/02/2022, 3:22 PMRETURN key
Thank you for the extra set of eyes!!