如何跟踪对 Postgresql 数据库中变量的更改?

How do I track changes to a variable in Postgresql database?

我有一个 postgresql table,用于存储电子商务商店中多种产品的库存。当客户购买 (return) 件商品时,每件商品的库存都会减少(增加)以反映交易。

我正在尝试编写一个分析工具来显示项目何时更改以及数量变化 - 本质上是该特定库存项目的时间序列。

有人可以指点资源来帮助我吗?

谢谢。

不,您会在 table 中添加触发器。假设你有一个 inventory table 和一个 history table:

create table inventory (id serial primary key, product_id int, quantity int);
create table history (id serial primary key, event_time timestamp not null default now(), product int, delta int);

您可以创建触发器函数和对应的触发器:

edb=# CREATE OR REPLACE FUNCTION update_history() RETURNS trigger AS 
$$
BEGIN
  IF (TG_OP = 'UPDATE') THEN
    INSERT INTO history (product, delta) VALUES (OLD.product_id, NEW.quantity - OLD.quantity);
  RETURN NULL;
  END IF;
  IF (TG_OP = 'INSERT') THEN
    INSERT INTO history (product, delta) VALUES (NEW.product_id, NEW.quantity);
  RETURN NULL;
  END IF;
END
$$
LANGUAGE PLPGSQL;
CREATE FUNCTION
edb=# CREATE TRIGGER trigger_inventory_change
AFTER INSERT OR UPDATE 
ON inventory
FOR EACH ROW EXECUTE PROCEDURE update_history();
CREATE TRIGGER

然后,对于 inventory table 中的每一次更改,您都会将一个事件添加到 history table:

edb=# insert into inventory values (1,1,100);
INSERT 0 1
edb=# select * from history;
 id |        event_time         | product | delta 
----+---------------------------+---------+-------
  2 | 15-NOV-19 00:38:29.204491 |       1 |   100
(1 row)

edb=# insert into inventory values (2,10,100);
INSERT 0 1
edb=# select * from history;
 id |        event_time         | product | delta 
----+---------------------------+---------+-------
  2 | 15-NOV-19 00:38:29.204491 |       1 |   100
  3 | 15-NOV-19 00:38:58.01209  |      10 |   100
(2 rows)
edb=# update inventory set quantity = quantity - 2 where product_id = 1;
UPDATE 1
edb=# update inventory set quantity = quantity - 20 where product_id = 10;
UPDATE 1
edb=# update inventory set quantity = quantity + 20 where product_id = 1;
UPDATE 1
edb=# select * from history
edb-# ;
 id |        event_time         | product | delta 
----+---------------------------+---------+-------
  1 | 15-NOV-19 00:38:29.204491 |       1 |   100
  2 | 15-NOV-19 00:38:58.01209  |      10 |   100
  3 | 15-NOV-19 00:40:01.121778 |       1 |    -2
  4 | 15-NOV-19 00:40:09.403276 |      10 |   -20
  5 | 15-NOV-19 00:40:17.425085 |       1 |    20
(5 rows)

我没有添加 DELETE 发生的情况,但这是相同的想法