aboutsummaryrefslogtreecommitdiffstats
path: root/atuin-server-postgres/migrations/20220419082412_add_count_trigger.sql
diff options
context:
space:
mode:
authorEllie Huxtable <ellie@elliehuxtable.com>2024-04-18 16:41:28 +0100
committerGitHub <noreply@github.com>2024-04-18 16:41:28 +0100
commit95cc472037fcb3207b510e67f1a44af4e2a2cae9 (patch)
treefc1d3e71d8e0bdb806370e4144fd6f373bcc9c5e /atuin-server-postgres/migrations/20220419082412_add_count_trigger.sql
parentfeat: show preview auto (#1804) (diff)
downloadatuin-95cc472037fcb3207b510e67f1a44af4e2a2cae9.zip
chore: move crates into crates/ dir (#1958)
I'd like to tidy up the root a little, and it's nice to have all the rust crates in one place
Diffstat (limited to 'atuin-server-postgres/migrations/20220419082412_add_count_trigger.sql')
-rw-r--r--atuin-server-postgres/migrations/20220419082412_add_count_trigger.sql51
1 files changed, 0 insertions, 51 deletions
diff --git a/atuin-server-postgres/migrations/20220419082412_add_count_trigger.sql b/atuin-server-postgres/migrations/20220419082412_add_count_trigger.sql
deleted file mode 100644
index dd1afa88..00000000
--- a/atuin-server-postgres/migrations/20220419082412_add_count_trigger.sql
+++ /dev/null
@@ -1,51 +0,0 @@
--- Prior to this, the count endpoint was super naive and just ran COUNT(1).
--- This is slow asf. Now that we have an amount of actual traffic,
--- stop doing that!
--- This basically maintains a count, so we can read ONE row, instead of ALL the
--- rows. Much better.
--- Future optimisation could use some sort of cache so we don't even need to hit
--- postgres at all.
-
-create table total_history_count_user(
- id bigserial primary key,
- user_id bigserial,
- total integer -- try and avoid using keywords - hence total, not count
-);
-
-create or replace function user_history_count()
-returns trigger as
-$func$
-begin
- if (TG_OP='INSERT') then
- update total_history_count_user set total = total + 1 where user_id = new.user_id;
-
- if not found then
- insert into total_history_count_user(user_id, total)
- values (
- new.user_id,
- (select count(1) from history where user_id = new.user_id)
- );
- end if;
-
- elsif (TG_OP='DELETE') then
- update total_history_count_user set total = total - 1 where user_id = new.user_id;
-
- if not found then
- insert into total_history_count_user(user_id, total)
- values (
- new.user_id,
- (select count(1) from history where user_id = new.user_id)
- );
- end if;
- end if;
-
- return NEW; -- this is actually ignored for an after trigger, but oh well
-end;
-$func$
-language plpgsql volatile -- pldfplplpflh
-cost 100; -- default value
-
-create trigger tg_user_history_count
- after insert or delete on history
- for each row
- execute procedure user_history_count();