Skip to content

Commit c128a4b

Browse files
committed
Automatically insert crate_downloads row on crates table insert
1 parent a6e4588 commit c128a4b

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
1+
drop trigger insert_crate_downloads_row on crates;
2+
drop function insert_crate_downloads_row;
13
drop table crate_downloads;

migrations/2024-03-04-092044_crate-downloads-table/up.sql

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
-- Create the `crate_downloads` table.
2+
13
create table crate_downloads
24
(
35
crate_id integer not null
@@ -13,6 +15,21 @@ comment on table crate_downloads is 'Number of downloads per crate. This was ext
1315
comment on column crate_downloads.crate_id is 'Reference to the crate that this row belongs to.';
1416
comment on column crate_downloads.downloads is 'The total number of downloads for this crate.';
1517

18+
-- Create a trigger to automatically add a row to `crate_downloads` when a new
19+
-- crate is inserted into the `crates` table.
20+
21+
create or replace function insert_crate_downloads_row() returns trigger as $$
22+
begin
23+
insert into crate_downloads(crate_id) values (new.id);
24+
return new;
25+
end;
26+
$$ language plpgsql;
27+
28+
create trigger insert_crate_downloads_row
29+
after insert on crates
30+
for each row
31+
execute function insert_crate_downloads_row();
32+
1633
-- The following query can take a couple of seconds so it should be run manually
1734
-- outside of the migration to prevent the server from taking a long time to
1835
-- start up while waiting for the migration to complete.

0 commit comments

Comments
 (0)