{"id":23084750,"url":"https://github.com/andrerav/generatehistorytriggers","last_synced_at":"2026-04-16T10:32:35.424Z","repository":{"id":268391257,"uuid":"904182534","full_name":"andrerav/GenerateHistoryTriggers","owner":"andrerav","description":"A simple tool that will generate SQL for history tables and associated triggers for PostgreSQL based on a simple JSON definition file.","archived":false,"fork":false,"pushed_at":"2024-12-16T12:43:19.000Z","size":16,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-31T08:21:11.271Z","etag":null,"topics":["dotnet","history","postgresql","temporal","versioning"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/andrerav.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-12-16T12:03:59.000Z","updated_at":"2025-03-29T17:25:40.000Z","dependencies_parsed_at":null,"dependency_job_id":"e1d5e5f7-06ec-4c08-9649-cbef55a3c1c1","html_url":"https://github.com/andrerav/GenerateHistoryTriggers","commit_stats":null,"previous_names":["andrerav/generatehistorytriggers"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/andrerav/GenerateHistoryTriggers","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrerav%2FGenerateHistoryTriggers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrerav%2FGenerateHistoryTriggers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrerav%2FGenerateHistoryTriggers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrerav%2FGenerateHistoryTriggers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andrerav","download_url":"https://codeload.github.com/andrerav/GenerateHistoryTriggers/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrerav%2FGenerateHistoryTriggers/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267875624,"owners_count":24158781,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-30T02:00:09.044Z","response_time":70,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dotnet","history","postgresql","temporal","versioning"],"created_at":"2024-12-16T16:43:43.578Z","updated_at":"2026-04-16T10:32:35.389Z","avatar_url":"https://github.com/andrerav.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# GenerateHistoryTriggers\nA simple tool that will generate SQL for history tables and associated triggers for PostgreSQL based on a simple JSON definition file.\n\n## How to use\nEnter the project directory\n```bash\ncd src/GenerateHistoryTriggers\n```\n\nRun the project and specify the input definition file with the `-i` argument:\n\n```bash\ndotnet run -i .\\Input\\Blog.example.json\n```\n\nTo store the output to a file, use an IO redirect:\n\n```bash\ndotnet run -i .\\Input\\Blog.example.json \u003e HistoryTable.sql\n```\n\n## How the code generation works\n\nThe C# program and T4 template use a JSON definition file to generate the history table scripts, triggers, and functions. This file defines the metadata for each table you want to track changes for.\n\n## JSON Structure\n\nThe JSON file is an array of objects, where each object represents the configuration for a table. Below is the structure of each table configuration object:\n\n| Property Name                  | Type     | Description                                                                                                                                       | Required |\n|--------------------------------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------|----------|\n| `TableName`                    | `string` | The name of the table for which history tracking is being configured.                                                                             | Yes      |\n| `SchemaName`                   | `string` | The schema where the main table resides.                                                                                                          | Yes      |\n| `HistorySchemaName`            | `string` | The schema where the corresponding history table will be created. If the schema does not exist, it will be created.                                                                                | Yes      |\n| `PreviousValidToColumnName`    | `string` | The column or expression from the main table to determine the `active_from` timestamp in the history table if it’s the first entry for a row. You can use `NOW()` if there is no such column, but I strongly urge you to add such a column to the table to have a proper audit record of the data.     | Yes      |\n| `PrimaryKeys`                  | `array`  | An array of objects defining the primary key columns of the table.                                                                                | Yes      |\n\n### `PrimaryKeys` Array\n\nEach element in the `PrimaryKeys` array describes a primary key column for the table. The following fields are included:\n\n| Property Name    | Type     | Description                                      | Required |\n|-------------------|----------|--------------------------------------------------|----------|\n| `PrimaryKeyName` | `string` | The name of the primary key column.              | Yes      |\n| `SqlType`        | `string` | The SQL data type of the primary key column.     | Yes      |\n\n## Example JSON\n\nBelow is an example JSON definition file for tracking changes to `posts` and `comments` tables:\n\n```json\n[\n  {\n    \"TableName\": \"posts\",\n    \"SchemaName\": \"public\",\n    \"HistorySchemaName\": \"history_tables\",\n    \"PreviousValidToColumnName\": \"OLD.created_date\",\n    \"PrimaryKeys\": [\n      {\n        \"PrimaryKeyName\": \"id\",\n        \"SqlType\": \"int\"\n      }\n    ]\n  },\n  {\n    \"TableName\": \"comments\",\n    \"SchemaName\": \"public\",\n    \"HistorySchemaName\": \"history_tables\",\n    \"PreviousValidToColumnName\": \"OLD.created_date\",\n    \"PrimaryKeys\": [\n      {\n        \"PrimaryKeyName\": \"id\",\n        \"SqlType\": \"int\"\n      }\n    ]\n  }\n]\n\n```\n\n\n## How the history table logic works\n\n\u003e [!NOTE]\n\u003e This explanation is based on the example definition in the included Blog.example.json definition file. \n\nThe `posts_history` table records historical changes made to the `posts` table, capturing the state of a row before updates or deletions occur. This is accomplished using a combination of a trigger function and a trigger, ensuring that changes are logged automatically.\n\n1. **Trigger Function (`fn_posts_update_history`)**:\n   - This function is invoked whenever an `UPDATE` or `DELETE` operation is performed on the `posts` table.\n   - The function calculates the MD5 hash of the current and previous row data to determine if a change has occurred.\n   - If the row data has changed, the function inserts the previous state of the row into the `posts_history` table.\n   - The function also manages the `revision` numbers and the `active_from`/`active_to` timestamps to maintain a complete history.\n\n2. **Trigger (`trg_posts_on_update`)**:\n   - This trigger is set on the `posts` table.\n   - It invokes the `fn_posts_update_history` function after any `UPDATE` or `DELETE` operation.\n\n### Table Definition: `history_tables.posts_history`\n\nThe `posts_history` table is structured to store the historical states of rows from the `posts` table. Below is a breakdown of its columns:\n\n| Column Name      | Data Type               | Purpose                                                                                          |\n|-------------------|-------------------------|--------------------------------------------------------------------------------------------------|\n| `id`             | `int`                  | The primary key of the row in the `posts` table that this history entry corresponds to.         |\n| `row_data`       | `jsonb`                | A JSONB representation of the row's state at the time of the change.                            |\n| `md5_hash`       | `varchar(32)`          | An MD5 hash of the row's state, used to detect changes in content.                              |\n| `revision`       | `integer`              | The revision number of the row, incremented for each historical entry.                         |\n| `active_from`    | `timestamp with time zone` | The timestamp indicating when this historical state became active.                             |\n| `active_to`      | `timestamp with time zone` | The timestamp indicating when this historical state was replaced by a newer revision (if any). |\n\n### Key Features\n\n- **Automatic Revision Tracking**: The `revision` column increments automatically to track the number of changes made to a row.\n- **Time-Based History**: The `active_from` and `active_to` columns define the time range during which a particular historical state was active.\n- **Change Detection via Hashing**: MD5 hashes of the row data are used to detect changes, ensuring no duplicate entries are created for identical updates.\n- **Comprehensive Auditing**: Both `UPDATE` and `DELETE` operations are logged, enabling complete historical tracking.\n\n### Trigger and Function Logic\n\n#### Trigger Function: `fn_posts_update_history`\n\n- Determines the current revision number for the row in the `posts_history` table.\n- Checks if the content of the row has changed by comparing MD5 hashes.\n- If the row has changed, inserts the previous state into the `posts_history` table with:\n  - The current `revision`.\n  - The appropriate `active_from` and `active_to` timestamps.\n- Returns the updated or deleted row for further processing.\n\n#### Trigger: `trg_posts_on_update`\n\n- Executes the `fn_posts_update_history` function after an `UPDATE` or `DELETE` operation on the `posts` table.\n- Ensures historical tracking is applied consistently to all changes.\n\n## Example Usage\n\n1. **Updating a Post**:\n   - When a post is updated, the trigger captures the previous state and inserts it into the `posts_history` table.\n   - A new revision is created for the current state.\n\n2. **Deleting a Post**:\n   - When a post is deleted, its last known state is recorded in the `posts_history` table with an appropriate `active_to` timestamp.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrerav%2Fgeneratehistorytriggers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandrerav%2Fgeneratehistorytriggers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrerav%2Fgeneratehistorytriggers/lists"}