【问题标题】:postgresql function not found找不到postgresql函数
【发布时间】:2016-02-27 10:59:18
【问题描述】:

尝试运行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(text) 不存在

【问题讨论】:

  • INSERT INTO users SELECT email, sha256('mypass') FROM tab_email;
  • @lad2025 这样更好,但没有解释错误。这很奇怪。
  • \df *.sha256 显示什么? SELECT sha256('1') 怎么样?

标签: sql postgresql transactions commit


【解决方案1】:

这是因为 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】:

    我最终使用了

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

    【讨论】:

      【解决方案3】:

      如果你在 redshift 中创建这个函数,你就可以使用你的 f_sha256

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

      【讨论】:

      • 见“Explaining entirely code-based answers”。虽然这在技术上可能是正确的,但它并不能解释为什么它可以解决问题或应该是选择的答案。除了帮助解决问题,我们还应该进行教育。
      猜你喜欢
      • 2019-12-20
      • 2019-05-02
      • 2021-06-17
      • 2019-12-06
      • 2015-08-22
      • 1970-01-01
      • 2021-02-04
      • 2022-10-05
      • 2017-05-24
      相关资源
      最近更新 更多