找不到postgresql函数

时间:2015-11-24 20:29:26

标签: sql postgresql transactions commit

尝试运行sha256功能

CREATE EXTENSION pgcrypto;
CREATE OR REPLACE FUNCTION sha256(bytea) returns text AS $$
    SELECT encode(digest($1, 'sha256'), 'hex')
$$ LANGUAGE SQL STRICT IMMUTABLE;

WITH
tab_email as        (SELECT 'my@email.com'::text as email FROM tmp),
INSERT INTO users (email, password) VALUES ((SELECT email FROM tab_email), sha256('mypass'));

我收到了这个错误

  

错误:函数sha256(文本)不存在

3 个答案:

答案 0 :(得分:0)

我最终使用

encode(digest(password, 'sha256'), 'hex') from tab_password)

答案 1 :(得分:0)

这是因为Postgres的内置sha256函数带有一个bytea参数:

citus=> \df+ sha256
                                                                               List of functions
   Schema   |  Name  | Result data type | Argument data types | Type | Volatility | Parallel |  Owner   | Security | Access privileges | Language | Source code  | Description
------------+--------+------------------+---------------------+------+------------+----------+----------+----------+-------------------+----------+--------------+--------------
 pg_catalog | sha256 | bytea            | bytea               | func | immutable  | safe     | postgres | invoker  |                   | internal | sha256_bytea | SHA-256 hash
(1 row)

因此,只需先投射到::bytea

citus=> select encode(sha256('a'::bytea), 'hex');
                              encode
------------------------------------------------------------------
 ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb
(1 row)

答案 2 :(得分:-1)

CREATE OR REPLACE FUNCTION f_sha256 (mes VARCHAR)
returns VARCHAR
STABLE AS $$
import hashlib
return hashlib.sha256(mes).hexdigest()
$$ language plpythonu;