2017-06-28 45 views
6

我正在将一些使用MySQL的工具转换为PostgreSQL。因此,我遇到了很多问题,但能够找到大多数问题。我遇到问题的是HEX()UNHEX()。我试过encode(%s, 'hex')decode(%s, 'hex')这确实停止了,导致我有错误,但它似乎仍然没有成功。有没有人有一个想法,这些功能相当于Postgres?MySQL的HEX()和UNHEX()等同于Postgres?

这里是旧版本的MySQL查询:

SELECT HEX(test_table.hash), 
     title, 
     user, 
     reason, 
     description, 
     url, 
     performed, 
     comment, 
     authenticated, 
     status 
FROM alerts 
JOIN user_responses ON test_table.hash = user_responses.hash 
JOIN test_status ON test_table.hash = test_status.hash 
WHERE status = %s 

这里是PostgreSQL中的格式我更新的查询:

SELECT encode(test_table.hash, 'hex') as hash, 
     title, 
     user, 
     reason, 
     description, 
     url, 
     performed, 
     comment, 
     authenticated, 
     status 
FROM test_table 
JOIN user_responses ON test_table.hash = user_responses.hash 
JOIN test_status ON test_table.hash = test_status.hash 
WHERE status = %s 

谢谢!

回答

4
create function hex(text) returns text language sql immutable strict as $$ 
    select encode($1::bytea, 'hex') 
$$; 

create function hex(bigint) returns text language sql immutable strict as $$ 
    select to_hex($1) 
$$; 

create function unhex(text) returns text language sql immutable strict as $$ 
    select encode(decode($1, 'hex'), 'escape') 
$$; 


select hex('abc'), hex(123), unhex(hex('PostgreSQL')); 

结果:

 
╔════════╤═════╤════════════╗ 
║ hex │ hex │ unhex ║ 
╠════════╪═════╪════════════╣ 
║ 616263 │ 7b │ PostgreSQL ║ 
╚════════╧═════╧════════════╝ 

2

我推荐的Postgres检查出mysqlcompat库,它包含了一大堆的移植到MySQL的Postgres的功能。

您可以看到他们的HEXUNHEX函数的实现。特别注意MySQL的十六进制函数有:two different modes of working

如果参数是一个字符串,则参数中的每个字符都被转换为两个十六进制数字。

如果参数是十进制,则该函数返回参数的十六进制字符串表示形式,并将其视为longlong(BIGINT)数字。

因此,如果您推出自己的产品,请确保您支持所有可能的用例,即mysqlcompat的方式。

相关问题