temporal_tables (temporal tables)
PolarDB for PostgreSQL (Compatible with Oracle) supports the temporal_tables extension, which implements the system-period temporal table feature. When a row is inserted into a data table, the system automatically generates the start value and end value of the period. When a row in the data table is updated or deleted, the old row is archived to another table, which is called a history table, namely the temporal table described in this topic.
Prerequisites
The supported versions of PolarDB for PostgreSQL (Compatible with Oracle) are as follows:
Oracle syntax compatibility 2.0 (minor version 2.0.14.25.0 and later)
You can use the following statement to view the minor version of PolarDB for PostgreSQL (Compatible with Oracle):
SHOW polar_version;Usage
Install the extension
CREATE EXTENSION temporal_tables;Create a system-period temporal table
The temporal_tables extension uses a generic trigger function to maintain the behavior of system-period temporal tables:
versioning(<system_period_column_name>, <history_table_name>, <adjust>)This function must be triggered before INSERT, UPDATE, or DELETE on a system-period temporal table. The following parameters must be specified:
Parameter | Description |
system_period_column_name | The name of the system period column. |
history_table_name | The name of the history table. |
adjust | When a row is inserted into a data table, the system automatically generates the start value and end value of the period. This parameter is used to check whether the end value of the period is greater than the start value. Valid values:
|
Example
Prepare the basic data and create the employees table:
CREATE TABLE employees ( name text NOT NULL PRIMARY KEY, department text, salary numeric(20, 2) );Modify the employees table into a system-period temporal table and add a system period column:
ALTER TABLE employees ADD COLUMN sys_period tstzrange NOT NULL;Create a history table that contains the archived rows of the table. The simplest way to create it is to use the
LIKEstatement:CREATE TABLE employees_history (LIKE employees);NoteThe history table does not need to have the same structure as the original table. For example, you may want to archive some columns of the original rows while ignoring other columns, or the history table may contain some useful information that is not needed in the original table. The two requirements that the history table must meet are as follows:
The history table must contain a system period column with the same name and data type as that in the original table.
If the history table and the original table both contain a column that you want to archive, the data type of the column must be the same in the two tables.
Create a trigger on the employees table to associate it with the history table.
CREATE TRIGGER versioning_trigger BEFORE INSERT OR UPDATE OR DELETE ON employees FOR EACH ROW EXECUTE PROCEDURE versioning('sys_period', 'employees_history', true);
Insert data
Inserting data into a system-period temporal table is similar to inserting data into a regular table.
Example
Insert the following data into the employees table on August 8, 2006:
INSERT INTO employees (name, department, salary) VALUES ('Bernard Marx', 'Hatchery and Conditioning Centre', 10000); INSERT INTO employees (name, department, salary) VALUES ('Lenina Crowne', 'Hatchery and Conditioning Centre', 7000); INSERT INTO employees (name, department, salary) VALUES ('Helmholtz Watson', 'College of Emotional Engineering', 18500);Query the data in the employees table and its history table.
employees table:
SELECT * FROM employees;The following result is returned:
name | department | salary | sys_period -----------------+----------------------------------+----------+----------------------------- Bernard Marx | Hatchery and Conditioning Centre | 10000.00 | ["2006-08-08 00:00:00+00",) Lenina Crowne | Hatchery and Conditioning Centre | 7000.00 | ["2006-08-08 00:00:00+00",) Helmholtz Watson | College of Emotional Engineering | 18500.00 | ["2006-08-08 00:00:00+00",) (3 rows)History table employees_history:
SELECT * FROM employees_history;The following result is returned. The table data is empty:
name | department | salary | sys_period ------+------------+--------+------------ (0 rows)
The start time of the sys_period column indicates the time when the row became current. The trigger generates this value by using the CURRENT_TIMESTAMP value, which indicates the time when the first data change statement was executed in the current transaction.
Update data
When the column values of a row in a system-period temporal table are updated, the trigger inserts a copy of the old row into the associated history table. If a single transaction updates the same row multiple times, only one history row is generated.
Example
Update the following data in the employees table on February 27, 2007:
UPDATE employees SET salary = 11200 WHERE name = 'Bernard Marx';Query the data in the employees table and its history table.
employees table:
SELECT * FROM employees;The following result is returned:
name | department | salary | sys_period ------------------+----------------------------------+----------+----------------------------- Lenina Crowne | Hatchery and Conditioning Centre | 7000.00 | ["2006-08-08 00:00:00+00",) Helmholtz Watson | College of Emotional Engineering | 18500.00 | ["2006-08-08 00:00:00+00",) Bernard Marx | Hatchery and Conditioning Centre | 11200.00 | ["2007-02-27 00:00:00+00",) (3 rows)History table employees_history:
SELECT * FROM employees_history;The following result is returned, which shows the updated records of the employees table:
name | department | salary | sys_period --------------+----------------------------------+----------+----------------------------------------------------- Bernard Marx | Hatchery and Conditioning Centre | 10000.00 | ["2006-08-08 00:00:00+00","2007-02-27 00:00:00+00") (1 row)
Update conflicts and time adjustment
When multiple transactions update the same row, an update conflict may occur. For example, transactions A and B execute statements on the employees table at the same time:
Time | Transaction A | Transaction B |
T1 | INSERT INTO employees (name, salary) VALUES ('Bernard Marx', 10000); | |
T2 | INSERT INTO employees (name, salary) VALUES ('Lenina Crowne', 7000); | |
T3 | COMMIT; | |
T4 | UPDATE employees SET salary = 6800 WHERE name = 'Lenina Crowne'; | |
T5 | INSERT INTO employees (name, salary) VALUES ('Helmholtz Watson', 18500); | |
T6 | COMMIT; |
After the insertions at T1 and T2, the system-period temporal table employees contains the following data:
name | department | salary | sys_period |
Bernard Marx | Hatchery and Conditioning Centre | 10000 | [T1, ) |
Lenina Crowne | Hatchery and Conditioning Centre | 7000 | [T2, ) |
The history table employees_history is empty. At T4, the trigger must set the start of the sys_period column of the row to T1 and insert the following row into the history table:
name | department | salary | sys_period |
Lenina Crowne | Hatchery and Conditioning Centre | 7000 | [T2, T1) |
However, T2 > T1, so the row cannot be inserted. In this case, the update at T4 fails with SQL STATE 22000. To avoid this failure, you can set the "adjust" parameter of the trigger to true. Then, at T4, the start time of the sys_period column is set to T2 plus a small time interval (usually 1 microsecond). After this adjustment and the completion of transaction A, the employees table is as follows:
name | department | salary | sys_period |
Bernard Marx | Hatchery and Conditioning Centre | 10000 | [T1, ) |
Lenina Crowne | Hatchery and Conditioning Centre | 6800 | [T2 + delta, ) |
Helmholtz Watson | College of Emotional Engineering | 18500 | [T1, ) |
The history table employees_history contains the following data:
name | department | salary | sys_period |
Lenina Crowne | Hatchery and Conditioning Centre | 7000 | [T2, T2 + delta) |
Delete data
When data is deleted from a system-period temporal table, the trigger adds the row to the associated history table.
Example
Delete the following data from the employees table on December 24, 2012:
DELETE FROM employees WHERE name = 'Helmholtz Watson';Query the data in the employees table and its history table.
employees table:
SELECT * FROM employees;The following result is returned:
name | department | salary | sys_period ---------------+----------------------------------+----------+----------------------------- Lenina Crowne | Hatchery and Conditioning Centre | 7000.00 | ["2006-08-08 00:00:00+00",) Bernard Marx | Hatchery and Conditioning Centre | 11200.00 | ["2007-02-27 00:00:00+00",) (2 rows)History table employees_history:
SELECT * FROM employees_history;The following result is returned, which shows the updated records of the employees table:
name | department | salary | sys_period ------------------+----------------------------------+----------+----------------------------------------------------- Bernard Marx | Hatchery and Conditioning Centre | 10000.00 | ["2006-08-08 00:00:00+00","2007-02-27 00:00:00+00") Helmholtz Watson | College of Emotional Engineering | 18500.00 | ["2006-08-08 00:00:00+00","2012-12-24 00:00:00+00") (2 rows)
Advanced usage
In addition to using CURRENT_TIMESTAMP, you can set a custom system time for the versioning trigger. This is useful for creating a data warehouse based on data recorded with the system time.
SELECT set_system_time('1985-08-08 06:42:00+08');To restore the default behavior, you can call this function with NULL as the parameter.
SELECT set_system_time(NULL);If the set_system_time function is executed within a transaction and the transaction is later aborted, all changes are reverted. If the transaction is committed, the changes persist until the end of the session.
Create a system-period temporal table by using inheritance
In the previous Example, the LIKE statement is used to create the history table. Sometimes it is better to use inheritance. For example:
CREATE TABLE employees_history
(
name text NOT NULL,
department text,
salary numeric(20, 2),
sys_period tstzrange NOT NULL
);Then create the system-period temporal table:
CREATE TABLE employees (PRIMARY KEY(name)) INHERITS (employees_history);Maintain the history table
The history table is always growing and therefore consumes more and more storage space. You can use the following methods to maintain the history table space.
Delete old data from the history table:
Periodically delete old data from the history table.
Use partitions and detach old partitions from the history table.
Rules for maintaining old rows:
Delete rows older than a certain age.
Keep only the latest N versions of a row.
Delete the corresponding rows in the history table when the corresponding rows are deleted from the system-period temporal table.
Delete rows that meet specified business rules.
Set another tablespace for the history table to move it to other storage. For more information, see Cold data tiered storage.
Use system-period temporal tables for data auditing
You can use system-period temporal tables for data auditing. For example, you can add the following triggers to save the user who modified or deleted the current row:
CREATE FUNCTION employees_modify()
RETURNS TRIGGER AS $$
BEGIN
NEW.user_modified = SESSION_USER;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER employees_modify
BEFORE INSERT OR UPDATE ON employees
FOR EACH ROW EXECUTE PROCEDURE employees_modify();
CREATE FUNCTION employees_delete()
RETURNS TRIGGER AS $$
BEGIN
NEW.user_deleted = SESSION_USER;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER employees_delete
BEFORE INSERT ON employees_history
FOR EACH ROW EXECUTE PROCEDURE employees_delete();References
For detailed descriptions of temporal_tables, see temporal_tables.