2023-02-14 11:39:54 +00:00
|
|
|
-- Deploy numerus:add_product to pg
|
|
|
|
-- requires: schema_numerus
|
|
|
|
-- requires: product
|
|
|
|
-- requires: product_tax
|
|
|
|
-- requires: parse_price
|
|
|
|
-- requires: company
|
|
|
|
-- requires: currency
|
2023-03-26 11:51:57 +00:00
|
|
|
-- requires: tag_name
|
2023-02-14 11:39:54 +00:00
|
|
|
|
|
|
|
begin;
|
|
|
|
|
|
|
|
set search_path to numerus, public;
|
|
|
|
|
2023-03-26 11:51:57 +00:00
|
|
|
create or replace function add_product(company_id integer, name text, description text, price text, taxes integer[], tags tag_name[]) returns uuid
|
2023-02-14 11:39:54 +00:00
|
|
|
as $$
|
|
|
|
declare
|
|
|
|
pid integer;
|
|
|
|
pslug uuid;
|
|
|
|
begin
|
Replace tag relations with array attributes
It all started when i wanted to try to filter invoices by multiple tags
using an “AND”, instead of “OR” as it was doing until now. But
something felt off and seemed to me that i was doing thing much more
complex than needed, all to be able to list the tags as a suggestion
in the input field—which i am not doing yet.
I found this article series[0] exploring different approaches for
tagging, which includes the one i was using, and comparing their
performance. I have not actually tested it, but it seems that i have
chosen the worst option, in both query time and storage.
I attempted to try using an array attribute to each table, which is more
or less the same they did in the articles but without using a separate
relation for tags, and i found out that all the queries were way easier
to write, and needed two joins less, so it was a no-brainer.
[0]: http://www.databasesoup.com/2015/01/tag-all-things.html
2023-04-07 19:31:35 +00:00
|
|
|
insert into product (company_id, name, description, price, tags)
|
|
|
|
select add_product.company_id, add_product.name, add_product.description, parse_price(add_product.price, decimal_digits), add_product.tags
|
2023-02-14 11:39:54 +00:00
|
|
|
from company
|
|
|
|
join currency using (currency_code)
|
|
|
|
where company.company_id = add_product.company_id
|
|
|
|
returning product_id, slug
|
|
|
|
into pid, pslug;
|
|
|
|
|
|
|
|
insert into product_tax (product_id, tax_id)
|
|
|
|
select pid, tax_id
|
|
|
|
from unnest(taxes) as tax(tax_id);
|
|
|
|
|
|
|
|
return pslug;
|
|
|
|
end;
|
|
|
|
$$ language plpgsql;
|
|
|
|
|
2023-03-26 11:51:57 +00:00
|
|
|
revoke execute on function add_product(integer, text, text, text, integer[], tag_name[]) from public;
|
|
|
|
grant execute on function add_product(integer, text, text, text, integer[], tag_name[]) to invoicer;
|
|
|
|
grant execute on function add_product(integer, text, text, text, integer[], tag_name[]) to admin;
|
2023-02-14 11:39:54 +00:00
|
|
|
|
|
|
|
commit;
|