I was successful in implementing a table's history (for auditing) based on this answer that basically suggests to create two tables wherein one contains the current version and the other a table of versions with the real data:
CREATE TABLE dbo.Page(
ID int PRIMARY KEY,
Name nvarchar(200) NOT NULL,
CreatedByName nvarchar(100) NOT NULL,
CurrentRevision int NOT NULL,
CreatedDateTime datetime NOT NULL
CREATE TABLE dbo.PageContent(
PageID int NOT NULL,
Revision int NOT NULL,
Title nvarchar(200) NOT NULL,
User nvarchar(100) NOT NULL,
LastModified datetime NOT NULL,
Comment nvarchar(300) NULL,
Content nvarchar(max) NOT NULL,
Description nvarchar(200) NULL
My UPDATE
s to static, non-dynamic fields are OK where the versioning is recognised correctly (rough pseudocode adapted from dev't code):
$sql_pagecontent = array(
'PageID' => // logic to get PageID
'Title' => $data['Title']
'User' => $data['User'],
'LastModified' => $this->get_date(),
'Comment' => $data['Comment'],
'Content' => $data['Content'],
'Description' => $data['Description']
);
$this->db->insert('PageContent', $sql_pagecontent);
$id_version = $this->db->insert_id();
$sql_page = array(
'CurrentRevision' => $id_version
);
if($type_version === 'UPDATE')
{
$this->db->where('ID', $page_id_to_replace);
$this->db->update('Page', $sql_page);
}
else
{
$this->db->insert('Page', $sql_page);
}
The problem is when I apply this to dynamic tables with UPDATE
.
During UPDATE
, I want to achieve the following, just similar to the non-dynamic tables (context of Page
and PageContent
):
- a new
PageContent
row isINSERT
ed (newPageContent
), a new row ofCurrentRevision
inPage
is added - a new
PageContent
row isINSERT
ed (update of existingPageContent
), theCurrentRevision
inPage
UPDATE
d with this new row - deleted
PageContent
s are removed fromPage
NOTE I want each row of these dynamic tables preserved in both Page
and PageContent
if ever the user wants to check the changes so I just cannot do INSERT
which will just flood the table.
I cannot seem to filter these dynamic values correctly with the current implementation.
Please advise on how to deal with this use case.
Solution
I am not sure if my current implementation of my said requirements is correct, feasible or recommended but it does the job:
- get ID of current
PageContent
being modified - get ID of current
Page
being modified - delete all rows of
Page
that has the ID of #1 - perform
INSERT
and applyUPDATE
as type of action ofPageContent
Number 3 is key to make sure whether existing rows are edited/deleted or new rows added are saved as the current version in Page
. Number 4 puts this into place to make sure every row is recognised.