Convert byte array to readable String in psql taking input from select statement

Viewed 14

I am working with a database with key-value store, and the data is in a form of an byte array. \d on stats I have used this example to decode a byte array

select convert_from(decode('121412432d3134323932342e3132325a', 'hex'), 'UTF8');

Which works fine. But when I try to get the values to decode with a Select statement:

select convert_from(decode(select columnvalue from stats limit 1), 'hex'), 'UTF8');

I am getting

No function matches the given name and argument types. You might need to add explicit type casts.

From what I understand, the decode function expects a byte array, but from the select statement is getting a String. Is that assumption correct? How would I go resolving it?

I have tried to encode the result, and then decode it, but I am getting the same problem.

SELECT convert_from(decode(encode(convert_to((select columnvalue from stats limit 1),'UTF-8'),'base64'),'hex'),'UTF8');

Full query with error:

SELECT convert_from(decode(encode(convert_to((select columnvalue from stats limit 1),'UTF8'),'base64'),'hex'),'UTF8');
ERROR:  function convert_to(bytea, unknown) does not exist
LINE 1: SELECT convert_from(decode(encode(convert_to((select columnv...
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
1 Answers

you have to convert the bytea to character varying and replace the \x with '' after that you will get

create table dobytea(columnvalue bytea);
insert into dobytea values (decode('121412432d3134323932342e3132325a', 'hex'));

select convert_from(decode('121412432d3134323932342e3132325a', 'hex'), 'UTF8');
select columnvalue from dobytea limit 1;

select convert_from(decode(
 (select replace (columnvalue::CHARACTER VARYINg,'\x','') from dobytea limit 1)
  , 'hex'), 'UTF8') as conv;

OUTPUT :

convert_from
C-142924.122Z

columnvalue
\x121412432d3134323932342e3132325a


conv
C-142924.122Z
Related