I've recently started using PostgreSQL and I'm trying to do things "the right way" as I've understood it. Meaning putting as much work in the database server instead of on the client as possible.
So I've created a function with PL/pgSQL that will add data to a table. Since I've a primary key constraint set on that table, and the referenced key may not exist at the time I'm trying to add the new data I've added an exception catching that will create the key and then try to insert the new row again.
This is working satisfactory for me, but I'm curious whether I'm handling this "the correct way". I've been trying to find some kind of guide of designing these user defined functions but havn't really found anything I found helpful.
CREATE OR REPLACE FUNCTION add_product_price_promo_xml(v_product_code varchar, v_description varchar, v_product_group varchar,
v_mixmatch_id integer, v_price_at date, v_cost_price numeric, v_sales_price numeric,
v_tax_rate integer) RETURNS void AS $$
BEGIN
INSERT INTO product_prices (product_code , mixmatch_id , price_at , cost_price , sales_price , tax_rate) VALUES
(v_product_code, v_mixmatch_id, v_price_at, v_cost_price, v_sales_price, v_tax_rate);
EXCEPTION WHEN foreign_key_violation THEN
INSERT INTO products (code, description, product_group) VALUES (v_product_code, v_description, v_product_group);
PERFORM add_product_price_promo_xml($1, $2, $3, $4, $5, $6, $7, $8);
END;
$$ LANGUAGE plpgsql;
The database in question is going to be used to make reports and will be importing the complete item register every day with price updates and new items, but I won't know which items are new and which ones are old.