
-- Copyright (C) 2011-2013, 2024, 2025 The Meme Factory, Inc.,
--           http://www.karlpinc.com/
-- Copyright (C) 2004-2011, Karl O. Pinc <kop@karlpinc.com>
--
--  This program is free software: you can redistribute it and/or modify
--  it under the terms of the GNU Affero General Public License as published
--  by the Free Software Foundation, either version 3 of the License, or
--  (at your option) any later version.
--
--  This program is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--  GNU Affero General Public License for more details.
--
--  You should have received a copy of the GNU Affero General Public License
--  along with this program.  If not, see <https://www.gnu.org/licenses/>.
--
-- Karl O. Pinc <kop@karlpinc.com>

-- DO NOT EDIT THIS FILE.  It was automatically generated.  Edit
-- the *.m4 files instead.  (Files _should_ be re-created by
-- typing 'make', with the appropriate target, at the command line.)

--  
-- isok_results
--

CREATE FUNCTION isok_results_func ()
  RETURNS trigger
  LANGUAGE plpgsql
  AS $$
  BEGIN
  -- Function for isok_results insert and update triggers
  --
  -- Copyright (C) 2015, 2025 The Meme Factory, Inc., http://www.karlpinc.com/
  -- Distributed under the GNU Affero General Public License, version 3 or later.

  IF TG_OP = 'UPDATE' THEN
    
  IF NEW.IRID <> OLD.IRID THEN
    -- IRID has changed
    RAISE EXCEPTION integrity_constraint_violation USING
          MESSAGE = 'Error on UPDATE of @EXTSCHEMA@.ISOK_RESULTS'
        , DETAIL =  'Value (IRID) = (' || OLD.IRID
                    || '): @EXTSCHEMA@.ISOK_RESULTS.IRID cannot be changed';
    RETURN NULL;
  END IF;

  END IF;

  -- Errors are not allowed to be resolved.
  IF NEW.resolved IS NOT NULL THEN
    PERFORM 1
      FROM @extschema@.isok_queries
      WHERE @extschema@.isok_queries.iqname = NEW.iqname
            AND @extschema@.isok_queries.error;
    IF FOUND THEN
      RAISE EXCEPTION integrity_constraint_violation USING
            MESSAGE = 'Error on ' || TG_OP || ' of ISOK_QUERIES'
          , DETAIL = 'Key (IRID) = (' || NEW.irid
                     || '): Value (IQName) = (' || NEW.iqname
                     || '): Value (QR_ID) = (' || NEW.qr_id
                     || '): Value (Resolved) = (' || NEW.resolved
                     || '): The INTEGRITY_QUERY ('
                     || NEW.iqname
                     || ') produces errors, these may not be marked resolved';
      RETURN NULL;
    END IF;
  END IF;

  RETURN NULL;
  END;
$$;


CREATE TRIGGER isok_results_trigger
  AFTER INSERT OR UPDATE
  ON isok_results FOR EACH ROW
  EXECUTE PROCEDURE isok_results_func();
