Note that there are some explanatory texts on larger screens.

plurals
  1. POPostgreSQL triggers and exceptions
    primarykey
    data
    text
    <p>I'm trying to get my first ever trigger and function to work, but how I throw exceptions and return data right way?</p> <p>PostgreSQL 8.4.1</p> <pre><code>CREATE TABLE "SHIFTS" ( id integer NOT NULL, -- SERIAL added timestamp without time zone DEFAULT now() NOT NULL, starts timestamp without time zone NOT NULL, ends timestamp without time zone NOT NULL, employee_id integer, modified timestamp without time zone, status integer DEFAULT 1 NOT NULL, billid integer, CONSTRAINT "SHIFTS_check" CHECK ((starts &lt; ends)) ); -- Check if given shift time overlaps with existing data CREATE OR REPLACE FUNCTION shift_overlaps (integer, timestamp, timestamp) RETURNS boolean AS $$ DECLARE _employeeid ALIAS FOR $1; _start ALIAS FOR $2; _end ALIAS FOR $3; BEGIN SELECT COUNT(id) AS c FROM "SHIFTS" WHERE employee_id = _employeeid AND status = 1 AND ( (starts BETWEEN _start AND _end) OR (ends BETWEEN _start AND _end) ) ; -- Return boolean RETURN (c &gt; 0); END; $$ LANGUAGE plpgsql ; CREATE OR REPLACE FUNCTION check_shift() RETURNS trigger AS ' BEGIN -- Bill ID is set, do not allow update IF tg_op = "UPDATE" THEN IF old.billid IS NOT NULL THEN RAISE EXCEPTION "Shift is locked" END IF; END IF; -- Check for overlap IF tg_op = "INSERT" THEN IF new.employee_id IS NOT NULL THEN IF shift_overlaps(new.employee_id, new.starts, new.ends) THEN RAISE EXCEPTION "Given time overlaps with shifts" END IF; END IF; END IF; -- Check for overlap IF tg_op = "UPDATE" THEN IF (new.employee_id IS NOT NULL) AND (new.status = 1) THEN IF shift_overlaps(new.employee_id, new.starts, new.ends) THEN RAISE EXCEPTION "Given time overlaps with shifts" END IF; END IF; END IF; RETURN new; END ' LANGUAGE plpgsql ; -- Shift checker trigger CREATE TRIGGER check_shifts BEFORE INSERT OR UPDATE ON "SHIFTS" FOR EACH ROW EXECUTE PROCEDURE check_shift() ; </code></pre> <p>shift_overlaps():</p> <pre><code>SQL error: ERROR: query has no destination for result data </code></pre> <p>check_shift():</p> <pre><code>SQL error: ERROR: unrecognized exception condition "Shift is locked" </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload