1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
-- ==============================================================
-- GNUmed database schema change script
--
-- License: GPL v2 or later
-- Author: Karsten Hilbert
--
-- ==============================================================
-- $Id: v10-clin-allergy-dynamic.sql,v 1.2 2009-04-03 10:00:32 ncq Exp $
-- $Revision: 1.2 $
-- --------------------------------------------------------------
\set ON_ERROR_STOP 1
--set default_transaction_read_only to off;
-- --------------------------------------------------------------
\unset ON_ERROR_STOP
drop function clin.trf_sync_allergic_state_on_allergies_modified() cascade;
\set ON_ERROR_STOP 1
create function clin.trf_sync_allergic_state_on_allergies_modified()
returns trigger
language 'plpgsql'
as '
DECLARE
_fk_patient integer;
_fk_encounter integer;
_state integer;
_no_of_allergies integer;
BEGIN
if TG_OP = ''INSERT'' then
select into _fk_patient fk_patient from clin.encounter where pk = NEW.fk_encounter;
_fk_encounter := NEW.fk_encounter;
_state := 1;
end if;
if TG_OP = ''DELETE'' then
-- only run this trigger if deleting last allergy
select into _fk_patient fk_patient from clin.encounter where pk = OLD.fk_encounter;
select into _no_of_allergies count(1) from clin.allergy where fk_encounter in (
select pk from clin.encounter where fk_patient = _fk_patient
);
if _no_of_allergies > 1 then
return OLD; -- still allergies left
end if;
_fk_encounter := OLD.fk_encounter;
_state := 0;
end if;
update clin.allergy_state
set
has_allergy = _state,
last_confirmed = coalesce(last_confirmed, now())
where fk_encounter in (
select pk from clin.encounter where fk_patient = _fk_patient
);
if not FOUND then
insert into clin.allergy_state
(fk_encounter, has_allergy, last_confirmed)
values
(_fk_encounter, _state, now());
end if;
return NEW;
END;';
comment on function clin.trf_sync_allergic_state_on_allergies_modified() is
'trigger function to sync the allergy state on insert/delete';
create trigger tr_sync_allergic_state_on_allergies_modified
after insert or delete on clin.allergy
for each row execute procedure clin.trf_sync_allergic_state_on_allergies_modified()
;
-- --------------------------------------------------------------
select gm.log_script_insertion('$RCSfile: v10-clin-allergy-dynamic.sql,v $', '$Revision: 1.2 $');
-- ==============================================================
-- $Log: v10-clin-allergy-dynamic.sql,v $
-- Revision 1.2 2009-04-03 10:00:32 ncq
-- - auto-insertion of allergy state from trigger must
-- include last_confirmed on appropriate states
--
-- Revision 1.1 2008/10/12 14:58:07 ncq
-- - new
--
--
|