Created
November 6, 2021 18:35
-
-
Save motoroller95/4b19bd11e8824c99b905306c235d013a to your computer and use it in GitHub Desktop.
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
create table gifts_partitioned ( | |
id integer not null default nextval('gifts_id_seq'::regclass), | |
; ... | |
finished boolean not null default false, | |
; ... | |
PRIMARY KEY(id, finished) | |
) | |
partition by list(finished); | |
create table gifts_unfinished | |
partition of gifts_partitioned for values in (false); | |
create table gifts_finished | |
partition of gifts_partitioned for values in (true); |
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
CREATE OR REPLACE FUNCTION create_or_update_gifts_in_partitioned_table() | |
RETURNS TRIGGER | |
AS | |
$$ | |
BEGIN | |
if exists (select 1 from gifts_partitioned where id = NEW.id) then | |
update gifts_partitioned set#{' '} | |
#{ | |
(Gift.columns.map(&:name) - %w[id]).map do |column| | |
"#{column} = NEW.#{column}" | |
end.join(", ") | |
} | |
where id = NEW.id; | |
else | |
insert into gifts_partitioned (#{Gift.columns.map(&:name).join(",")}) | |
values ( | |
#{ | |
Gift.columns.map(&:name).map do |column| | |
"NEW.#{column}" | |
end.join(", ") | |
} | |
); | |
end if; | |
return null; | |
END; | |
$$ | |
LANGUAGE plpgsql; | |
create TRIGGER copy_to_partitioned_table after INSERT or UPDATE on gifts | |
for each row EXECUTE PROCEDURE create_or_update_gifts_in_partitioned_table(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment