-
-
Notifications
You must be signed in to change notification settings - Fork 588
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
43 additions
and
0 deletions.
There are no files selected for viewing
43 changes: 43 additions & 0 deletions
43
crates/atuin-server-postgres/migrations/20240614104159_idx-cache.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,43 @@ | ||
-- using group by and max is slow. as the store grows, latency is creeping up. | ||
-- get a handle on it! | ||
-- Really this sort of workload (lots of aggregation) is better suited to OLAP, | ||
-- but let's just stick with postgres until we can't any more | ||
|
||
create table store_idx_cache( | ||
id bigserial primary key, | ||
user_id bigint, | ||
|
||
host uuid, | ||
tag text, | ||
idx bigint | ||
); | ||
|
||
|
||
create or replace function cache_store_idx() | ||
returns trigger as | ||
$func$ | ||
begin | ||
if (TG_OP='INSERT') then | ||
update store_idx_cache set idx = (select max(idx) from store where user_id=new.user_id and host=new.host and tag=new.tag) where user_id=new.user_id and host=new.host and tag=new.tag; | ||
|
||
if not found then | ||
insert into store_idx_cache(user_id, host, tag, idx) | ||
values ( | ||
new.user_id, | ||
new.host, | ||
new.tag, | ||
(select max(idx) from store where user_id = new.user_id and host=new.host and tag=new.tag) | ||
); | ||
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 or replace trigger tg_cache_store_idx | ||
after insert on store | ||
for each row | ||
execute procedure cache_store_idx(); |