-- Facts-Split-Undo-RM9.sql
/* 
2012-12-21 Tom Holden ve3meo
2023-03-08 rev for RM9
Reverses the changes made by Facts-SplitSharedToIndiv-RM9.sql
Requires tables zTmpShareSplit and WitnessTableSafe from the Split query

Deletes the new Indiv Share, Census and Residence events and 
related citations, media tags and webtags
and restores the Sharings. Cleans out the not-in-database sharers 
appended to the original fact.

Requires sqlite manager with support for REGEXP_REPLACE() function.
*/

DELETE FROM EventTable WHERE EventID > (SELECT Maxrowid FROM zTmpShareSplit WHERE TableName LIKE 'EventTable');
DELETE FROM CitationTable WHERE CitationID > (SELECT Maxrowid FROM zTmpShareSplit WHERE TableName LIKE 'CitationTable'); 
DELETE FROM CitationLinkTable WHERE LinkID > (SELECT Maxrowid FROM zTmpShareSplit WHERE TableName LIKE 'CitationLinkTable'); 
DELETE FROM MediaLinkTable WHERE LinkID > (SELECT Maxrowid FROM zTmpShareSplit WHERE TableName LIKE 'MediaLinkTable'); 
DELETE FROM URLTable WHERE LinkID > (SELECT Maxrowid FROM zTmpShareSplit WHERE TableName LIKE 'URLTable'); 
-- To restore the Sharings:
INSERT OR REPLACE INTO WitnessTable
SELECT * FROM WitnessTableSafe
;

-- Clean Event Notes of the not-in-database 'sharers'
UPDATE EventTable
SET Note =
  REGEXP_REPLACE(Note,'\{\*\*[^\{]+\*\*\}','')
WHERE Note LIKE '%{**%'
;