底层函数更改后重新计算 Postgres 生成列中的值

Recompute values in Postgres generated column after underlying function changed

图像 table 生成的列如下:

CREATE OR REPLACE FUNCTION extract_first_name(p_name text) RETURNS text
LANGUAGE SQL IMMUTABLE
AS $$
    SELECT split_part(p_name, ' ', 1);
$$;

CREATE TABLE customers (
    id serial,
    name text,
    first_name text GENERATED ALWAYS AS (extract_first_name(name)) STORED
);

后来有人发现extract_first_name功能过于简单,需要改一下。然后更新,但 first_name 列中的值保持不变。我们如何以最简单和最有效的方式重新计算 first_name 列中的所有值以使用最新版本的函数 w/o 锁定 table?

生成的列是 'computed' 2 个事件。何时插入行以及何时更新基础列。因此,您需要使用 something like

更新每一行
Update customers 
   set name = name; 

这将根据需要更新 table 中的每一行。但由于 Postgres 使用 MVCC 模型,这不会阻止其他人在操作期间进行选择。

The main advantage of using the MVCC model of concurrency control rather than locking is that in MVCC locks acquired for querying (reading) data do not conflict with locks acquired for writing data, and so reading never blocks writing and writing never blocks reading. PostgreSQL maintains this guarantee even when providing the strictest level of transaction isolation through the use of an innovative Serializable Snapshot Isolation (SSI) level.

但是,如果您在此过程中继续允许更新,则需要注意死锁。