Skip to content

Commit f71830e

Browse files
authored
Add helpful functions for interacting with db manually (modrinth#3602)
Brought over from modrinth/labrinth#862
1 parent bd0d6a9 commit f71830e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
CREATE OR REPLACE FUNCTION from_base62(input VARCHAR)
2+
RETURNS BIGINT AS $$
3+
DECLARE
4+
base INT := 62;
5+
chars VARCHAR := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
6+
result BIGINT := 0;
7+
i INT;
8+
char VARCHAR;
9+
index INT;
10+
BEGIN
11+
FOR i IN 1..LENGTH(input) LOOP
12+
char := SUBSTRING(input FROM i FOR 1);
13+
index := POSITION(char IN chars) - 1;
14+
IF index < 0 THEN
15+
RAISE EXCEPTION 'Error: Invalid character in input string';
16+
END IF;
17+
result := result * base + index;
18+
END LOOP;
19+
20+
RETURN result;
21+
END;
22+
$$ LANGUAGE plpgsql;
23+
24+
CREATE OR REPLACE FUNCTION to_base62(input BIGINT)
25+
RETURNS VARCHAR AS $$
26+
DECLARE
27+
base INT := 62;
28+
chars VARCHAR := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
29+
result VARCHAR := '';
30+
remainder INT;
31+
BEGIN
32+
WHILE input > 0 LOOP
33+
remainder := input % base;
34+
result := SUBSTRING(chars FROM remainder + 1 FOR 1) || result;
35+
input := input / base;
36+
END LOOP;
37+
38+
RETURN result;
39+
END;
40+
$$ LANGUAGE plpgsql;

0 commit comments

Comments
 (0)