场景
我们需要在PostgreSQL中存储记录历史,这样当将记录插入或更新到主表(例如:pets
)时,它会自动备份到历史表格(pets_history
)。
理想情况下,我们需要基于主表的模式生成历史表,而不需要任何人工干预。
INSERT INTO pets(name, species) VALUES ('Meowth', 'Cat')
pets:
+---+------------+-------------+
|id | name | species |
+---+------------+-------------+
| 1 | Meowth | Cat |
+---+------------+-------------+
触发器
应自动将记录插入到pets_history
中:
pets_history:
+----+--------+-----------+---------+
| id | ref_id | name | species |
+----+--------+-----------+---------+
| 1 | 1 | Meowth | Cat |
+----+--------+-----------+---------+
当对宠物进行更新以更改我的猫的名称从 Meowth 更改为
Persian 时。例如:
<code><code>UPDATE pets SET name = 'Persian' WHERE id = 1;
</code></code>
<code><code>pets:
+---+------------+-------------+
|id | name | species |
+---+------------+-------------+
| 1 | Persian | Cat |
+---+------------+-------------+
</code></code>
我希望最终得到以下结果...
<code><code>pets_history:
+----+--------+-----------+---------+
| id | ref_id | name | species |
+----+--------+-----------+---------+
| 1 | 1 | Meowth | Cat |
| 2 | 1 | Persian | Cat |
+----+--------+-----------+---------+
</code></code>
当其他列/字段被添加到
pets
表中时,例如:color
。
<code><code>pets:
+---+--------+---------+-------+
|id | name | species | color |
+---+--------+---------+-------+
| 1 | Meowth | Cat | cream |
+---+--------+---------+-------+
</code></code>
我们希望这可以自动反映在
pets_history
表中:
<code><code>pets_history:
+----+--------+---------+---------+-------+
| id | ref_id | name | species | color |
+----+--------+---------+---------+-------+
| 1 | 1 | Meowth | Cat | null |
| 2 | 1 | Persian | Cat | null |
| 3 | 1 | Persian | Cat | cream |
+----+--------+---------+---------+-------+
</code></code>
如果有人知道如何在PostgreSQL本地或其他方式中实现这一点,请分享。
我们查看了这个问题/答案Implementing history of PostgreSQL table,它部分地解决了这个挑战,但它不会自动创建
_history
表。