mysqlsqlpostgresqlbase58

Base58 Encoder function in PostgreSQL


I found this MySQL function for Base58 Encoder in a Github Gist.

DELIMITER $$

CREATE FUNCTION base58_encode (num int) RETURNS varchar(255)
  DETERMINISTIC

BEGIN
  DECLARE alphabet varchar(255);
  DECLARE base_count int DEFAULT 0;
  DECLARE encoded varchar(255);
  DECLARE divisor DECIMAL(10,4);
  DECLARE mode int DEFAULT 0;

  SET alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
  SET base_count = CHAR_LENGTH(alphabet);
  SET encoded = "";

  WHILE num  >= base_count DO
    SET divisor = num / base_count;
    SET mode = (num - (base_count* TRUNCATE(divisor,0)));
    SET encoded = CONCAT(SUBSTRING(alphabet FROM mode+1 FOR 1), encoded);
    SET num = TRUNCATE(divisor,0);
  END WHILE;

  SET encoded = CONCAT(SUBSTRING(alphabet FROM num+1 FOR 1), encoded);

  RETURN (encoded);

END

I am new to PostgreSQL and having difficulty converting above function to PostgreSQL function.

How would be the equivalent PostgreSQL function of above SQL snippet for Base58 Encoder?


Solution

  • Equivalent function in PostgreSQL that I came up with is as follows.

    CREATE FUNCTION base58_encode(num INT)
      RETURNS VARCHAR(255) AS $encoded$
    
    DECLARE
      alphabet   VARCHAR(255);
      base_count INT DEFAULT 0;
      encoded    VARCHAR(255);
      divisor    DECIMAL(10, 4);
      mod        INT DEFAULT 0;
    
    BEGIN
      alphabet := '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
      base_count := char_length(alphabet);
      encoded := '';
    
      WHILE num >= base_count LOOP
        divisor := num / base_count;
        mod := (num - (base_count * trunc(divisor, 0)));
        encoded := concat(substring(alphabet FROM mod + 1 FOR 1), encoded);
        num := trunc(divisor, 0);
      END LOOP;
    
      encoded = concat(substring(alphabet FROM num + 1 FOR 1), encoded);
    
      RETURN (encoded);
    
    END; $encoded$
    LANGUAGE PLPGSQL;