Created
September 5, 2012 08:02
-
-
Save xen/3632970 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| CREATE OR REPLACE FUNCTION unique_key_create() | |
| RETURNS text AS | |
| $BODY$ | |
| DECLARE | |
| _length INTEGER := 10; --from backend settings | |
| _key TEXT; | |
| BEGIN | |
| WHILE TRUE LOOP | |
| SELECT array_to_string( | |
| ARRAY (SELECT substring('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' | |
| FROM (ceil(random()*62))::int FOR 1) | |
| FROM generate_series(1, _length)), '') INTO _key; | |
| BEGIN | |
| INSERT INTO "unique_key" ("key") VALUES (_key); | |
| RETURN _key; | |
| EXCEPTION WHEN unique_violation THEN | |
| -- pass | |
| END; | |
| END LOOP; | |
| END; | |
| $BODY$ | |
| LANGUAGE plpgsql VOLATILE | |
| COST 100; | |
| ALTER FUNCTION get_key() | |
| OWNER TO postgres; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment