Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

sql - MySQL's HEX() and UNHEX() equivalent in Postgres?

I'm in the process of converting some tools over that are using MySQL to PostgreSQL. With that, I've run into a number of issues but was able to find most everything. The one I'm having an issue with is HEX() and UNHEX(). I've tried encode(%s, 'hex') and decode(%s, 'hex') which did actually stop causing me to have errors, but it still did not seem to do the trick. Does anyone have an idea to what the equivalent of those functions would be in Postgres?

Here is the old MySQL query:

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

And here is my updated query in PostgreSQL format:

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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'));

Result:

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

It is PostgreSQL: everything possible :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...