-
Notifications
You must be signed in to change notification settings - Fork 38
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
src/server/db_migrations/20201207_synchronise_url_clicks.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
-- This SQL file is used to populate the url_clicks table with data from the | ||
-- url_table, and also add the necessary hooks such that they will always be | ||
-- in sync. These include 1) when a url_table row's click is changed, and | ||
-- 2) when a new url_table row is created. | ||
BEGIN TRANSACTION; | ||
|
||
INSERT INTO "url_clicks" ("shortUrl", "clicks", "createdAt", "updatedAt") | ||
SELECT "shortUrl", "clicks", "createdAt", "updatedAt" from urls; | ||
|
||
CREATE OR REPLACE FUNCTION update_clicks() | ||
RETURNS TRIGGER AS $$ | ||
BEGIN | ||
UPDATE url_clicks | ||
SET "clicks" = NEW."clicks" | ||
WHERE url_clicks."shortUrl" = NEW."shortUrl"; | ||
RETURN NEW; | ||
END; $$ LANGUAGE PLPGSQL; | ||
|
||
CREATE TRIGGER url_table_click_incremented | ||
AFTER UPDATE of "clicks" on urls | ||
FOR EACH ROW | ||
WHEN (OLD."clicks" <> NEW."clicks") | ||
EXECUTE PROCEDURE update_clicks(); | ||
|
||
CREATE OR REPLACE FUNCTION create_clicks() | ||
RETURNS TRIGGER AS $$ | ||
BEGIN | ||
INSERT INTO url_clicks ("shortUrl", "clicks", "createdAt", "updatedAt") | ||
VALUES (NEW."shortUrl", NEW."clicks", NEW."createdAt", NEW."updatedAt"); | ||
RETURN NEW; | ||
END; $$ LANGUAGE PLPGSQL; | ||
|
||
CREATE TRIGGER url_created | ||
AFTER INSERT on urls | ||
FOR EACH ROW | ||
EXECUTE PROCEDURE create_clicks(); | ||
|
||
COMMIT; |