[英]MySQL's HEX() and UNHEX() equivalent in Postgres?
我正在將一些使用 MySQL 的工具轉換為 PostgreSQL。 有了這個,我遇到了許多問題,但能夠找到大部分內容。 我遇到的問題是HEX()
和UNHEX()
。 我已經嘗試過encode(%s, 'hex')
和decode(%s, 'hex')
,它們實際上不再導致我出錯,但它似乎仍然沒有成功。 有沒有人知道 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
謝謝!
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 ║ ╚════════╧═════╧════════════╝
它是 PostgreSQL:一切皆有可能:)
我建議查看 Postgres 的mysqlcompat庫,它包括一大堆移植到 Postgres 的 MySQL 函數。
您可以查看它們對HEX或UNHEX函數的實現。 特別注意 MySQL 的十六進制函數有兩種不同的工作模式:
如果參數是字符串,則參數中的每個字符都將轉換為兩個十六進制數字。
如果參數為十進制,則該函數返回該參數的十六進制字符串表示形式,並將其視為 longlong(BIGINT) 數字。
因此,如果您自己動手,請確保您支持所有可能的用例,就像 mysqlcompat 那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.