Skip to content
This repository has been archived by the owner on Feb 8, 2018. It is now read-only.

Commit

Permalink
Move migration into a transaction; #141
Browse files Browse the repository at this point in the history
This dodges a race condition where we could fail to log some goal
changes.
  • Loading branch information
chadwhitacre committed Apr 3, 2013
1 parent b67c222 commit ebb1c83
Showing 1 changed file with 31 additions and 26 deletions.
57 changes: 31 additions & 26 deletions schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -367,29 +367,34 @@ CREATE TABLE goals
, goal numeric(35,2) DEFAULT NULL
);

-- Migrate data from goal column of participants over to new goals table.
INSERT INTO goals (ctime, mtime, participant, goal)
SELECT CURRENT_TIMESTAMP
, CURRENT_TIMESTAMP
, id
, goal
FROM participants
WHERE goal IS NOT null;

-- Create a rule to log changes to participant.goal into goals.
CREATE RULE log_goal_changes
AS ON UPDATE TO participants
WHERE (OLD.goal IS NULL AND NOT NEW.goal IS NULL)
OR (NEW.goal IS NULL AND NOT OLD.goal IS NULL)
OR NEW.goal <> OLD.goal
DO
INSERT INTO goals
(ctime, participant, goal)
VALUES ( COALESCE (( SELECT ctime
FROM goals
WHERE participant=OLD.id
LIMIT 1
), CURRENT_TIMESTAMP)
, OLD.id
, NEW.goal
);

BEGIN;

-- Migrate data from goal column of participants over to new goals table.
INSERT INTO goals (ctime, mtime, participant, goal)
SELECT CURRENT_TIMESTAMP
, CURRENT_TIMESTAMP
, id
, goal
FROM participants
WHERE goal IS NOT NULL;

-- Create a rule to log changes to participant.goal into goals.
CREATE RULE log_goal_changes
AS ON UPDATE TO participants
WHERE (OLD.goal IS NULL AND NOT NEW.goal IS NULL)
OR (NEW.goal IS NULL AND NOT OLD.goal IS NULL)
OR NEW.goal <> OLD.goal
DO
INSERT INTO goals
(ctime, participant, goal)
VALUES ( COALESCE (( SELECT ctime
FROM goals
WHERE participant=OLD.id
LIMIT 1
), CURRENT_TIMESTAMP)
, OLD.id
, NEW.goal
);

END;

0 comments on commit ebb1c83

Please sign in to comment.