Skip to content

Instantly share code, notes, and snippets.

@timothyklim
Created November 5, 2012 13:27
Show Gist options
  • Save timothyklim/4017174 to your computer and use it in GitHub Desktop.
Save timothyklim/4017174 to your computer and use it in GitHub Desktop.
PLV8 base52 implementation
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE EXTENSION IF NOT EXISTS plv8;
DROP FUNCTION IF EXISTS to_base52(digit_number bigint);
DROP FUNCTION IF EXISTS to_base52(digit_number text, base integer);
CREATE FUNCTION to_base52(digit_number bigint) RETURNS text AS
$$
var codeset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
var base = codeset.length
var converted = ''
while (digit_number > 0) {
converted = codeset.substr((digit_number % base), 1) + converted
digit_number = Math.floor(digit_number / base)
}
return converted
$$
LANGUAGE plv8 IMMUTABLE STRICT;
CREATE FUNCTION to_base52(digit_number text, base integer) RETURNS text AS
$$
var digit_number = parseInt(digit_number, base)
var codeset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
var base = codeset.length
var converted = ''
while (digit_number > 0) {
converted = codeset.substr((digit_number % base), 1) + converted
digit_number = Math.floor(digit_number / base)
}
return converted
$$
LANGUAGE plv8 IMMUTABLE STRICT;
SELECT
encode(
encrypt ('1000000000000', 'key', 'aes'),
'hex'
),
encode(
encrypt ('100000000000', 'key', 'aes'),
'base64'
),
to_base52 (encode(
encrypt ('1000000000000', 'key', 'aes'),
'hex'
), 16);
@timothyklim
Copy link
Author

SELECT
to_base52 (encode(
encrypt ('1000000000000', 'key', 'aes'),
'hex'
), 16)
from generate_series(1, 500000)
limit 1;

-- 0.09 sec elapsed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment