To implement a partially versioned table in PostgreSQL, where some columns (e.g., name and image) are versioned to track changes over time, while others (e.g., id and last_connect_date) are not versioned and only store the current value, you can use a combination of a main table for the current state and a history table for tracking changes to the versioned columns. This is typically achieved using triggers to automatically log changes.
Here's a step-by-step guide to implement this correctly in PostgreSQL:
1. Design the Tables
- Create a main table to store the current state of all columns. This table will be updated directly for any changes.
- Create a history table to store past versions of only the versioned columns (e.g.,
name and image). This avoids redundancy by not storing non-versioned columns in the history unless they are needed for context.
Example SQL:
-- Main table: stores the current state of all columns
CREATE TABLE users (
id SERIAL PRIMARY KEY, -- Non-versioned, auto-incrementing ID
last_connect_date TIMESTAMP, -- Non-versioned, only current value is stored
name TEXT, -- Versioned, changes are tracked
image TEXT -- Versioned, changes are tracked
);
-- History table: stores past versions of only the versioned columns
CREATE TABLE users_history (
history_id BIGSERIAL PRIMARY KEY, -- Surrogate key for the history table
user_id INTEGER REFERENCES users(id),-- Foreign key referencing the main table's ID
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Timestamp of the change
name TEXT, -- Versioned column
image TEXT -- Versioned column
);
- Rationale for table design:
- The
users table holds the current state, so queries for the latest data are fast and direct.
- The
users_history table only includes the versioned columns (name and image) to minimize storage overhead. The changed_at column records when the change occurred, and user_id links back to the main table for easy joining.
2. Create a Trigger Function
- Use a PL/pgSQL function to handle the logic for inserting rows into the history table. This function will be triggered on
INSERT and UPDATE operations on the main table.
- The function should:
- On
INSERT, optionally record the initial state of the versioned columns in the history table (to capture the starting point).
- On
UPDATE, check if any versioned columns have changed and, if so, insert the old values into the history table.
- Use the
IS DISTINCT FROM operator to handle changes correctly, as it accounts for NULL values (unlike <>, which can produce unexpected results with NULL).
Example SQL:
-- Trigger function to handle versioning
CREATE OR REPLACE FUNCTION users_versioning_trigger()
RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
-- Optionally insert the initial state into history (recommended to capture the starting point)
INSERT INTO users_history (user_id, name, image)
VALUES (NEW.id, NEW.name, NEW.image);
RETURN NEW;
ELSIF TG_OP = 'UPDATE' THEN
-- Check if any versioned columns have changed
IF NEW.name IS DISTINCT FROM OLD.name OR NEW.image IS DISTINCT FROM OLD.image THEN
-- Insert the old values into history
INSERT INTO users_history (user_id, name, image)
VALUES (OLD.id, OLD.name, OLD.image);
END IF;
RETURN NEW;
END IF;
RETURN NULL; -- This line is not reached but is good practice for completeness
END;
$$ LANGUAGE plpgsql;
- Notes on the trigger function:
- The
INSERT part is optional but recommended if you want the initial state to be part of the history. If you omit it, the history will only start recording changes from the first update.
- The
UPDATE part only inserts a history row if name or image changes, ensuring that updates to non-versioned columns (e.g., last_connect_date) do not create unnecessary history entries.
3. Create Triggers
- Attach the trigger function to the main table for
INSERT and UPDATE operations. You can use a single trigger that handles both operations or separate triggers for clarity.
Example SQL:
-- Trigger for INSERT and UPDATE operations
CREATE TRIGGER users_versioning_trigger
AFTER INSERT OR UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION users_versioning_trigger();
- Trigger timing: Use
AFTER instead of BEFORE to ensure the row is inserted or updated in the main table first, so NEW and OLD refer to the correct values.
4. Handle Edge Cases
- Deletion: If you need to track deletions (e.g., record when a row is deleted), you can extend the trigger function to handle
DELETE operations by inserting a row into the history table with a flag (e.g., add a operation column like 'DELETE'). However, this is not specified in your query, so it's omitted here.
- NULL Handling: The
IS DISTINCT FROM operator ensures correct behavior when columns are NULL.
- Performance Considerations: Triggers add overhead, so test with your expected load. If high performance is critical, consider indexing the
user_id and changed_at columns in the history table for faster queries.
- Querying the Data:
- To get the current state: Query the
users table directly.
- To get the history of versioned columns: Query the
users_history table, e.g.,
SELECT * FROM users_history WHERE user_id = ? ORDER BY changed_at DESC;
- To get the state at a specific point in time: You may need to join with the main table or use a subquery to find the most recent history row before a given timestamp. For example:
SELECT uh.name, uh.image, u.last_connect_date AS current_last_connect_date
FROM users_history uh
JOIN users u ON uh.user_id = u.id
WHERE uh.user_id = ? AND uh.changed_at <= '2023-10-01 00:00:00'
ORDER BY uh.changed_at DESC
LIMIT 1;
Note that the non-versioned column (last_connect_date) is taken from the current main table, as its history is not tracked.
5. Advantages and Considerations
- Advantages:
- Simple and flexible implementation using standard PostgreSQL features (no extensions required).
- Only versioned columns are stored in history, reducing storage costs.
- Easy to query current and historical data separately.
- Considerations:
- If you update a non-versioned column (e.g.,
last_connect_date) alongside a versioned column in the same transaction, the history will only capture the change for the versioned columns.
- If you need full temporal querying (e.g., the state of all columns at any point in time), this approach might not be sufficient, as non-versioned columns are not historized. In that case, consider PostgreSQL's built-in temporal features (available in PostgreSQL 14+) or extensions like
pg_temp for more advanced temporal support.
- Test the setup with sample data to ensure the triggers work as expected, especially with edge cases like NULL values or concurrent updates.
This approach ensures that only the specified columns (name and image) are versioned, while id and last_connect_date remain non-versioned and are only updated in the main table. If you have additional requirements (e.g., versioning on delete or more complex querying), you can extend this setup accordingly.