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

Commit

Permalink
cache a user's takes in a new column of the participants table
Browse files Browse the repository at this point in the history
  • Loading branch information
Changaco committed Jun 14, 2014
1 parent 0e1aa9e commit b7aa3d1
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions branch.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
BEGIN;

ALTER TABLE participants ADD COLUMN takes numeric(35,2) NOT NULL DEFAULT 0;

This comment has been minimized.

Copy link
@chadwhitacre

chadwhitacre Jun 16, 2014

Contributor

Everything after this line is a one-off, right? Is the process_take function something we need to keep around in the db? If not, do we need to delete it here?

This comment has been minimized.

Copy link
@Changaco

Changaco Jun 16, 2014

Author Contributor

Yes it's a one-off, and yes I guess we should delete process_take.


CREATE TEMPORARY TABLE temp_teams AS
SELECT username, receiving
FROM participants
WHERE "number" = 'plural';

CREATE TEMPORARY TABLE temp_takes
( team text
, member text
, amount numeric(35,2)
);

CREATE FUNCTION process_take() RETURNS trigger AS $$
DECLARE
actual_amount numeric(35,2);
team_balance numeric(35,2);
BEGIN
team_balance := (
SELECT receiving
FROM temp_teams
WHERE username = NEW.team
);
actual_amount := NEW.amount;
IF (team_balance < NEW.amount) THEN
actual_amount := team_balance;
END IF;
UPDATE participants
SET takes = (takes + actual_amount)
, receiving = (receiving + actual_amount)
WHERE username = NEW.member;
UPDATE temp_teams
SET receiving = (receiving - actual_amount)

This comment has been minimized.

Copy link
@chadwhitacre

chadwhitacre Jun 17, 2014

Contributor

So team receiving amount is going to be reported less the amount that members are taking?

This comment has been minimized.

Copy link
@Changaco

Changaco Jun 17, 2014

Author Contributor

@whit537 No, that's just a temporary table, the real receiving in the participants table isn't modified.

This comment has been minimized.

Copy link
@chadwhitacre

chadwhitacre Jun 17, 2014

Contributor

Okay, cool.

WHERE username = NEW.team;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER process_take AFTER INSERT ON temp_takes
FOR EACH ROW EXECUTE PROCEDURE process_take();

INSERT INTO temp_takes
SELECT team, member, amount
FROM current_takes t
WHERE t.amount > 0
ORDER BY ctime DESC;

END;

1 comment on commit b7aa3d1

@chadwhitacre
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm good w/ this commit.

Please sign in to comment.