5

I'm trying to use Postgresql encode() function and put some other functions as it's arguments. I get errors, and I can't understand why.

I am using Postgres 9.6.14 on Windows.

  1. This works fine and returns 698d51a19d8a121ce581499d7b701668
select md5('111'); 
  1. This also works fine and returns some value
select encode('698d51a19d8a121ce581499d7b701668', 'base64');
  1. But this one, which combines the first 2, doesn't work and returns "ERROR: function encode(text, unknown) does not exist"
select encode(md5('111'), 'base64');
  1. This also doesn't work and returns the same error
select encode(concat('1', '11'), 'base64');
  1. I thought that there is a rule which prevents to use one function inside another, but the following one works fine and returns the same value as the first request here, as expected.
select md5(concat('1', '11'))

So what's the issue with requests number 3 and 4 and encode() function overall?

1 Answers1

3

Look at the definition of encode:

\df encode
                          List of functions
   Schema   |  Name  | Result data type | Argument data types | Type 
------------+--------+------------------+---------------------+------
 pg_catalog | encode | text             | bytea, text         | func
(1 row)

The first argument has to be bytea, that is a binary byte string.

Your first two queries work because string literals are of type unknown, which can be cast to bytea implicitly.

In the queries that do not work, you are using the functions md5 and concat, which both have text as a result type. Now there is no implicit cast between text and bytea, hence the error message.

To make that work, you have to introduce an explicit type cast:

select encode(CAST(md5('111') AS bytea), 'base64');
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
  • 1
    Though if your aim is to get the base64 representation of the MD5 hash, you probably want `encode(CAST('\x' || md5('111') AS bytea), 'base64')` instead – Nick Barnes Jul 04 '19 at 12:15