postgresql 覆盖Postgres now()函数

q8l4jmvw  于 2022-12-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(138)

在我的测试数据库中,我想覆盖Postgres中的now(),这样我就可以旅行到某个时间点。

CREATE SCHEMA if not exists override;
CREATE OR REPLACE FUNCTION override.now()
RETURNS timestamp with time zone
AS
$$
BEGIN
RETURN pg_catalog.now() + COALESCE(
  NULLIF(current_setting('timecop.offset_in_seconds', true), '')::integer, 0
) * interval '1 second';
END;
$$
LANGUAGE plpgsql STABLE PARALLEL SAFE STRICT;
SET search_path TO DEFAULT;
SELECT set_config('search_path', 'override,' || current_setting('search_path'), false);

要启用它,我调用

SET timecop.offset_in_seconds = 3600 -- 1 hour ahead

要禁用它,我调用

RESET timecop.offset_in_seconds


问题是,Postgres不知何故没有使用这个函数:

app_test=# select now();
              now
-------------------------------
 2022-12-04 10:22:26.824469+00
(1 row)

app_test=# SET timecop.offset_in_seconds = 3600;
SET
app_test=# select now();
              now
-------------------------------
 2022-12-04 10:22:34.481502+00
(1 row)

查看now()方法本身,我发现搜索路径在pg_catalog中搜索override模式之前:

app_test=# \df+ now
                                                                                        List of functions
   Schema   | Name |     Result data type     | Argument data types | Type | Volatility | Parallel |  Owner   | Security | Access privileges | Language | Source code |       Description
------------+------+--------------------------+---------------------+------+------------+----------+----------+----------+-------------------+----------+-------------+--------------------------
 pg_catalog | now  | timestamp with time zone |                     | func | stable     | safe     | postgres | invoker  |                   | internal | now         | current transaction time

那么,如何将已覆盖的now()移到pg_catalog之前呢?

bq8i3lrv

bq8i3lrv1#

pg_catalog * 总是 * 在搜索路径上,但您可以选择不在开始时使用它:

SET search_path = override, pg_catalog;

相关问题