1

So i have this inventory db

https://dbfiddle.uk/?rdbms=postgres_10&fiddle=19946dda5ca1ab86e9a8cf63717e65fa

Which more or less adds inventories from various sources (inventory_type) and will have a products(id) foreign key reference. According to which the sum would be calculated.

The predicated should be

If the stock value is in negative then it shouldn't be greater than the stock itself.

How would you suggest me to achieve it ?

Here is what i tried.

Check doesn't allow subqueries so i settled for triggers.

 CREATE FUNCTION public.check_stock_quantity()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF 
AS $BODY$
BEGIN
   IF NEW.stock < 0 THEN
       IF ((SELECT SUM(stock) FROM inventory WHERE id= NEW.id) - NEW.stock ) < 0 THEN
            RAISE EXCEPTION 'Not enough stocks. Invalid stock entry';
        END IF;
   END IF;

   RETURN NEW;
END;
$BODY$;

And then i applied it

stock_trigger BEFORE INSERT OR UPDATE ON inventory FOR EACH ROW EXECUTE PROCEDURE check_stock_quantity()

But it refuses to work.

Is there a better way to handle such an inventory ? If no then what is wrong with my triggers ?

2
  • In what way does it not work? Be specific. Commented Aug 22, 2019 at 20:14
  • EDIT :- it worked Commented Aug 23, 2019 at 1:53

1 Answer 1

1

First, the new stock should be added to (not subtracted from) the sum of stocks in the table. Next, you probably mean pid as the grouping column, as id is a primary key. So the function body should look like this:

    IF NEW.stock < 0 THEN
        IF ((SELECT SUM(stock) FROM inventory WHERE pid= NEW.pid) + NEW.stock ) < 0 THEN
            RAISE EXCEPTION 'Not enough stocks. Invalid stock entry';
        END IF;
    END IF;

    RETURN NEW;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.