例如,如何进行以下不可变交易:
+------+-------+-------+----------+--------+
| From | To | Price | Quantity | Item |
+------+-------+-------+----------+--------+
| Tom | Sam | 10 | 2 | Book |
+------+-------+-------+----------+--------+
| Sam | Jerry | 2 | 1 | Pen |
+------+-------+-------+----------+--------+
| Bill | Sam | 1 | 3 | Pencil |
+------+-------+-------+----------+--------+
| Matt | Sam | 1.5 | 4 | Pencil |
+------+-------+-------+----------+--------+
进入快照并更新视图,而不是在每次添加新事务时重新计算视图:
+-------+--------+----------+---------------+
| Name | Item | Quantity | Average Price |
+-------+--------+----------+---------------+
| Tom | Book | -2 | 10 |
+-------+--------+----------+---------------+
| Sam | Book | 2 | 10 |
+-------+--------+----------+---------------+
| Sam | Pen | -1 | 2 |
+-------+--------+----------+---------------+
| Jerry | Pen | 1 | 2 |
+-------+--------+----------+---------------+
| Sam | Pencil | 7 | 1.29 |
+-------+--------+----------+---------------+
| Bill | Pencil | -3 | 1 |
+-------+--------+----------+---------------+
| Matt | Pencil | -4 | 1.5 |
+-------+--------+----------+---------------+
目标是在数据库中生成快照并在应用程序中使用快照,而不是在应用程序本身中生成快照。这主要是为了保持事务和快照之间的一致性。
通过一些研究,解决方案可能涉及使用LISTEN
,NOTIFY
,TRIGGER
和VIEW
。我使用的是PostgreSQL 10,可以选择使用TimescaleDB。