Skip to content

Instantly share code, notes, and snippets.

Created October 21, 2013 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/7088877 to your computer and use it in GitHub Desktop.
Save anonymous/7088877 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION djb2_hash(string text)
RETURNS bigint
LANGUAGE sql
AS $$
WITH RECURSIVE t(seed, string) AS (
VALUES (
87049::bigint,
$1
)
UNION ALL
SELECT
(
(
(t.seed << 5) #
t.seed #
ascii (
substr (
t.string,
1,
1
)
)
)
),
substr (
t.string,
2
)
FROM t
)
SELECT seed & ~(1::bigint << 31)
FROM t
WHERE string = ''
$$;
WITH v(s) AS (
VALUES
('foo'),
('bar'),
('http://www.disqus.com'),
('etc'),
('etc.')
)
SELECT s, djb2_hash(s)
FROM v;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment