Index for gnumed_v22

Dumped on 2023-07-26

# Index of database - gnumed_v22

- au

- referral

- audit

- audit_fields
- audit_trail
- audited_tables
- log_access_log
- log_address
- log_allergy
- log_allergy_state
- log_auto_hint
- log_beh_fall_typ
- log_bill
- log_bill_item
- log_billable
- log_clin_aux_note
- log_clin_diag
- log_clin_item_type
- log_clin_narrative
- log_consumable_substance
- log_consumed_substance
- log_data_source
- log_doc_desc
- log_doc_med
- log_dose
- log_drug_product
- log_encounter
- log_episode
- log_external_care
- log_family_history
- log_fhx_relation_type
- log_form_data
- log_form_instances
- log_gender_label
- log_health_issue
- log_hospital_stay
- log_hx_family_item
- log_identity
- log_identity_tag
- log_inbox_item_category
- log_inbox_item_type
- log_incoming_data_unmatchable
- log_incoming_data_unmatched
- log_lab_request
- log_lab_test_gnr
- log_lnk_code2aoe
- log_lnk_code2episode
- log_lnk_code2fhx
- log_lnk_code2h_issue
- log_lnk_code2narrative
- log_lnk_code2procedure
- log_lnk_code2rfe
- log_lnk_code2tst_pnl
- log_lnk_constraint2vacc_course
- log_lnk_dose2drug
- log_lnk_identity2ext_id
- log_lnk_identity2primary_doc
- log_lnk_job2person
- log_lnk_loinc2substance
- log_lnk_loinc2test_panel
- log_lnk_org_unit2comm
- log_lnk_org_unit2ext_id
- log_lnk_pat2vaccination_course
- log_lnk_person2relative
- log_lnk_substance2brand
- log_lnk_tst2norm
- log_lnk_type2item
- log_lnk_vaccination_course2schedule
- log_lnk_vaccine2inds
- log_message_inbox
- log_occupation
- log_operation
- log_org
- log_org_unit
- log_paperwork_templates
- log_patient
- log_prax_geb_paid
- log_praxis_branch
- log_procedure
- log_referral
- log_region
- log_relation_types
- log_report_query
- log_staff
- log_street
- log_substance
- log_substance_in_brand
- log_substance_intake
- log_suppressed_hint
- log_tag_image
- log_test_org
- log_test_panel
- log_test_result
- log_test_type
- log_urb
- log_vacc_indication
- log_vacc_route
- log_vaccination
- log_vaccination_course
- log_vaccination_course_constraint
- log_vaccination_definition
- log_vaccination_schedule
- log_vaccine
- log_vaccine_batches
- log_waiting_list
- log_xlnk_identity
- v_audit_trail
- add_table_for_audit(name)
- add_table_for_audit(name, name)
- ft_del_access_log()
- ft_del_active_substance()
- ft_del_address()
- ft_del_allergy()
- ft_del_allergy_state()
- ft_del_atc_group()
- ft_del_atc_substance()
- ft_del_auto_hint()
- ft_del_beh_fall_typ()
- ft_del_behandlungsfall()
- ft_del_bill()
- ft_del_bill_item()
- ft_del_clin_aux_note()
- ft_del_clin_diag()
- ft_del_clin_item_type()
- ft_del_clin_medication()
- ft_del_clin_narrative()
- ft_del_coded_phrase()
- ft_del_consumable_substance()
- ft_del_consumed_substance()
- ft_del_data_source()
- ft_del_doc_desc()
- ft_del_doc_med()
- ft_del_dose()
- ft_del_drug_product()
- ft_del_encounter()
- ft_del_episode()
- ft_del_external_care()
- ft_del_family_history()
- ft_del_fhx_relation_type()
- ft_del_form_data()
- ft_del_form_defs()
- ft_del_form_instances()
- ft_del_gender_label()
- ft_del_health_issue()
- ft_del_hospital_stay()
- ft_del_hx_family_item()
- ft_del_identity()
- ft_del_identity_tag()
- ft_del_inbox_item_category()
- ft_del_inbox_item_type()
- ft_del_incoming_data_unmatchable()
- ft_del_incoming_data_unmatched()
- ft_del_lab_request()
- ft_del_lab_test_gnr()
- ft_del_lnk_code2aoe()
- ft_del_lnk_code2episode()
- ft_del_lnk_code2fhx()
- ft_del_lnk_code2h_issue()
- ft_del_lnk_code2narrative()
- ft_del_lnk_code2procedure()
- ft_del_lnk_code2rfe()
- ft_del_lnk_code2tst_pnl()
- ft_del_lnk_constraint2vacc_course()
- ft_del_lnk_dose2drug()
- ft_del_lnk_identity2ext_id()
- ft_del_lnk_identity2primary_doc()
- ft_del_lnk_job2person()
- ft_del_lnk_loinc2substance()
- ft_del_lnk_loinc2test_panel()
- ft_del_lnk_org_unit2comm()
- ft_del_lnk_org_unit2ext_id()
- ft_del_lnk_pat2vaccination_course()
- ft_del_lnk_person2relative()
- ft_del_lnk_substance2brand()
- ft_del_lnk_tst2norm()
- ft_del_lnk_type2item()
- ft_del_lnk_vaccination_course2schedule()
- ft_del_lnk_vaccine2inds()
- ft_del_message_inbox()
- ft_del_occupation()
- ft_del_operation()
- ft_del_org()
- ft_del_org_unit()
- ft_del_paperwork_templates()
- ft_del_patient()
- ft_del_prax_geb_paid()
- ft_del_praxis_branch()
- ft_del_procedure()
- ft_del_ref_source()
- ft_del_referral()
- ft_del_region()
- ft_del_relation_types()
- ft_del_report_query()
- ft_del_staff()
- ft_del_staff_role()
- ft_del_street()
- ft_del_substance()
- ft_del_substance_in_brand()
- ft_del_substance_intake()
- ft_del_suppressed_hint()
- ft_del_tag_image()
- ft_del_test_org()
- ft_del_test_panel()
- ft_del_test_result()
- ft_del_test_type()
- ft_del_urb()
- ft_del_vacc_indication()
- ft_del_vacc_route()
- ft_del_vaccination()
- ft_del_vaccination_course()
- ft_del_vaccination_course_constraint()
- ft_del_vaccination_definition()
- ft_del_vaccination_schedule()
- ft_del_vaccine()
- ft_del_vaccine_batches()
- ft_del_waiting_list()
- ft_del_xlnk_identity()
- ft_ins_access_log()
- ft_ins_active_substance()
- ft_ins_address()
- ft_ins_allergy()
- ft_ins_allergy_state()
- ft_ins_atc_group()
- ft_ins_atc_substance()
- ft_ins_auto_hint()
- ft_ins_beh_fall_typ()
- ft_ins_behandlungsfall()
- ft_ins_bill()
- ft_ins_bill_item()
- ft_ins_clin_aux_note()
- ft_ins_clin_diag()
- ft_ins_clin_item_type()
- ft_ins_clin_medication()
- ft_ins_clin_narrative()
- ft_ins_coded_phrase()
- ft_ins_consumable_substance()
- ft_ins_consumed_substance()
- ft_ins_data_source()
- ft_ins_doc_desc()
- ft_ins_doc_med()
- ft_ins_dose()
- ft_ins_drug_product()
- ft_ins_encounter()
- ft_ins_episode()
- ft_ins_external_care()
- ft_ins_family_history()
- ft_ins_fhx_relation_type()
- ft_ins_form_data()
- ft_ins_form_defs()
- ft_ins_form_instances()
- ft_ins_gender_label()
- ft_ins_health_issue()
- ft_ins_hospital_stay()
- ft_ins_hx_family_item()
- ft_ins_identity()
- ft_ins_identity_tag()
- ft_ins_inbox_item_category()
- ft_ins_inbox_item_type()
- ft_ins_incoming_data_unmatchable()
- ft_ins_incoming_data_unmatched()
- ft_ins_lab_request()
- ft_ins_lab_test_gnr()
- ft_ins_lnk_code2aoe()
- ft_ins_lnk_code2episode()
- ft_ins_lnk_code2fhx()
- ft_ins_lnk_code2h_issue()
- ft_ins_lnk_code2narrative()
- ft_ins_lnk_code2procedure()
- ft_ins_lnk_code2rfe()
- ft_ins_lnk_code2tst_pnl()
- ft_ins_lnk_constraint2vacc_course()
- ft_ins_lnk_dose2drug()
- ft_ins_lnk_identity2ext_id()
- ft_ins_lnk_identity2primary_doc()
- ft_ins_lnk_job2person()
- ft_ins_lnk_loinc2substance()
- ft_ins_lnk_loinc2test_panel()
- ft_ins_lnk_org_unit2comm()
- ft_ins_lnk_org_unit2ext_id()
- ft_ins_lnk_pat2vaccination_course()
- ft_ins_lnk_person2relative()
- ft_ins_lnk_substance2brand()
- ft_ins_lnk_tst2norm()
- ft_ins_lnk_type2item()
- ft_ins_lnk_vaccination_course2schedule()
- ft_ins_lnk_vaccine2inds()
- ft_ins_message_inbox()
- ft_ins_occupation()
- ft_ins_operation()
- ft_ins_org()
- ft_ins_org_unit()
- ft_ins_paperwork_templates()
- ft_ins_patient()
- ft_ins_prax_geb_paid()
- ft_ins_praxis_branch()
- ft_ins_procedure()
- ft_ins_ref_source()
- ft_ins_referral()
- ft_ins_region()
- ft_ins_relation_types()
- ft_ins_report_query()
- ft_ins_staff()
- ft_ins_staff_role()
- ft_ins_street()
- ft_ins_substance()
- ft_ins_substance_in_brand()
- ft_ins_substance_intake()
- ft_ins_suppressed_hint()
- ft_ins_tag_image()
- ft_ins_test_org()
- ft_ins_test_panel()
- ft_ins_test_result()
- ft_ins_test_type()
- ft_ins_urb()
- ft_ins_vacc_indication()
- ft_ins_vacc_route()
- ft_ins_vaccination()
- ft_ins_vaccination_course()
- ft_ins_vaccination_course_constraint()
- ft_ins_vaccination_definition()
- ft_ins_vaccination_schedule()
- ft_ins_vaccine()
- ft_ins_vaccine_batches()
- ft_ins_waiting_list()
- ft_ins_xlnk_identity()
- ft_upd_access_log()
- ft_upd_active_substance()
- ft_upd_address()
- ft_upd_allergy()
- ft_upd_allergy_state()
- ft_upd_atc_group()
- ft_upd_atc_substance()
- ft_upd_auto_hint()
- ft_upd_beh_fall_typ()
- ft_upd_behandlungsfall()
- ft_upd_bill()
- ft_upd_bill_item()
- ft_upd_clin_aux_note()
- ft_upd_clin_diag()
- ft_upd_clin_item_type()
- ft_upd_clin_medication()
- ft_upd_clin_narrative()
- ft_upd_coded_phrase()
- ft_upd_consumable_substance()
- ft_upd_consumed_substance()
- ft_upd_data_source()
- ft_upd_doc_desc()
- ft_upd_doc_med()
- ft_upd_dose()
- ft_upd_drug_product()
- ft_upd_encounter()
- ft_upd_episode()
- ft_upd_external_care()
- ft_upd_family_history()
- ft_upd_fhx_relation_type()
- ft_upd_form_data()
- ft_upd_form_defs()
- ft_upd_form_instances()
- ft_upd_gender_label()
- ft_upd_health_issue()
- ft_upd_hospital_stay()
- ft_upd_hx_family_item()
- ft_upd_identity()
- ft_upd_identity_tag()
- ft_upd_inbox_item_category()
- ft_upd_inbox_item_type()
- ft_upd_incoming_data_unmatchable()
- ft_upd_incoming_data_unmatched()
- ft_upd_lab_request()
- ft_upd_lab_test_gnr()
- ft_upd_lnk_code2aoe()
- ft_upd_lnk_code2episode()
- ft_upd_lnk_code2fhx()
- ft_upd_lnk_code2h_issue()
- ft_upd_lnk_code2narrative()
- ft_upd_lnk_code2procedure()
- ft_upd_lnk_code2rfe()
- ft_upd_lnk_code2tst_pnl()
- ft_upd_lnk_constraint2vacc_course()
- ft_upd_lnk_dose2drug()
- ft_upd_lnk_identity2ext_id()
- ft_upd_lnk_identity2primary_doc()
- ft_upd_lnk_job2person()
- ft_upd_lnk_loinc2substance()
- ft_upd_lnk_loinc2test_panel()
- ft_upd_lnk_org_unit2comm()
- ft_upd_lnk_org_unit2ext_id()
- ft_upd_lnk_pat2vaccination_course()
- ft_upd_lnk_person2relative()
- ft_upd_lnk_substance2brand()
- ft_upd_lnk_tst2norm()
- ft_upd_lnk_type2item()
- ft_upd_lnk_vaccination_course2schedule()
- ft_upd_lnk_vaccine2inds()
- ft_upd_message_inbox()
- ft_upd_occupation()
- ft_upd_operation()
- ft_upd_org()
- ft_upd_org_unit()
- ft_upd_paperwork_templates()
- ft_upd_patient()
- ft_upd_prax_geb_paid()
- ft_upd_praxis_branch()
- ft_upd_procedure()
- ft_upd_ref_source()
- ft_upd_referral()
- ft_upd_region()
- ft_upd_relation_types()
- ft_upd_report_query()
- ft_upd_staff()
- ft_upd_staff_role()
- ft_upd_street()
- ft_upd_substance()
- ft_upd_substance_in_brand()
- ft_upd_substance_intake()
- ft_upd_suppressed_hint()
- ft_upd_tag_image()
- ft_upd_test_org()
- ft_upd_test_panel()
- ft_upd_test_result()
- ft_upd_test_type()
- ft_upd_urb()
- ft_upd_vacc_indication()
- ft_upd_vacc_route()
- ft_upd_vaccination()
- ft_upd_vaccination_course()
- ft_upd_vaccination_course_constraint()
- ft_upd_vaccination_definition()
- ft_upd_vaccination_schedule()
- ft_upd_vaccine()
- ft_upd_vaccine_batches()
- ft_upd_waiting_list()
- ft_upd_xlnk_identity()
- register_table_for_auditing(name, name)

- bill

- bill
- bill_item
- lnk_enc_type2billable
- v_bill_items
- v_bills
- get_bill_receiver_identity(integer)
- trf_prevent_empty_bills()
- trf_prevent_mislinked_bills()

- blobs

- doc_desc
- doc_med
- doc_obj
- doc_type
- lnk_doc_med2episode
- reviewed_doc_objs
- v_doc_desc
- v_doc_med
- v_doc_med_journal
- v_doc_type
- v_latest_mugshot
- v_obj4doc_no_data
- v_reviewed_doc_objects
- v_unreviewed_docs
- v_unreviewed_docs_inbox
- v_unreviewed_docs_summary
- delete_document(integer, integer)
- delete_document_part(integer, integer)
- trf_do_not_duplicate_primary_episode_in_link_table()
- trf_mark_unreviewed_on_doc_obj_update()
- trf_remove_primary_episode_from_link_table()
- trf_set_intended_reviewer()
- trf_verify_page_number()

- cfg

- cfg_data
- cfg_item
- cfg_numeric
- cfg_str_array
- cfg_string
- cfg_template
- cfg_type_enum
- config
- db_logon_banner
- report_query
- v_cfg_options
- v_cfg_opts_data
- v_cfg_opts_numeric
- v_cfg_opts_str_array
- v_cfg_opts_string
- create_cfg_item(text, text, text, text, text)
- set_option(text, anyelement, text, text, text)

- clin

- _enum_allergy_type
- _view_emr_journal_without_suppressed_hints
- allergy
- allergy_state
- clin_aux_note
- clin_diag
- clin_item_type
- clin_narrative
- clin_root_item
- encounter
- encounter_type
- episode
- export_item
- external_care
- family_history
- fhx_relation_type
- form_data
- form_instances
- health_issue
- hospital_stay
- incoming_data_unmatchable
- incoming_data_unmatched
- lab_request
- lnk_code2aoe
- lnk_code2episode
- lnk_code2fhx
- lnk_code2h_issue
- lnk_code2item_root
- lnk_code2narrative
- lnk_code2procedure
- lnk_code2rfe
- lnk_code2tst_pnl
- lnk_constraint2vacc_course
- lnk_loinc2test_panel
- lnk_pat2vaccination_course
- lnk_substance2episode
- lnk_tst2norm
- lnk_type2item
- lnk_vaccination_course2schedule
- meta_test_type
- patient
- procedure
- review_root
- reviewed_test_results
- soap_cat_ranks
- substance_intake
- suppressed_hint
- test_org
- test_panel
- test_result
- test_type
- v_candidate_diagnoses
- v_edc_journal
- v_emr_journal
- v_export_items
- v_external_care
- v_external_care_journal
- v_family_history
- v_family_history_journal
- v_health_issues
- v_health_issues_journal
- v_hospital_stays
- v_hospital_stays_journal
- v_hospital_stays_journal_multi_day_adm
- v_hospital_stays_journal_multi_day_dis
- v_hospital_stays_journal_no_discharge
- v_hospital_stays_journal_one_day
- v_incoming_data_unmatched
- v_linked_codes
- v_most_recent_encounters
- v_narrative
- v_pat_allergies
- v_pat_allergies_journal
- v_pat_allergy_state
- v_pat_allergy_state_journal
- v_pat_encounters
- v_pat_encounters_journal
- v_pat_episodes
- v_pat_episodes_journal
- v_pat_items
- v_pat_last_vacc4indication
- v_pat_narrative_journal
- v_pat_vaccs4indication
- v_potential_problem_list
- v_problem_list
- v_procedures
- v_procedures_at_hospital
- v_procedures_at_hospital_journal
- v_procedures_journal
- v_procedures_not_at_hospital
- v_procedures_not_at_hospital_journal
- v_reminders_journal
- v_reviewed_items
- v_subst_intake4narr_search
- v_substance_intake_journal
- v_substance_intakes
- v_suppressed_hints
- v_suppressed_hints_journal
- v_test_orgs
- v_test_panels
- v_test_results
- v_test_results_journal
- v_test_types
- v_test_types4test_panel
- v_vaccination_courses_in_schedule
- v_vaccinations
- v_vaccinations_journal
- v_waiting_list
- vaccination
- vaccination_course
- vaccination_course_constraint
- vaccination_definition
- vaccination_schedule
- waiting_list
- _get_recommendation_for_patient_hint(text, integer)
- add_coded_phrase(text, text, text)
- f_del_booster_must_have_base_immunity()
- f_fk_reviewer_default()
- f_ins_booster_must_have_base_immunity()
- f_protect_clin_root_item()
- f_upd_booster_must_have_base_immunity()
- get_dob(integer)
- get_dod(integer)
- get_hints_for_patient(_pk_identity integer)
- hint_suppression_exists(_o_rationale integer, _o_md5 integer)
- move_waiting_list_entry(integer, integer)
- remove_old_empty_encounters(integer)
- remove_old_empty_encounters(integer, interval)
- run_hint_query(_o_title text, _o_applies text)
- transfer_all_encounter_data(_pk_target_encounter integer, _pk_source_encounter integer)
- trf_activate_issue_on_opening_episode()
- trf_announce_active_substance_mod_no_pk()
- trf_announce_consumed_substance_mod_no_pk()
- trf_check_ext_care_uniq_issue_per_enc_and_unit_ins_upd()
- trf_del_intake_document_deleted()
- trf_del_intake_must_unlink_all_drug_components()
- trf_ensure_one_allergy_state_per_patient()
- trf_ins_intake_prevent_duplicate_component_links()
- trf_ins_lc2sth_fk_generic_code()
- trf_ins_upd_export_item_normalize_fk_identity()
- trf_insert_intake_links_all_drug_components()
- trf_invalidate_review_on_result_change()
- trf_normalize_proc_is_ongoing()
- trf_notify_reviewer_of_review_change()
- trf_sanity_check_enc_epi_ins_upd()
- trf_sanity_check_enc_issue_ins_upd()
- trf_sanity_check_enc_vs_issue_on_epi()
- trf_sanity_check_procedure_episode()
- trf_sanity_check_uniq_hint_per_pat_ins_upd()
- trf_sync_allergic_state_on_allergies_modified()
- trf_undiscontinue_unsets_reason()
- trf_unique_indication_in_schedule()
- trf_upd_intake_must_link_all_drug_components()
- trf_upd_intake_prevent_duplicate_component_links()
- trf_upd_intake_updates_all_drug_components()
- trf_upd_lc2sth_fk_generic_code()

- de_de

- beh_fall_typ
- kvk
- lab_test_gnr
- payment_method
- prax_geb_paid
- zuzahlungsbefreiung

- dem

- address
- address_type
- country
- enum_comm_types
- enum_ext_id_types
- gender_label
- identity
- identity_tag
- inbox_item_category
- inbox_item_type
- lnk_identity2comm
- lnk_identity2ext_id
- lnk_job2person
- lnk_org_unit2comm
- lnk_org_unit2ext_id
- lnk_person2address
- lnk_person2relative
- lnk_person_org_address
- marital_status
- message_inbox
- name_gender_map
- names
- occupation
- org
- org_category
- org_unit
- praxis_branch
- region
- relation_types
- staff
- street
- urb
- v_active_persons
- v_address
- v_all_persons
- v_basic_address
- v_deleted_persons
- v_external_ids4identity
- v_external_ids4org_unit
- v_gender_labels
- v_identity_tags
- v_inbox_item_type
- v_message_inbox
- v_org_unit_comms
- v_org_units
- v_org_units_no_praxis_check
- v_orgs
- v_pat_addresses
- v_person_comms
- v_person_jobs
- v_person_names
- v_persons
- v_praxis_branches
- v_region
- v_staff
- v_street
- v_uniq_zipped_urbs
- v_urb
- v_zip2data
- v_zip2street
- v_zip2urb
- add_external_id_type(text, text)
- add_name(integer, text, text, boolean)
- address_exists(text, text, text, text, text, text, text)
- assert_unique_named_identity()
- create_address(text, text, text, text, text, text, text)
- create_comm_type(text)
- create_occupation(text)
- create_street(text, text, text, text, text)
- create_urb(text, text, text, text)
- date_trunc_utc(text, timestamp with time zone)
- dob_is_in_range(timestamp with time zone, interval, interval)
- f_always_active_name()
- f_delete_names()
- f_uniq_active_name()
- gm_upd_default_regions()
- remove_person(integer)
- set_nickname(integer, text)
- trf_normalize_time_in_dob()
- trf_null_empty_title()
- trf_prevent_deletion_of_in_use_staff()
- trf_prevent_multiple_praxi()
- trf_protect_active_name_of_person()

- gm

- access_log
- notifying_tables
- schema_revision
- account_is_dbowner_or_staff(_account name)
- add_missing_array_bits()
- add_table_for_notifies(name, name)
- add_user_to_permission_group(name, name)
- array_unnest(anyarray)
- concat_table_structure()
- concat_table_structure(integer)
- concat_table_structure_v1()
- concat_table_structure_v16_and_up()
- concat_table_structure_v17_and_up()
- concat_table_structure_v18_and_up()
- concat_table_structure_v19_and_up()
- concat_table_structure_v2()
- concat_table_structure_v3()
- create_all_enc_epi_sanity_check_triggers()
- create_all_table_mod_triggers(_drop_old_triggers boolean)
- create_enc_epi_sanity_check_trigger(_fk_episode_col name, _fk_encounter_col name, _table_name name, _schema_name name)
- create_generic_combi_vaccine(text, text[], text, boolean)
- create_table_mod_triggers(_table_name name, _schema_name name)
- create_user(name, text)
- disable_user(name)
- drop_user(name)
- get_users()
- get_users(name)
- is_null_or_blank_string(text)
- is_null_or_non_empty_string(text)
- lo_chunked_md5(oid, integer)
- log_access2emr(text)
- log_other_access(text)
- log_script_insertion(text, text)
- nullify_empty_string(text)
- register_notifying_table(name, name)
- strip_allzeros_fraction(numeric)
- transfer_users(text)
- transfer_users(text, text)
- trf_announce_table_del()
- trf_announce_table_ins_upd()
- user_exists(name)
- xid2int(xid)

- i18n

- curr_lang
- keys
- translations
- v_missing_translations
- _(text)
- _(text, text)
- force_curr_lang(text)
- get_curr_lang()
- get_curr_lang(text)
- i18n(text)
- set_curr_lang(text)
- set_curr_lang(text, name)
- tx_or_null(text)
- tx_or_null(text, text)
- unset_curr_lang()
- unset_curr_lang(name)
- untranslate(text, text)
- upd_tx(text, text)
- upd_tx(text, text, text)

- pgtrgm

- gin_extract_query_trgm(text, internal, smallint, internal, internal, internal, internal)
- gin_extract_value_trgm(text, internal)
- gin_trgm_consistent(internal, smallint, text, integer, internal, internal, internal, internal)
- gin_trgm_triconsistent(internal, smallint, text, integer, internal, internal, internal)
- gtrgm_compress(internal)
- gtrgm_consistent(internal, text, smallint, oid, internal)
- gtrgm_decompress(internal)
- gtrgm_distance(internal, text, smallint, oid, internal)
- gtrgm_in(cstring)
- gtrgm_options(internal)
- gtrgm_out(pgtrgm.gtrgm)
- gtrgm_penalty(internal, internal, internal)
- gtrgm_picksplit(internal, internal)
- gtrgm_same(pgtrgm.gtrgm, pgtrgm.gtrgm, internal)
- gtrgm_union(internal, internal)
- set_limit(real)
- show_limit()
- show_trgm(text)
- similarity(text, text)
- similarity_dist(text, text)
- similarity_op(text, text)
- strict_word_similarity(text, text)
- strict_word_similarity_commutator_op(text, text)
- strict_word_similarity_dist_commutator_op(text, text)
- strict_word_similarity_dist_op(text, text)
- strict_word_similarity_op(text, text)
- word_similarity(text, text)
- word_similarity_commutator_op(text, text)
- word_similarity_dist_commutator_op(text, text)
- word_similarity_dist_op(text, text)
- word_similarity_op(text, text)

- public

- basic_unit
- form_field_types
- form_fields
- form_job_queue
- form_job_targets
- form_print_defs
- gm_client_db_match
- housekeeping_todo
- test_norm
- unit
- _(text)
- _(text, text)
- f_rfi_type2item()
- f_set_encounter_timezone()

- ref

- atc
- atc_staging
- auto_hint
- billable
- coda
- code_thesaurus_root
- coding_system_root
- data_source
- document_type
- dose
- drug_product
- form_types
- icd10
- icd9
- icpc
- icpc_chapter
- icpc_component
- icpc_thesaurus
- keyword_expansion
- lnk_dose2drug
- lnk_loinc2substance
- loinc
- ops
- other_code
- papersizes
- paperwork_templates
- substance
- tag_image
- v_atc
- v_auto_hints
- v_billables
- v_coded_terms
- v_drug_components
- v_drug_products
- v_generic_codes
- v_icpc
- v_icpc_thesaurus
- v_indications4vaccine
- v_keyword_expansions
- v_lnk_loincs2substances
- v_paperwork_templates
- v_substance_doses
- v_substances
- v_tag_images_no_data
- v_vaccines
- v_your_keyword_expansions
- vacc_route
- vaccine
- trf_announce_substance_in_brand_mod_no_pk()
- trf_assert_product_has_components()
- trf_assert_product_keeps_components()
- trf_consumable_subst_normalize_amount()
- trf_del_ref_code_tbl_check_backlink()
- trf_do_not_update_component_if_taken_by_patient()
- trf_do_not_update_substance_if_taken_by_patient()
- trf_ins_upd_assert_dose_unit_across_drug_components()
- trf_protect_template_data()
- trf_true_brands_must_have_components()
- trf_upd_assert_dose_unit_in_multi_component_drugs()
- trf_upd_ref_code_tbl_check_backlink()

- staging

- lab_request
- lnk_vacc_ind2subst_dose
- loinc_staging
- test_result

# Schema au

## Table: au.referral

table for referrals to defined individuals

au.referral Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| id |  | PRIMARY KEY
clin.episode.pk | fk_episode |  |
clin.encounter.pk | fk_encounter |  |
dem.identity.pk | fk_referee |  |
clin.form_instances.pk | fk_form |  |

Table au.referral Inherits clin_root_item,

au.referral Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))

idx_au_referral_fk_encounter fk_encounter idx_au_referral_fk_episode fk_episode

Index - Schema au

# Schema audit

## Table: audit.audit_fields

this table holds all the fields needed for auditing

audit.audit_fields Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit |  | PRIMARY KEY

audit.audit_fields Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema audit

## Table: audit.audit_trail

Each table that needs standard auditing must have a log table inheriting from this table. Log tables have the same name with a prepended "log_". However, log_* tables shall not have constraints.

audit.audit_trail Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit |  | PRIMARY KEY

audit.audit_trail Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.audited_tables

All tables that need standard auditing must be recorded in this table. Audit triggers will be generated automatically for all tables recorded here.

audit.audited_tables Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| table_name |  | UNIQUE#1
| id |  | PRIMARY KEY
| schema |  | UNIQUE#1

Index - Schema audit

## Table: audit.log_access_log

audit.log_access_log Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_access_log Inherits audit_trail,

audit.log_access_log Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_address

audit.log_address Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_address Inherits audit_trail,

audit.log_address Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_allergy

audit.log_allergy Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_allergy Inherits audit_trail,

audit.log_allergy Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_allergy_state

audit.log_allergy_state Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_allergy_state Inherits audit_trail,

audit.log_allergy_state Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_auto_hint

audit.log_auto_hint Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_auto_hint Inherits audit_trail,

audit.log_auto_hint Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_beh_fall_typ

audit.log_beh_fall_typ Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_beh_fall_typ Inherits audit_trail,

audit.log_beh_fall_typ Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_bill

audit.log_bill Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_bill Inherits audit_trail,

audit.log_bill Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_bill_item

audit.log_bill_item Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_bill_item Inherits audit_trail,

audit.log_bill_item Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_billable

audit.log_billable Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_billable Inherits audit_trail,

audit.log_billable Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_clin_aux_note

audit.log_clin_aux_note Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_clin_aux_note Inherits audit_trail,

audit.log_clin_aux_note Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_clin_diag

audit.log_clin_diag Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_clin_diag Inherits audit_trail,

audit.log_clin_diag Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_clin_item_type

audit.log_clin_item_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_clin_item_type Inherits audit_trail,

audit.log_clin_item_type Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_clin_narrative

audit.log_clin_narrative Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_clin_narrative Inherits audit_trail,

audit.log_clin_narrative Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_consumable_substance

audit.log_consumable_substance Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_consumable_substance Inherits audit_trail,

audit.log_consumable_substance Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_consumed_substance

audit.log_consumed_substance Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_consumed_substance Inherits audit_trail,

audit.log_consumed_substance Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_data_source

audit.log_data_source Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_data_source Inherits audit_trail,

audit.log_data_source Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_doc_desc

audit.log_doc_desc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_doc_desc Inherits audit_trail,

audit.log_doc_desc Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_doc_med

audit.log_doc_med Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_doc_med Inherits audit_trail,

audit.log_doc_med Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_dose

audit.log_dose Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_dose Inherits audit_trail,

audit.log_dose Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_drug_product

audit.log_drug_product Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_drug_product Inherits audit_trail,

audit.log_drug_product Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_encounter

audit.log_encounter Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_encounter Inherits audit_trail,

audit.log_encounter Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_episode

audit.log_episode Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_episode Inherits audit_trail,

audit.log_episode Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_external_care

audit.log_external_care Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_external_care Inherits audit_trail,

audit.log_external_care Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_family_history

audit.log_family_history Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_family_history Inherits audit_trail,

audit.log_family_history Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_fhx_relation_type

audit.log_fhx_relation_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_fhx_relation_type Inherits audit_trail,

audit.log_fhx_relation_type Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_form_data

audit.log_form_data Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_form_data Inherits audit_trail,

audit.log_form_data Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_form_instances

audit.log_form_instances Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_form_instances Inherits audit_trail,

audit.log_form_instances Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_gender_label

audit.log_gender_label Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_gender_label Inherits audit_trail,

audit.log_gender_label Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_health_issue

audit.log_health_issue Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_health_issue Inherits audit_trail,

audit.log_health_issue Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_hospital_stay

audit.log_hospital_stay Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_hospital_stay Inherits audit_trail,

audit.log_hospital_stay Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_hx_family_item

audit.log_hx_family_item Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_hx_family_item Inherits audit_trail,

audit.log_hx_family_item Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_identity

audit.log_identity Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_identity Inherits audit_trail,

audit.log_identity Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_identity_tag

audit.log_identity_tag Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_identity_tag Inherits audit_trail,

audit.log_identity_tag Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_inbox_item_category

audit.log_inbox_item_category Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_inbox_item_category Inherits audit_trail,

audit.log_inbox_item_category Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_inbox_item_type

audit.log_inbox_item_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_inbox_item_type Inherits audit_trail,

audit.log_inbox_item_type Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_incoming_data_unmatchable

audit.log_incoming_data_unmatchable Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_incoming_data_unmatchable Inherits audit_trail,

audit.log_incoming_data_unmatchable Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_incoming_data_unmatched

audit.log_incoming_data_unmatched Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_incoming_data_unmatched Inherits audit_trail,

audit.log_incoming_data_unmatched Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lab_request

audit.log_lab_request Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lab_request Inherits audit_trail,

audit.log_lab_request Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lab_test_gnr

audit.log_lab_test_gnr Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lab_test_gnr Inherits audit_trail,

audit.log_lab_test_gnr Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_code2aoe

audit.log_lnk_code2aoe Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_code2aoe Inherits audit_trail,

audit.log_lnk_code2aoe Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_code2episode

audit.log_lnk_code2episode Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_code2episode Inherits audit_trail,

audit.log_lnk_code2episode Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_code2fhx

audit.log_lnk_code2fhx Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_code2fhx Inherits audit_trail,

audit.log_lnk_code2fhx Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_code2h_issue

audit.log_lnk_code2h_issue Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_code2h_issue Inherits audit_trail,

audit.log_lnk_code2h_issue Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_code2narrative

audit.log_lnk_code2narrative Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_code2narrative Inherits audit_trail,

audit.log_lnk_code2narrative Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_code2procedure

audit.log_lnk_code2procedure Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_code2procedure Inherits audit_trail,

audit.log_lnk_code2procedure Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_code2rfe

audit.log_lnk_code2rfe Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_code2rfe Inherits audit_trail,

audit.log_lnk_code2rfe Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_code2tst_pnl

audit.log_lnk_code2tst_pnl Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_code2tst_pnl Inherits audit_trail,

audit.log_lnk_code2tst_pnl Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_constraint2vacc_course

audit.log_lnk_constraint2vacc_course Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_constraint2vacc_course Inherits audit_trail,

audit.log_lnk_constraint2vacc_course Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_dose2drug

audit.log_lnk_dose2drug Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_dose2drug Inherits audit_trail,

audit.log_lnk_dose2drug Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_identity2ext_id

audit.log_lnk_identity2ext_id Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_identity2ext_id Inherits audit_trail,

audit.log_lnk_identity2ext_id Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_identity2primary_doc

audit.log_lnk_identity2primary_doc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_identity2primary_doc Inherits audit_trail,

audit.log_lnk_identity2primary_doc Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_job2person

audit.log_lnk_job2person Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_job2person Inherits audit_trail,

audit.log_lnk_job2person Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_loinc2substance

audit.log_lnk_loinc2substance Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_loinc2substance Inherits audit_trail,

audit.log_lnk_loinc2substance Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_loinc2test_panel

audit.log_lnk_loinc2test_panel Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_loinc2test_panel Inherits audit_trail,

audit.log_lnk_loinc2test_panel Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_org_unit2comm

audit.log_lnk_org_unit2comm Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_org_unit2comm Inherits audit_trail,

audit.log_lnk_org_unit2comm Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_org_unit2ext_id

audit.log_lnk_org_unit2ext_id Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_org_unit2ext_id Inherits audit_trail,

audit.log_lnk_org_unit2ext_id Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_pat2vaccination_course

audit.log_lnk_pat2vaccination_course Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_pat2vaccination_course Inherits audit_trail,

audit.log_lnk_pat2vaccination_course Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_person2relative

audit.log_lnk_person2relative Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_person2relative Inherits audit_trail,

audit.log_lnk_person2relative Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_substance2brand

audit.log_lnk_substance2brand Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_substance2brand Inherits audit_trail,

audit.log_lnk_substance2brand Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_tst2norm

audit.log_lnk_tst2norm Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_tst2norm Inherits audit_trail,

audit.log_lnk_tst2norm Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_type2item

audit.log_lnk_type2item Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_type2item Inherits audit_trail,

audit.log_lnk_type2item Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_vaccination_course2schedule

audit.log_lnk_vaccination_course2schedule Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_vaccination_course2schedule Inherits audit_trail,

audit.log_lnk_vaccination_course2schedule Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_lnk_vaccine2inds

audit.log_lnk_vaccine2inds Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_lnk_vaccine2inds Inherits audit_trail,

audit.log_lnk_vaccine2inds Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_message_inbox

audit.log_message_inbox Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_message_inbox Inherits audit_trail,

audit.log_message_inbox Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_occupation

audit.log_occupation Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_occupation Inherits audit_trail,

audit.log_occupation Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_operation

audit.log_operation Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_operation Inherits audit_trail,

audit.log_operation Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_org

audit.log_org Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_org Inherits audit_trail,

audit.log_org Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_org_unit

audit.log_org_unit Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_org_unit Inherits audit_trail,

audit.log_org_unit Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_paperwork_templates

audit.log_paperwork_templates Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_paperwork_templates Inherits audit_trail,

audit.log_paperwork_templates Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_patient

audit.log_patient Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_patient Inherits audit_trail,

audit.log_patient Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_prax_geb_paid

audit.log_prax_geb_paid Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_prax_geb_paid Inherits audit_trail,

audit.log_prax_geb_paid Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_praxis_branch

audit.log_praxis_branch Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_praxis_branch Inherits audit_trail,

audit.log_praxis_branch Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_procedure

audit.log_procedure Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_procedure Inherits audit_trail,

audit.log_procedure Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_referral

audit.log_referral Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_referral Inherits audit_trail,

audit.log_referral Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_region

audit.log_region Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_region Inherits audit_trail,

audit.log_region Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_relation_types

audit.log_relation_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_relation_types Inherits audit_trail,

audit.log_relation_types Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_report_query

audit.log_report_query Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_report_query Inherits audit_trail,

audit.log_report_query Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_staff

audit.log_staff Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_staff Inherits audit_trail,

audit.log_staff Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_street

audit.log_street Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_street Inherits audit_trail,

audit.log_street Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_substance

audit.log_substance Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_substance Inherits audit_trail,

audit.log_substance Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_substance_in_brand

audit.log_substance_in_brand Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_substance_in_brand Inherits audit_trail,

audit.log_substance_in_brand Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_substance_intake

audit.log_substance_intake Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_substance_intake Inherits audit_trail,

audit.log_substance_intake Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_suppressed_hint

audit.log_suppressed_hint Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_suppressed_hint Inherits audit_trail,

audit.log_suppressed_hint Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_tag_image

audit.log_tag_image Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_tag_image Inherits audit_trail,

audit.log_tag_image Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_test_org

audit.log_test_org Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_test_org Inherits audit_trail,

audit.log_test_org Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_test_panel

audit.log_test_panel Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_test_panel Inherits audit_trail,

audit.log_test_panel Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_test_result

audit.log_test_result Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_test_result Inherits audit_trail,

audit.log_test_result Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_test_type

audit.log_test_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_test_type Inherits audit_trail,

audit.log_test_type Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_urb

audit.log_urb Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_urb Inherits audit_trail,

audit.log_urb Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_vacc_indication

audit.log_vacc_indication Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_vacc_indication Inherits audit_trail,

audit.log_vacc_indication Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_vacc_route

audit.log_vacc_route Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_vacc_route Inherits audit_trail,

audit.log_vacc_route Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_vaccination

audit.log_vaccination Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_vaccination Inherits audit_trail,

audit.log_vaccination Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_vaccination_course

audit.log_vaccination_course Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_vaccination_course Inherits audit_trail,

audit.log_vaccination_course Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_vaccination_course_constraint

audit.log_vaccination_course_constraint Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_vaccination_course_constraint Inherits audit_trail,

audit.log_vaccination_course_constraint Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_vaccination_definition

audit.log_vaccination_definition Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_vaccination_definition Inherits audit_trail,

audit.log_vaccination_definition Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_vaccination_schedule

audit.log_vaccination_schedule Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_vaccination_schedule Inherits audit_trail,

audit.log_vaccination_schedule Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_vaccine

audit.log_vaccine Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_vaccine Inherits audit_trail,

audit.log_vaccine Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_vaccine_batches

audit.log_vaccine_batches Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_vaccine_batches Inherits audit_trail,

audit.log_vaccine_batches Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_waiting_list

audit.log_waiting_list Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_waiting_list Inherits audit_trail,

audit.log_waiting_list Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_xlnk_identity

audit.log_xlnk_identity Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Table audit.log_xlnk_identity Inherits audit_trail,

audit.log_xlnk_identity Constraints
Name | Constraint
--- | ---
audit_audit_trail_orig_before_audit_when | CHECK (((orig_when <= audit_when) IS TRUE))
audit_audit_trail_sane_audit_when | CHECK (((audit_when <= clock_timestamp()) IS TRUE))
audit_audit_trail_sane_orig_when | CHECK (((orig_when <= clock_timestamp()) IS TRUE))
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## View: audit.v_audit_trail

audit.v_audit_trail Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT to_char
    (aat.audit_when
         ,'YYYY-MM-DD HH24:MI'::text
    ) AS event_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = aat.audit_by)
         )
         , (
               ('<'::text ||
                     (aat.audit_by)::text
               ) || '>'::text
         )
    ) AS event_by
    ,

    (aat.orig_tableoid)::regclass AS event_table
    ,
        aat.orig_version AS row_version_before
    ,
            CASE
                WHEN
    (aat.audit_action = 'DELETE'::text) THEN NULL::integer
                ELSE
    (aat.orig_version + 1)
            END AS row_version_after
    ,
        aat.audit_action AS event
    ,
        aat.audit_when AS audit_when_ts
    ,
        aat.pk_audit

    FROM audit.audit_trail aat

    UNION ALL

    SELECT to_char
    (gal.modified_when
         ,'YYYY-MM-DD HH24:MI'::text
    ) AS event_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = gal.modified_by)
         )
         , (
               ('<'::text ||
                     (gal.modified_by)::text
               ) || '>'::text
         )
    ) AS event_by
    ,
        'gm.access_log'::regclass AS event_table
    ,
        NULL::integer AS row_version_before
    ,
        0 AS row_version_after
    ,
        gal.user_action AS event
    ,
        gal.modified_when AS audit_when_ts
    ,
        gal.pk_audit

    FROM gm.access_log gal

    WHERE (gal.row_version = 0)
    UNION ALL

    SELECT to_char
    (aaf.modified_when
         ,'YYYY-MM-DD HH24:MI'::text
    ) AS event_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = aaf.modified_by)
         )
         , (
               ('<'::text ||
                     (aaf.modified_by)::text
               ) || '>'::text
         )
    ) AS event_by
    ,

    (aaf.tableoid)::regclass AS event_table
    ,
        NULL::integer AS row_version_before
    ,
        0 AS row_version_after
    ,
        'INSERT'::text AS event
    ,
        aaf.modified_when AS audit_when_ts
    ,
        aaf.pk_audit

    FROM audit.audit_fields aaf

    WHERE (aaf.row_version = 0);

Index - Schema audit

## Function: audit.add_table_for_audit(name)

### Returns: boolean

### Language: SQL

sanity-checking convenience function for marking tables for auditing, schema is always "public"

    select audit.add_table_for_audit('public', $1);

## Function: audit.add_table_for_audit(name, name)

### Returns: boolean

### Language: PLPGSQL

sanity-checking convenience function for marking tables for auditing

    DECLARE
    	_relnamespace alias for $1;
    	_relname ALIAS FOR $2;
    	dummy RECORD;
    	tmp text;
    BEGIN
    	-- does table exist ?
    	select relname into dummy from pg_class where
    		relname = _relname and
    		relnamespace = (select oid from pg_namespace where nspname = _relnamespace)
    	;
    	if not found then
    		tmp := _relnamespace || '.' || _relname;
    		raise exception 'audit.add_table_for_audit: Table [%] does not exist.', tmp;
    		return false;
    	end if;
    	-- already queued for auditing ?
    	select 1 into dummy from audit.audited_tables where table_name = _relname and schema = _relnamespace;
    	if found then
    		return true;
    	end if;
    	-- add definition
    	insert into audit.audited_tables (
    		schema, table_name
    	) values (
    		_relnamespace, _relname
    	);
    	return true;
    END;

## Function: audit.ft_del_access_log()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_access_log (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, user_action
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.user_action
    	);
    	return OLD;
    END;

## Function: audit.ft_del_active_substance()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_active_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, atc_code
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.description, OLD.atc_code
    	);
    	return OLD;
    END;

## Function: audit.ft_del_address()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_address (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_street, aux_street, number, subunit, addendum, lat_lon
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_street, OLD.aux_street, OLD.number, OLD.subunit, OLD.addendum, OLD.lat_lon
    	);
    	return OLD;
    END;

## Function: audit.ft_del_allergy()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_allergy (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, substance, substance_code, generics, allergene, atc_code, fk_type, generic_specific, definite
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.substance, OLD.substance_code, OLD.generics, OLD.allergene, OLD.atc_code, OLD.fk_type, OLD.generic_specific, OLD.definite
    	);
    	return OLD;
    END;

## Function: audit.ft_del_allergy_state()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_allergy_state (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, has_allergy, comment, last_confirmed, fk_encounter
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.has_allergy, OLD.comment, OLD.last_confirmed, OLD.fk_encounter
    	);
    	return OLD;
    END;

## Function: audit.ft_del_atc_group()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_atc_group (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, code, description
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.code, OLD.description
    	);
    	return OLD;
    END;

## Function: audit.ft_del_atc_substance()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_atc_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, code, name, ddd_amount, fk_ddd_unit, route, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.code, OLD.name, OLD.ddd_amount, OLD.fk_ddd_unit, OLD.route, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_auto_hint()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_auto_hint (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, query, title, hint, url, is_active, source, lang, recommendation_query, popup_type, highlight_as_priority
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.query, OLD.title, OLD.hint, OLD.url, OLD.is_active, OLD.source, OLD.lang, OLD.recommendation_query, OLD.popup_type, OLD.highlight_as_priority
    	);
    	return OLD;
    END;

## Function: audit.ft_del_beh_fall_typ()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_beh_fall_typ (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, code, kurzform, name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.code, OLD.kurzform, OLD.name
    	);
    	return OLD;
    END;

## Function: audit.ft_del_behandlungsfall()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_behandlungsfall (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient, fk_falltyp, started, must_pay_prax_geb
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient, OLD.fk_falltyp, OLD.started, OLD.must_pay_prax_geb
    	);
    	return OLD;
    END;

## Function: audit.ft_del_bill()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_bill (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, invoice_id, close_date, apply_vat, fk_receiver_identity, fk_receiver_address, fk_doc, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.invoice_id, OLD.close_date, OLD.apply_vat, OLD.fk_receiver_identity, OLD.fk_receiver_address, OLD.fk_doc, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_bill_item()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_bill_item (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_provider, fk_encounter, date_to_bill, description, net_amount_per_unit, currency, status, fk_billable, fk_bill, unit_count, amount_multiplier
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_provider, OLD.fk_encounter, OLD.date_to_bill, OLD.description, OLD.net_amount_per_unit, OLD.currency, OLD.status, OLD.fk_billable, OLD.fk_bill, OLD.unit_count, OLD.amount_multiplier
    	);
    	return OLD;
    END;

## Function: audit.ft_del_clin_aux_note()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_clin_aux_note (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_clin_diag()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_clin_diag (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_narrative, laterality, is_chronic, is_active, is_definite, clinically_relevant
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_narrative, OLD.laterality, OLD.is_chronic, OLD.is_active, OLD.is_definite, OLD.clinically_relevant
    	);
    	return OLD;
    END;

## Function: audit.ft_del_clin_item_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_clin_item_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, type, code
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.type, OLD.code
    	);
    	return OLD;
    END;

## Function: audit.ft_del_clin_medication()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_clin_medication (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, last_prescribed, fk_last_script, discontinued, brandname, generic, adjuvant, dosage_form, ufk_drug, drug_db, atc_code, is_cr, dosage, period, dosage_unit, directions, is_prn
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.last_prescribed, OLD.fk_last_script, OLD.discontinued, OLD.brandname, OLD.generic, OLD.adjuvant, OLD.dosage_form, OLD.ufk_drug, OLD.drug_db, OLD.atc_code, OLD.is_cr, OLD.dosage, OLD.period, OLD.dosage_unit, OLD.directions, OLD.is_prn
    	);
    	return OLD;
    END;

## Function: audit.ft_del_clin_narrative()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_clin_narrative (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_coded_phrase()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_coded_phrase (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, term, code, xfk_coding_system
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.term, OLD.code, OLD.xfk_coding_system
    	);
    	return OLD;
    END;

## Function: audit.ft_del_consumable_substance()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_consumable_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, atc_code, amount, unit
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.atc_code, OLD.amount, OLD.unit
    	);
    	return OLD;
    END;

## Function: audit.ft_del_consumed_substance()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_consumed_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, atc_code
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.description, OLD.atc_code
    	);
    	return OLD;
    END;

## Function: audit.ft_del_data_source()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_data_source (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, name_long, name_short, version, description, source, lang
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.name_long, OLD.name_short, OLD.version, OLD.description, OLD.source, OLD.lang
    	);
    	return OLD;
    END;

## Function: audit.ft_del_doc_desc()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_doc_desc (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_doc, text
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_doc, OLD.text
    	);
    	return OLD;
    END;

## Function: audit.ft_del_doc_med()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_doc_med (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_encounter, fk_episode, fk_type, comment, clin_when, ext_ref, fk_org_unit, unit_is_receiver, fk_hospital_stay
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_encounter, OLD.fk_episode, OLD.fk_type, OLD.comment, OLD.clin_when, OLD.ext_ref, OLD.fk_org_unit, OLD.unit_is_receiver, OLD.fk_hospital_stay
    	);
    	return OLD;
    END;

## Function: audit.ft_del_dose()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_dose (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_substance, amount, unit, dose_unit
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_substance, OLD.amount, OLD.unit, OLD.dose_unit
    	);
    	return OLD;
    END;

## Function: audit.ft_del_drug_product()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_drug_product (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, preparation, atc_code, is_fake, fk_data_source, external_code, external_code_type
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.preparation, OLD.atc_code, OLD.is_fake, OLD.fk_data_source, OLD.external_code, OLD.external_code_type
    	);
    	return OLD;
    END;

## Function: audit.ft_del_encounter()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_encounter (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient, fk_type, fk_location, source_time_zone, reason_for_encounter, assessment_of_encounter, started, last_affirmed
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient, OLD.fk_type, OLD.fk_location, OLD.source_time_zone, OLD.reason_for_encounter, OLD.assessment_of_encounter, OLD.started, OLD.last_affirmed
    	);
    	return OLD;
    END;

## Function: audit.ft_del_episode()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_episode (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_health_issue, description, is_open, fk_encounter, diagnostic_certainty_classification, summary
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_health_issue, OLD.description, OLD.is_open, OLD.fk_encounter, OLD.diagnostic_certainty_classification, OLD.summary
    	);
    	return OLD;
    END;

## Function: audit.ft_del_external_care()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_external_care (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_encounter, fk_health_issue, issue, fk_org_unit, provider, comment, inactive
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_encounter, OLD.fk_health_issue, OLD.issue, OLD.fk_org_unit, OLD.provider, OLD.comment, OLD.inactive
    	);
    	return OLD;
    END;

## Function: audit.ft_del_family_history()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_family_history (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_relation_type, age_noted, age_of_death, contributed_to_death, name_relative, dob_relative, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_relation_type, OLD.age_noted, OLD.age_of_death, OLD.contributed_to_death, OLD.name_relative, OLD.dob_relative, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_fhx_relation_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_fhx_relation_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, is_genetic
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.is_genetic
    	);
    	return OLD;
    END;

## Function: audit.ft_del_form_data()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_form_data (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_instance, fk_form_field, value
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_instance, OLD.fk_form_field, OLD.value
    	);
    	return OLD;
    END;

## Function: audit.ft_del_form_defs()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_form_defs (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_type, country, locale, soap_cat, name_short, name_long, revision, template, engine, in_use, url, is_user
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_type, OLD.country, OLD.locale, OLD.soap_cat, OLD.name_short, OLD.name_long, OLD.revision, OLD.template, OLD.engine, OLD.in_use, OLD.url, OLD.is_user
    	);
    	return OLD;
    END;

## Function: audit.ft_del_form_instances()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_form_instances (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_form_def, form_name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_form_def, OLD.form_name
    	);
    	return OLD;
    END;

## Function: audit.ft_del_gender_label()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_gender_label (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, tag, label, sort_weight, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.tag, OLD.label, OLD.sort_weight, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_health_issue()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_health_issue (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, laterality, age_noted, is_active, clinically_relevant, is_confidential, is_cause_of_death, fk_encounter, grouping, diagnostic_certainty_classification, summary
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.laterality, OLD.age_noted, OLD.is_active, OLD.clinically_relevant, OLD.is_confidential, OLD.is_cause_of_death, OLD.fk_encounter, OLD.grouping, OLD.diagnostic_certainty_classification, OLD.summary
    	);
    	return OLD;
    END;

## Function: audit.ft_del_hospital_stay()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_hospital_stay (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, discharge, fk_org_unit
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.discharge, OLD.fk_org_unit
    	);
    	return OLD;
    END;

## Function: audit.ft_del_hx_family_item()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_hx_family_item (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_narrative_condition, fk_relative, name_relative, dob_relative, condition, age_noted, age_of_death, is_cause_of_death
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_narrative_condition, OLD.fk_relative, OLD.name_relative, OLD.dob_relative, OLD.condition, OLD.age_noted, OLD.age_of_death, OLD.is_cause_of_death
    	);
    	return OLD;
    END;

## Function: audit.ft_del_identity()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_identity (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, deleted, gender, dob, fk_marital_status, cob, deceased, title, tob, emergency_contact, fk_emergency_contact, comment, fk_primary_provider, dob_is_estimated
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.deleted, OLD.gender, OLD.dob, OLD.fk_marital_status, OLD.cob, OLD.deceased, OLD.title, OLD.tob, OLD.emergency_contact, OLD.fk_emergency_contact, OLD.comment, OLD.fk_primary_provider, OLD.dob_is_estimated
    	);
    	return OLD;
    END;

## Function: audit.ft_del_identity_tag()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_identity_tag (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, fk_tag, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.fk_tag, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_inbox_item_category()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_inbox_item_category (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, is_user
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.is_user
    	);
    	return OLD;
    END;

## Function: audit.ft_del_inbox_item_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_inbox_item_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_inbox_item_category, description, is_user
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_inbox_item_category, OLD.description, OLD.is_user
    	);
    	return OLD;
    END;

## Function: audit.ft_del_incoming_data_unmatchable()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_incoming_data_unmatchable (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient_candidates, request_id, firstnames, lastnames, dob, postcode, other_info, type, data, gender, requestor, external_data_id, fk_identity_disambiguated
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient_candidates, OLD.request_id, OLD.firstnames, OLD.lastnames, OLD.dob, OLD.postcode, OLD.other_info, OLD.type, OLD.data, OLD.gender, OLD.requestor, OLD.external_data_id, OLD.fk_identity_disambiguated
    	);
    	return OLD;
    END;

## Function: audit.ft_del_incoming_data_unmatched()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_incoming_data_unmatched (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient_candidates, request_id, firstnames, lastnames, dob, postcode, other_info, type, data, gender, requestor, external_data_id, fk_identity_disambiguated, comment, fk_provider_disambiguated
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient_candidates, OLD.request_id, OLD.firstnames, OLD.lastnames, OLD.dob, OLD.postcode, OLD.other_info, OLD.type, OLD.data, OLD.gender, OLD.requestor, OLD.external_data_id, OLD.fk_identity_disambiguated, OLD.comment, OLD.fk_provider_disambiguated
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lab_request()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lab_request (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_test_org, request_id, fk_requestor, lab_request_id, lab_rxd_when, results_reported_when, request_status, is_pending, diagnostic_service_section, ordered_service, note_test_org
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_test_org, OLD.request_id, OLD.fk_requestor, OLD.lab_request_id, OLD.lab_rxd_when, OLD.results_reported_when, OLD.request_status, OLD.is_pending, OLD.diagnostic_service_section, OLD.ordered_service, OLD.note_test_org
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lab_test_gnr()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lab_test_gnr (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_test
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_test
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_code2aoe()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_code2aoe (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_code2episode()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_code2episode (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_code2fhx()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_code2fhx (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_code2h_issue()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_code2h_issue (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_code2narrative()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_code2narrative (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_code2procedure()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_code2procedure (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_code2rfe()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_code2rfe (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_code2tst_pnl()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_code2tst_pnl (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_constraint2vacc_course()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_constraint2vacc_course (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_vaccination_course, fk_constraint
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_vaccination_course, OLD.fk_constraint
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_dose2drug()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_dose2drug (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_drug_product, fk_dose
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_drug_product, OLD.fk_dose
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_identity2ext_id()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_identity2ext_id (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_identity, external_id, fk_origin, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_identity, OLD.external_id, OLD.fk_origin, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_identity2primary_doc()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_identity2primary_doc (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, fk_primary_doc
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.fk_primary_doc
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_job2person()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_job2person (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, fk_occupation, activities
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.fk_occupation, OLD.activities
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_loinc2substance()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_loinc2substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_substance, loinc, max_age, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_substance, OLD.loinc, OLD.max_age, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_loinc2test_panel()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_loinc2test_panel (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_test_panel, loinc
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_test_panel, OLD.loinc
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_org_unit2comm()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_org_unit2comm (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_org_unit, url, fk_type, is_confidential, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_org_unit, OLD.url, OLD.fk_type, OLD.is_confidential, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_org_unit2ext_id()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_org_unit2ext_id (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_org_unit, external_id, fk_type, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_org_unit, OLD.external_id, OLD.fk_type, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_pat2vaccination_course()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_pat2vaccination_course (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient, fk_course
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient, OLD.fk_course
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_person2relative()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_person2relative (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_identity, id_relative, id_relation_type, started, ended
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_identity, OLD.id_relative, OLD.id_relation_type, OLD.started, OLD.ended
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_substance2brand()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_substance2brand (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_brand, fk_substance
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_brand, OLD.fk_substance
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_tst2norm()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_tst2norm (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_test, id_norm
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_test, OLD.id_norm
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_type2item()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_type2item (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_type, fk_item
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_type, OLD.fk_item
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_vaccination_course2schedule()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_vaccination_course2schedule (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_course, fk_schedule
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_course, OLD.fk_schedule
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_vaccine2inds()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_lnk_vaccine2inds (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, fk_vaccine, fk_indication
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.fk_vaccine, OLD.fk_indication
    	);
    	return OLD;
    END;

## Function: audit.ft_del_message_inbox()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_message_inbox (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_staff, fk_inbox_item_type, comment, data, importance, fk_patient, ufk_context, due_date, expiry_date
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_staff, OLD.fk_inbox_item_type, OLD.comment, OLD.data, OLD.importance, OLD.fk_patient, OLD.ufk_context, OLD.due_date, OLD.expiry_date
    	);
    	return OLD;
    END;

## Function: audit.ft_del_occupation()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_occupation (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.name
    	);
    	return OLD;
    END;

## Function: audit.ft_del_operation()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_operation (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_health_issue, fk_encounter, clin_where, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_health_issue, OLD.fk_encounter, OLD.clin_where, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_org()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_org (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, fk_category, fk_data_source
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.fk_category, OLD.fk_data_source
    	);
    	return OLD;
    END;

## Function: audit.ft_del_org_unit()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_org_unit (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, fk_org, fk_address, fk_category
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.fk_org, OLD.fk_address, OLD.fk_category
    	);
    	return OLD;
    END;

## Function: audit.ft_del_paperwork_templates()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_paperwork_templates (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_template_type, instance_type, name_short, name_long, external_version, gnumed_revision, engine, in_use, filename, data, edit_after_substitution
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_template_type, OLD.instance_type, OLD.name_short, OLD.name_long, OLD.external_version, OLD.gnumed_revision, OLD.engine, OLD.in_use, OLD.filename, OLD.data, OLD.edit_after_substitution
    	);
    	return OLD;
    END;

## Function: audit.ft_del_patient()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_patient (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, edc
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.edc
    	);
    	return OLD;
    END;

## Function: audit.ft_del_prax_geb_paid()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_prax_geb_paid (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_fall, paid_amount, paid_when, paid_with
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_fall, OLD.paid_amount, OLD.paid_when, OLD.paid_with
    	);
    	return OLD;
    END;

## Function: audit.ft_del_praxis_branch()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_praxis_branch (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_org_unit
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_org_unit
    	);
    	return OLD;
    END;

## Function: audit.ft_del_procedure()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_procedure (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_hospital_stay, clin_end, is_ongoing, fk_org_unit, fk_doc, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_hospital_stay, OLD.clin_end, OLD.is_ongoing, OLD.fk_org_unit, OLD.fk_doc, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_ref_source()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_ref_source (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, name_short, name_long, version, description, source
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.name_short, OLD.name_long, OLD.version, OLD.description, OLD.source
    	);
    	return OLD;
    END;

## Function: audit.ft_del_referral()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_referral (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, id, fk_referee, fk_form
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.id, OLD.fk_referee, OLD.fk_form
    	);
    	return OLD;
    END;

## Function: audit.ft_del_region()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_region (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, code, country, name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.code, OLD.country, OLD.name
    	);
    	return OLD;
    END;

## Function: audit.ft_del_relation_types()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_relation_types (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, inverse, biological, biol_verified, description
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.inverse, OLD.biological, OLD.biol_verified, OLD.description
    	);
    	return OLD;
    END;

## Function: audit.ft_del_report_query()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_report_query (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, label, cmd
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.label, OLD.cmd
    	);
    	return OLD;
    END;

## Function: audit.ft_del_staff()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_staff (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, db_user, short_alias, comment, is_active
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.db_user, OLD.short_alias, OLD.comment, OLD.is_active
    	);
    	return OLD;
    END;

## Function: audit.ft_del_staff_role()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_staff_role (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, name, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.name, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_street()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_street (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_urb, name, postcode, suburb, lat_lon
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_urb, OLD.name, OLD.postcode, OLD.suburb, OLD.lat_lon
    	);
    	return OLD;
    END;

## Function: audit.ft_del_substance()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, atc, intake_instructions
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.atc, OLD.intake_instructions
    	);
    	return OLD;
    END;

## Function: audit.ft_del_substance_in_brand()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_substance_in_brand (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_brand, description, atc_code
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_brand, OLD.description, OLD.atc_code
    	);
    	return OLD;
    END;

## Function: audit.ft_del_substance_intake()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_substance_intake (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, schedule, aim, duration, intake_is_approved_of, is_long_term, discontinued, discontinue_reason, fk_drug_component, comment_on_start, harmful_use_type
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.schedule, OLD.aim, OLD.duration, OLD.intake_is_approved_of, OLD.is_long_term, OLD.discontinued, OLD.discontinue_reason, OLD.fk_drug_component, OLD.comment_on_start, OLD.harmful_use_type
    	);
    	return OLD;
    END;

## Function: audit.ft_del_suppressed_hint()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_suppressed_hint (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_encounter, fk_hint, suppressed_by, suppressed_when, rationale, md5_sum
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_encounter, OLD.fk_hint, OLD.suppressed_by, OLD.suppressed_when, OLD.rationale, OLD.md5_sum
    	);
    	return OLD;
    END;

## Function: audit.ft_del_tag_image()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_tag_image (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, filename, image
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.filename, OLD.image
    	);
    	return OLD;
    END;

## Function: audit.ft_del_test_org()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_test_org (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_org_unit, fk_adm_contact, fk_med_contact, comment, contact
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_org_unit, OLD.fk_adm_contact, OLD.fk_med_contact, OLD.comment, OLD.contact
    	);
    	return OLD;
    END;

## Function: audit.ft_del_test_panel()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_test_panel (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_test_result()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_test_result (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_type, val_num, val_alpha, val_unit, val_normal_min, val_normal_max, val_normal_range, val_target_min, val_target_max, val_target_range, abnormality_indicator, norm_ref_group, note_test_org, material, material_detail, fk_intended_reviewer, fk_request, status, source_data, val_grouping
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_type, OLD.val_num, OLD.val_alpha, OLD.val_unit, OLD.val_normal_min, OLD.val_normal_max, OLD.val_normal_range, OLD.val_target_min, OLD.val_target_max, OLD.val_target_range, OLD.abnormality_indicator, OLD.norm_ref_group, OLD.note_test_org, OLD.material, OLD.material_detail, OLD.fk_intended_reviewer, OLD.fk_request, OLD.status, OLD.source_data, OLD.val_grouping
    	);
    	return OLD;
    END;

## Function: audit.ft_del_test_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_test_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_test_org, name, comment, reference_unit, loinc, abbrev, fk_meta_test_type
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_test_org, OLD.name, OLD.comment, OLD.reference_unit, OLD.loinc, OLD.abbrev, OLD.fk_meta_test_type
    	);
    	return OLD;
    END;

## Function: audit.ft_del_urb()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_urb (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, fk_region, postcode, lat_lon, name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.fk_region, OLD.postcode, OLD.lat_lon, OLD.name
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vacc_indication()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_vacc_indication (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, description, atcs_single_indication, atcs_combi_indication
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.description, OLD.atcs_single_indication, OLD.atcs_combi_indication
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vacc_route()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_vacc_route (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, abbreviation, description
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.abbreviation, OLD.description
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccination()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_vaccination (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_provider, fk_vaccine, site, batch_no, reaction
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_provider, OLD.fk_vaccine, OLD.site, OLD.batch_no, OLD.reaction
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccination_course()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_vaccination_course (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_recommended_by, fk_indication, is_active, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_recommended_by, OLD.fk_indication, OLD.is_active, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccination_course_constraint()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_vaccination_course_constraint (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccination_definition()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_vaccination_definition (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, fk_course, is_booster, seq_no, min_age_due, max_age_due, min_interval, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.fk_course, OLD.is_booster, OLD.seq_no, OLD.min_age_due, OLD.max_age_due, OLD.min_interval, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccination_schedule()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_vaccination_schedule (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, name, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.name, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccine()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_vaccine (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, id_route, is_live, min_age, max_age, comment, fk_drug_product
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.id_route, OLD.is_live, OLD.min_age, OLD.max_age, OLD.comment, OLD.fk_drug_product
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccine_batches()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_vaccine_batches (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_vaccine, batch_no
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_vaccine, OLD.batch_no
    	);
    	return OLD;
    END;

## Function: audit.ft_del_waiting_list()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_deleter boolean;
    BEGIN
    	-- is the session user allowed to delete data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_deleter;
    	IF _is_allowed_deleter IS FALSE THEN
    		RAISE EXCEPTION
    			'DELETE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return OLD;
    	END IF;
    	INSERT INTO audit.log_waiting_list (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient, registered, urgency, list_position, comment, area
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient, OLD.registered, OLD.urgency, OLD.list_position, OLD.comment, OLD.area
    	);
    	return OLD;
    END;

## Function: audit.ft_del_xlnk_identity()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_xlnk_identity (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, xfk_identity, pupic, data
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.xfk_identity, OLD.pupic, OLD.data
    	);
    	return OLD;
    END;

## Function: audit.ft_ins_access_log()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_active_substance()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_address()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_allergy()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_allergy_state()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_atc_group()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_atc_substance()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_auto_hint()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_beh_fall_typ()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_behandlungsfall()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_bill()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_bill_item()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_clin_aux_note()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_clin_diag()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_clin_item_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_clin_medication()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_clin_narrative()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_coded_phrase()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_consumable_substance()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_consumed_substance()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_data_source()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_doc_desc()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_doc_med()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_dose()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_drug_product()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_encounter()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_episode()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_external_care()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_family_history()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_fhx_relation_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_form_data()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_form_defs()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_form_instances()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_gender_label()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_health_issue()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_hospital_stay()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_hx_family_item()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_identity()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_identity_tag()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_inbox_item_category()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_inbox_item_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_incoming_data_unmatchable()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_incoming_data_unmatched()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lab_request()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lab_test_gnr()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_code2aoe()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_code2episode()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_code2fhx()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_code2h_issue()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_code2narrative()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_code2procedure()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_code2rfe()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_code2tst_pnl()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_constraint2vacc_course()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_dose2drug()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_identity2ext_id()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_identity2primary_doc()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_job2person()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_loinc2substance()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_loinc2test_panel()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_org_unit2comm()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_org_unit2ext_id()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_pat2vaccination_course()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_person2relative()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_substance2brand()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_tst2norm()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_type2item()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_vaccination_course2schedule()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_lnk_vaccine2inds()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_message_inbox()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_occupation()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_operation()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_org()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_org_unit()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_paperwork_templates()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_patient()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_prax_geb_paid()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_praxis_branch()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_procedure()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_ref_source()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_referral()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_region()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_relation_types()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_report_query()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_staff()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_staff_role()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_street()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_substance()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_substance_in_brand()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_substance_intake()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_suppressed_hint()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_tag_image()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_test_org()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_test_panel()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_test_result()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_test_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_urb()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_vacc_indication()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_vacc_route()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_vaccination()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_vaccination_course()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_vaccination_course_constraint()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_vaccination_definition()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_vaccination_schedule()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_vaccine()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_vaccine_batches()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_waiting_list()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_inserter boolean;
    BEGIN
    	-- is the session user allowed to insert data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_inserter;
    	IF _is_allowed_inserter IS FALSE THEN
    		RAISE EXCEPTION
    			'INSERT: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_ins_xlnk_identity()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := 0;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	return NEW;
    END;

## Function: audit.ft_upd_access_log()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_access_log (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, user_action
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.user_action
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_active_substance()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_active_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, atc_code
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.description, OLD.atc_code
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_address()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_address (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_street, aux_street, number, subunit, addendum, lat_lon
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_street, OLD.aux_street, OLD.number, OLD.subunit, OLD.addendum, OLD.lat_lon
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_allergy()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_allergy (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, substance, substance_code, generics, allergene, atc_code, fk_type, generic_specific, definite
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.substance, OLD.substance_code, OLD.generics, OLD.allergene, OLD.atc_code, OLD.fk_type, OLD.generic_specific, OLD.definite
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_allergy_state()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_allergy_state (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, has_allergy, comment, last_confirmed, fk_encounter
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.has_allergy, OLD.comment, OLD.last_confirmed, OLD.fk_encounter
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_atc_group()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_atc_group (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, code, description
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.code, OLD.description
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_atc_substance()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_atc_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, code, name, ddd_amount, fk_ddd_unit, route, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.code, OLD.name, OLD.ddd_amount, OLD.fk_ddd_unit, OLD.route, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_auto_hint()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_auto_hint (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, query, title, hint, url, is_active, source, lang, recommendation_query, popup_type, highlight_as_priority
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.query, OLD.title, OLD.hint, OLD.url, OLD.is_active, OLD.source, OLD.lang, OLD.recommendation_query, OLD.popup_type, OLD.highlight_as_priority
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_beh_fall_typ()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_beh_fall_typ (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, code, kurzform, name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.code, OLD.kurzform, OLD.name
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_behandlungsfall()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_behandlungsfall (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient, fk_falltyp, started, must_pay_prax_geb
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient, OLD.fk_falltyp, OLD.started, OLD.must_pay_prax_geb
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_bill()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_bill (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, invoice_id, close_date, apply_vat, fk_receiver_identity, fk_receiver_address, fk_doc, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.invoice_id, OLD.close_date, OLD.apply_vat, OLD.fk_receiver_identity, OLD.fk_receiver_address, OLD.fk_doc, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_bill_item()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_bill_item (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_provider, fk_encounter, date_to_bill, description, net_amount_per_unit, currency, status, fk_billable, fk_bill, unit_count, amount_multiplier
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_provider, OLD.fk_encounter, OLD.date_to_bill, OLD.description, OLD.net_amount_per_unit, OLD.currency, OLD.status, OLD.fk_billable, OLD.fk_bill, OLD.unit_count, OLD.amount_multiplier
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_clin_aux_note()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_clin_aux_note (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_clin_diag()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_clin_diag (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_narrative, laterality, is_chronic, is_active, is_definite, clinically_relevant
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_narrative, OLD.laterality, OLD.is_chronic, OLD.is_active, OLD.is_definite, OLD.clinically_relevant
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_clin_item_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_clin_item_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, type, code
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.type, OLD.code
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_clin_medication()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_clin_medication (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, last_prescribed, fk_last_script, discontinued, brandname, generic, adjuvant, dosage_form, ufk_drug, drug_db, atc_code, is_cr, dosage, period, dosage_unit, directions, is_prn
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.last_prescribed, OLD.fk_last_script, OLD.discontinued, OLD.brandname, OLD.generic, OLD.adjuvant, OLD.dosage_form, OLD.ufk_drug, OLD.drug_db, OLD.atc_code, OLD.is_cr, OLD.dosage, OLD.period, OLD.dosage_unit, OLD.directions, OLD.is_prn
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_clin_narrative()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_clin_narrative (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_coded_phrase()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_coded_phrase (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, term, code, xfk_coding_system
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.term, OLD.code, OLD.xfk_coding_system
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_consumable_substance()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_consumable_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, atc_code, amount, unit
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.atc_code, OLD.amount, OLD.unit
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_consumed_substance()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_consumed_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, atc_code
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.description, OLD.atc_code
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_data_source()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_data_source (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, name_long, name_short, version, description, source, lang
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.name_long, OLD.name_short, OLD.version, OLD.description, OLD.source, OLD.lang
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_doc_desc()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_doc_desc (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_doc, text
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_doc, OLD.text
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_doc_med()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_doc_med (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_encounter, fk_episode, fk_type, comment, clin_when, ext_ref, fk_org_unit, unit_is_receiver, fk_hospital_stay
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_encounter, OLD.fk_episode, OLD.fk_type, OLD.comment, OLD.clin_when, OLD.ext_ref, OLD.fk_org_unit, OLD.unit_is_receiver, OLD.fk_hospital_stay
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_dose()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_dose (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_substance, amount, unit, dose_unit
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_substance, OLD.amount, OLD.unit, OLD.dose_unit
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_drug_product()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_drug_product (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, preparation, atc_code, is_fake, fk_data_source, external_code, external_code_type
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.preparation, OLD.atc_code, OLD.is_fake, OLD.fk_data_source, OLD.external_code, OLD.external_code_type
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_encounter()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_encounter (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient, fk_type, fk_location, source_time_zone, reason_for_encounter, assessment_of_encounter, started, last_affirmed
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient, OLD.fk_type, OLD.fk_location, OLD.source_time_zone, OLD.reason_for_encounter, OLD.assessment_of_encounter, OLD.started, OLD.last_affirmed
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_episode()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_episode (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_health_issue, description, is_open, fk_encounter, diagnostic_certainty_classification, summary
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_health_issue, OLD.description, OLD.is_open, OLD.fk_encounter, OLD.diagnostic_certainty_classification, OLD.summary
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_external_care()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_external_care (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_encounter, fk_health_issue, issue, fk_org_unit, provider, comment, inactive
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_encounter, OLD.fk_health_issue, OLD.issue, OLD.fk_org_unit, OLD.provider, OLD.comment, OLD.inactive
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_family_history()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_family_history (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_relation_type, age_noted, age_of_death, contributed_to_death, name_relative, dob_relative, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_relation_type, OLD.age_noted, OLD.age_of_death, OLD.contributed_to_death, OLD.name_relative, OLD.dob_relative, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_fhx_relation_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_fhx_relation_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, is_genetic
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.is_genetic
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_form_data()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_form_data (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_instance, fk_form_field, value
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_instance, OLD.fk_form_field, OLD.value
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_form_defs()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_form_defs (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_type, country, locale, soap_cat, name_short, name_long, revision, template, engine, in_use, url, is_user
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_type, OLD.country, OLD.locale, OLD.soap_cat, OLD.name_short, OLD.name_long, OLD.revision, OLD.template, OLD.engine, OLD.in_use, OLD.url, OLD.is_user
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_form_instances()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_form_instances (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_form_def, form_name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_form_def, OLD.form_name
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_gender_label()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_gender_label (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, tag, label, sort_weight, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.tag, OLD.label, OLD.sort_weight, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_health_issue()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_health_issue (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, laterality, age_noted, is_active, clinically_relevant, is_confidential, is_cause_of_death, fk_encounter, grouping, diagnostic_certainty_classification, summary
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.laterality, OLD.age_noted, OLD.is_active, OLD.clinically_relevant, OLD.is_confidential, OLD.is_cause_of_death, OLD.fk_encounter, OLD.grouping, OLD.diagnostic_certainty_classification, OLD.summary
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_hospital_stay()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_hospital_stay (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, discharge, fk_org_unit
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.discharge, OLD.fk_org_unit
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_hx_family_item()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_hx_family_item (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_narrative_condition, fk_relative, name_relative, dob_relative, condition, age_noted, age_of_death, is_cause_of_death
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_narrative_condition, OLD.fk_relative, OLD.name_relative, OLD.dob_relative, OLD.condition, OLD.age_noted, OLD.age_of_death, OLD.is_cause_of_death
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_identity()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_identity (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, deleted, gender, dob, fk_marital_status, cob, deceased, title, tob, emergency_contact, fk_emergency_contact, comment, fk_primary_provider, dob_is_estimated
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.deleted, OLD.gender, OLD.dob, OLD.fk_marital_status, OLD.cob, OLD.deceased, OLD.title, OLD.tob, OLD.emergency_contact, OLD.fk_emergency_contact, OLD.comment, OLD.fk_primary_provider, OLD.dob_is_estimated
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_identity_tag()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_identity_tag (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, fk_tag, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.fk_tag, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_inbox_item_category()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_inbox_item_category (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, is_user
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.is_user
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_inbox_item_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_inbox_item_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_inbox_item_category, description, is_user
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_inbox_item_category, OLD.description, OLD.is_user
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_incoming_data_unmatchable()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_incoming_data_unmatchable (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient_candidates, request_id, firstnames, lastnames, dob, postcode, other_info, type, data, gender, requestor, external_data_id, fk_identity_disambiguated
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient_candidates, OLD.request_id, OLD.firstnames, OLD.lastnames, OLD.dob, OLD.postcode, OLD.other_info, OLD.type, OLD.data, OLD.gender, OLD.requestor, OLD.external_data_id, OLD.fk_identity_disambiguated
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_incoming_data_unmatched()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_incoming_data_unmatched (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient_candidates, request_id, firstnames, lastnames, dob, postcode, other_info, type, data, gender, requestor, external_data_id, fk_identity_disambiguated, comment, fk_provider_disambiguated
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient_candidates, OLD.request_id, OLD.firstnames, OLD.lastnames, OLD.dob, OLD.postcode, OLD.other_info, OLD.type, OLD.data, OLD.gender, OLD.requestor, OLD.external_data_id, OLD.fk_identity_disambiguated, OLD.comment, OLD.fk_provider_disambiguated
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lab_request()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lab_request (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_test_org, request_id, fk_requestor, lab_request_id, lab_rxd_when, results_reported_when, request_status, is_pending, diagnostic_service_section, ordered_service, note_test_org
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_test_org, OLD.request_id, OLD.fk_requestor, OLD.lab_request_id, OLD.lab_rxd_when, OLD.results_reported_when, OLD.request_status, OLD.is_pending, OLD.diagnostic_service_section, OLD.ordered_service, OLD.note_test_org
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lab_test_gnr()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lab_test_gnr (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_test
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_test
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_code2aoe()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_code2aoe (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_code2episode()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_code2episode (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_code2fhx()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_code2fhx (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_code2h_issue()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_code2h_issue (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_code2narrative()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_code2narrative (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_code2procedure()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_code2procedure (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_code2rfe()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_code2rfe (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_code2tst_pnl()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_code2tst_pnl (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_lnk_code2item, fk_generic_code, fk_item, code_modifier, pk
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_lnk_code2item, OLD.fk_generic_code, OLD.fk_item, OLD.code_modifier, OLD.pk
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_constraint2vacc_course()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_constraint2vacc_course (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_vaccination_course, fk_constraint
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_vaccination_course, OLD.fk_constraint
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_dose2drug()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_dose2drug (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_drug_product, fk_dose
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_drug_product, OLD.fk_dose
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_identity2ext_id()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_identity2ext_id (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_identity, external_id, fk_origin, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_identity, OLD.external_id, OLD.fk_origin, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_identity2primary_doc()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_identity2primary_doc (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, fk_primary_doc
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.fk_primary_doc
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_job2person()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_job2person (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, fk_occupation, activities
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.fk_occupation, OLD.activities
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_loinc2substance()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_loinc2substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_substance, loinc, max_age, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_substance, OLD.loinc, OLD.max_age, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_loinc2test_panel()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_loinc2test_panel (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_test_panel, loinc
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_test_panel, OLD.loinc
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_org_unit2comm()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_org_unit2comm (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_org_unit, url, fk_type, is_confidential, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_org_unit, OLD.url, OLD.fk_type, OLD.is_confidential, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_org_unit2ext_id()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_org_unit2ext_id (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_org_unit, external_id, fk_type, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_org_unit, OLD.external_id, OLD.fk_type, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_pat2vaccination_course()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_pat2vaccination_course (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient, fk_course
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient, OLD.fk_course
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_person2relative()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_person2relative (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_identity, id_relative, id_relation_type, started, ended
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_identity, OLD.id_relative, OLD.id_relation_type, OLD.started, OLD.ended
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_substance2brand()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_substance2brand (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_brand, fk_substance
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_brand, OLD.fk_substance
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_tst2norm()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_tst2norm (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_test, id_norm
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_test, OLD.id_norm
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_type2item()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_type2item (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_type, fk_item
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_type, OLD.fk_item
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_vaccination_course2schedule()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_vaccination_course2schedule (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_course, fk_schedule
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_course, OLD.fk_schedule
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_vaccine2inds()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_lnk_vaccine2inds (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, fk_vaccine, fk_indication
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.fk_vaccine, OLD.fk_indication
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_message_inbox()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_message_inbox (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_staff, fk_inbox_item_type, comment, data, importance, fk_patient, ufk_context, due_date, expiry_date
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_staff, OLD.fk_inbox_item_type, OLD.comment, OLD.data, OLD.importance, OLD.fk_patient, OLD.ufk_context, OLD.due_date, OLD.expiry_date
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_occupation()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_occupation (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.name
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_operation()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_operation (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_health_issue, fk_encounter, clin_where, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_health_issue, OLD.fk_encounter, OLD.clin_where, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_org()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_org (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, fk_category, fk_data_source
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.fk_category, OLD.fk_data_source
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_org_unit()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_org_unit (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, fk_org, fk_address, fk_category
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.fk_org, OLD.fk_address, OLD.fk_category
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_paperwork_templates()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_paperwork_templates (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_template_type, instance_type, name_short, name_long, external_version, gnumed_revision, engine, in_use, filename, data, edit_after_substitution
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_template_type, OLD.instance_type, OLD.name_short, OLD.name_long, OLD.external_version, OLD.gnumed_revision, OLD.engine, OLD.in_use, OLD.filename, OLD.data, OLD.edit_after_substitution
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_patient()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_patient (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, edc
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.edc
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_prax_geb_paid()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_prax_geb_paid (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_fall, paid_amount, paid_when, paid_with
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_fall, OLD.paid_amount, OLD.paid_when, OLD.paid_with
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_praxis_branch()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_praxis_branch (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_org_unit
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_org_unit
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_procedure()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_procedure (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_hospital_stay, clin_end, is_ongoing, fk_org_unit, fk_doc, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_hospital_stay, OLD.clin_end, OLD.is_ongoing, OLD.fk_org_unit, OLD.fk_doc, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_ref_source()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_ref_source (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, name_short, name_long, version, description, source
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.name_short, OLD.name_long, OLD.version, OLD.description, OLD.source
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_referral()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_referral (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, id, fk_referee, fk_form
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.id, OLD.fk_referee, OLD.fk_form
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_region()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_region (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, code, country, name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.code, OLD.country, OLD.name
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_relation_types()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_relation_types (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, inverse, biological, biol_verified, description
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.inverse, OLD.biological, OLD.biol_verified, OLD.description
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_report_query()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_report_query (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, label, cmd
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.label, OLD.cmd
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_staff()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_staff (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_identity, db_user, short_alias, comment, is_active
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_identity, OLD.db_user, OLD.short_alias, OLD.comment, OLD.is_active
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_staff_role()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_staff_role (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, name, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.name, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_street()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_street (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, id_urb, name, postcode, suburb, lat_lon
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.id_urb, OLD.name, OLD.postcode, OLD.suburb, OLD.lat_lon
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_substance()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, atc, intake_instructions
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.atc, OLD.intake_instructions
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_substance_in_brand()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_substance_in_brand (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_brand, description, atc_code
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_brand, OLD.description, OLD.atc_code
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_substance_intake()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_substance_intake (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, schedule, aim, duration, intake_is_approved_of, is_long_term, discontinued, discontinue_reason, fk_drug_component, comment_on_start, harmful_use_type
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.schedule, OLD.aim, OLD.duration, OLD.intake_is_approved_of, OLD.is_long_term, OLD.discontinued, OLD.discontinue_reason, OLD.fk_drug_component, OLD.comment_on_start, OLD.harmful_use_type
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_suppressed_hint()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_suppressed_hint (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_encounter, fk_hint, suppressed_by, suppressed_when, rationale, md5_sum
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_encounter, OLD.fk_hint, OLD.suppressed_by, OLD.suppressed_when, OLD.rationale, OLD.md5_sum
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_tag_image()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_tag_image (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, filename, image
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.filename, OLD.image
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_test_org()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_test_org (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_org_unit, fk_adm_contact, fk_med_contact, comment, contact
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_org_unit, OLD.fk_adm_contact, OLD.fk_med_contact, OLD.comment, OLD.contact
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_test_panel()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_test_panel (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_test_result()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_test_result (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_type, val_num, val_alpha, val_unit, val_normal_min, val_normal_max, val_normal_range, val_target_min, val_target_max, val_target_range, abnormality_indicator, norm_ref_group, note_test_org, material, material_detail, fk_intended_reviewer, fk_request, status, source_data, val_grouping
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_type, OLD.val_num, OLD.val_alpha, OLD.val_unit, OLD.val_normal_min, OLD.val_normal_max, OLD.val_normal_range, OLD.val_target_min, OLD.val_target_max, OLD.val_target_range, OLD.abnormality_indicator, OLD.norm_ref_group, OLD.note_test_org, OLD.material, OLD.material_detail, OLD.fk_intended_reviewer, OLD.fk_request, OLD.status, OLD.source_data, OLD.val_grouping
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_test_type()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_test_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_test_org, name, comment, reference_unit, loinc, abbrev, fk_meta_test_type
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_test_org, OLD.name, OLD.comment, OLD.reference_unit, OLD.loinc, OLD.abbrev, OLD.fk_meta_test_type
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_urb()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_urb (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, fk_region, postcode, lat_lon, name
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.fk_region, OLD.postcode, OLD.lat_lon, OLD.name
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vacc_indication()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_vacc_indication (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, description, atcs_single_indication, atcs_combi_indication
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.description, OLD.atcs_single_indication, OLD.atcs_combi_indication
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vacc_route()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_vacc_route (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, abbreviation, description
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.abbreviation, OLD.description
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccination()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_vaccination (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_provider, fk_vaccine, site, batch_no, reaction
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_item, OLD.clin_when, OLD.fk_encounter, OLD.fk_episode, OLD.narrative, OLD.soap_cat, OLD.pk, OLD.fk_provider, OLD.fk_vaccine, OLD.site, OLD.batch_no, OLD.reaction
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccination_course()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_vaccination_course (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_recommended_by, fk_indication, is_active, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_recommended_by, OLD.fk_indication, OLD.is_active, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccination_course_constraint()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_vaccination_course_constraint (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, description
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.description
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccination_definition()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_vaccination_definition (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		id, fk_course, is_booster, seq_no, min_age_due, max_age_due, min_interval, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.id, OLD.fk_course, OLD.is_booster, OLD.seq_no, OLD.min_age_due, OLD.max_age_due, OLD.min_interval, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccination_schedule()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_vaccination_schedule (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, name, comment
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.name, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccine()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_vaccine (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, id_route, is_live, min_age, max_age, comment, fk_drug_product
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.id_route, OLD.is_live, OLD.min_age, OLD.max_age, OLD.comment, OLD.fk_drug_product
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccine_batches()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_vaccine_batches (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_vaccine, batch_no
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_vaccine, OLD.batch_no
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_waiting_list()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_is_allowed_updater boolean;
    BEGIN
    	-- is the session user allowed to update data ?
    	SELECT gm.account_is_dbowner_or_staff(SESSION_USER) INTO STRICT _is_allowed_updater;
    	IF _is_allowed_updater IS FALSE THEN
    		RAISE EXCEPTION
    			'UPDATE: gm.account_is_dbowner_or_staff(NAME): <%> is neither database owner, nor <postgres>, nor on staff', SESSION_USER
    			USING ERRCODE = 'integrity_constraint_violation'
    		;
    		return NEW;
    	END IF;
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_waiting_list (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk, fk_patient, registered, urgency, list_position, comment, area
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk, OLD.fk_patient, OLD.registered, OLD.urgency, OLD.list_position, OLD.comment, OLD.area
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_xlnk_identity()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	NEW.row_version := OLD.row_version + 1;
    	NEW.modified_when := CURRENT_TIMESTAMP;
    	NEW.modified_by := SESSION_USER;
    	INSERT INTO audit.log_xlnk_identity (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, xfk_identity, pupic, data
    	) VALUES (
    		OLD.row_version, OLD.modified_when, OLD.modified_by, TG_RELID, TG_OP,
    		OLD.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.xfk_identity, OLD.pupic, OLD.data
    	);
    	return NEW;
    END;

## Function: audit.register_table_for_auditing(name, name)

### Returns: boolean

### Language: PLPGSQL

sanity-checking convenience function for registering a table for auditing

    DECLARE
    	_schema alias for $1;
    	_table alias for $2;
    BEGIN
    	-- does table exist ?
    	perform 1 from pg_class where
    		relname = _table
    			and
    		relnamespace = (select oid from pg_namespace where nspname = _schema)
    	;
    	if not found then
    		raise exception 'audit.register_table_for_auditing(): table [%.%] does not exist', _schema, _table;
    		return false;
    	end if;
    	-- already queued for auditing ?
    	perform 1 from audit.audited_tables where
    		table_name = _table
    			and
    		schema = _schema;
    	if found then
    		return true;
    	end if;
    	-- add definition
    	insert into audit.audited_tables (
    		schema, table_name
    	) values (
    		_schema, _table
    	);
    	return true;
    END;

# Schema bill

Holds everything related to billing.

## Table: bill.bill

actual bills

bill.bill Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| invoice_id |  | UNIQUE
| pk |  | PRIMARY KEY
blobs.doc_med.pk | fk_doc |  |
dem.identity.pk | fk_receiver_identity |  |
dem.lnk_person_org_address.id | fk_receiver_address |  |

Table bill.bill Inherits audit_fields,

bill.bill Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
bill_bill_sane_apply_vat | CHECK (((apply_vat IS NOT NULL) OR ((apply_vat IS NULL) AND (fk_doc IS NULL))))
bill_bill_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
bill_bill_sane_invoice_id | CHECK ((gm.is_null_or_blank_string(invoice_id) IS FALSE))
bill_bill_sane_recv_adr | CHECK (((fk_receiver_address IS NOT NULL) OR (close_date IS NULL)))

Tables referencing this one via Foreign Key Constraints:

- bill.bill_item

Index - Schema bill

## Table: bill.bill_item

items patients currently *are* billed for

bill.bill_item Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
bill.bill.pk | fk_bill |  |
ref.billable.pk | fk_billable |  |
dem.staff.pk | fk_provider |  |
clin.encounter.pk | fk_encounter |  |

Table bill.bill_item Inherits audit_fields,

bill.bill_item Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
bill_bill_item_sane_count | CHECK ((unit_count > '-1'::integer))
bill_bill_item_sane_currency | CHECK ((gm.is_null_or_blank_string(currency) IS FALSE))
bill_bill_item_sane_desc | CHECK ((gm.is_null_or_non_empty_string(description) IS TRUE))
bill_bill_item_sane_multiplier | CHECK ((amount_multiplier > (0)::numeric))
valid_stati | CHECK ((status = ANY (ARRAY['new'::text, 'transferred'::text])))

idx_bill_bill_item_fk_bill fk_bill idx_bill_bill_item_fk_billable fk_billable

Index - Schema bill

## Table: bill.lnk_enc_type2billable

actual bills

bill.lnk_enc_type2billable Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter_type.pk | fk_encounter_type |  |
ref.billable.pk | fk_billable |  |
| pk |  | PRIMARY KEY

idx_lnk_enc_type2billable_fk_billable fk_billable idx_lnk_enc_type2billable_fk_encounter_type fk_encounter_type

Index - Schema bill

## View: bill.v_bill_items

bill.v_bill_items Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT b_bi.pk AS pk_bill_item
    ,
        r_b.code AS billable_code
    ,
        r_b.term AS billable_description
    ,
        b_bi.description AS item_detail
    ,
        COALESCE
    (
         (b_bi.date_to_bill)::timestamp with time zone
         , c_enc.started
    ) AS date_to_bill
    ,
        b_bi.net_amount_per_unit
    ,
        b_bi.unit_count
    ,
        b_bi.amount_multiplier
    ,

    (
         (
               (b_bi.unit_count)::numeric * b_bi.net_amount_per_unit
         ) * b_bi.amount_multiplier
    ) AS total_amount
    ,

    (
         (
               (
                     (b_bi.unit_count)::numeric * b_bi.net_amount_per_unit
               ) * b_bi.amount_multiplier
         ) * r_b.vat_multiplier
    ) AS vat
    ,
        b_bi.currency
    ,
        b_bi.date_to_bill AS raw_date_to_bill
    ,
        r_b.amount AS billable_amount
    ,
        r_b.vat_multiplier
    ,
        r_b.currency AS billable_currency
    ,
        r_b.comment AS billable_comment
    ,
        r_b.active AS billable_active
    ,
        r_b.discountable AS billable_discountable
    ,
        r_ds.name_long AS catalog_long
    ,
        r_ds.name_short AS catalog_short
    ,
        r_ds.version AS catalog_version
    ,
        r_ds.lang AS catalog_language
    ,
        c_enc.fk_patient AS pk_patient
    ,
        c_enc.fk_type AS pk_encounter_type
    ,
        b_bi.fk_provider AS pk_provider
    ,
        b_bi.fk_encounter AS pk_encounter_to_bill
    ,
        b_bi.fk_bill AS pk_bill
    ,
        r_b.pk AS pk_billable
    ,
        r_b.fk_data_source AS pk_data_source
    ,
        b_bi.xmin AS xmin_bill_item

    FROM (
         (
               (bill.bill_item b_bi

                  JOIN ref.billable r_b
                    ON (
                           (b_bi.fk_billable = r_b.pk)
                     )
               )

       LEFT JOIN ref.data_source r_ds
              ON (
                     (r_b.fk_data_source = r_ds.pk)
               )
         )

    LEFT JOIN clin.encounter c_enc
        ON (
               (b_bi.fk_encounter = c_enc.pk)
         )
    );

Index - Schema bill

## View: bill.v_bills

bill.v_bills Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT b_b.pk AS pk_bill
    ,
        b_b.invoice_id
    ,
        b_b.fk_receiver_identity AS pk_receiver_identity
    ,

    (
    SELECT round
         (sum
               (v_bill_items.total_amount)
               , 2
         ) AS round

      FROM bill.v_bill_items

     WHERE (v_bill_items.pk_bill = b_b.pk)
    ) AS total_amount
    ,

    (
    SELECT round
         (sum
               (v_bill_items.vat)
               , 2
         ) AS round

      FROM bill.v_bill_items

     WHERE (v_bill_items.pk_bill = b_b.pk)
    ) AS total_vat
    ,

    (
    SELECT round
         (sum
               (
                     (v_bill_items.total_amount + v_bill_items.vat)
               )
               , 2
         ) AS round

      FROM bill.v_bill_items

     WHERE (v_bill_items.pk_bill = b_b.pk)
    ) AS total_amount_with_vat
    ,

    (
    SELECT (v_bill_items.vat_multiplier *
               (100)::numeric
         )

      FROM bill.v_bill_items

     WHERE (v_bill_items.pk_bill = b_b.pk)
             LIMIT 1
    ) AS percent_vat
    ,

    (
    SELECT v_bill_items.currency

      FROM bill.v_bill_items

     WHERE (v_bill_items.pk_bill = b_b.pk)
             LIMIT 1
    ) AS currency
    ,
        b_b.close_date
    ,
        b_b.apply_vat
    ,
        b_b.comment
    ,
        b_b.fk_receiver_address AS pk_receiver_address
    ,
        b_b.fk_doc AS pk_doc
    ,

    (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk =
               (
                SELECT bill_item.fk_encounter

                  FROM bill.bill_item

                 WHERE (bill_item.fk_bill = b_b.pk)
                     LIMIT 1
               )
         )
    ) AS pk_patient
    ,

    (
    SELECT array_agg
         (sorted_values.pk_bill_item) AS array_agg

      FROM (
          SELECT b_vbi.pk_bill_item

            FROM bill.v_bill_items b_vbi

           WHERE (b_vbi.pk_bill = b_b.pk)

        ORDER BY b_vbi.date_to_bill
               , b_vbi.billable_code
         ) sorted_values
    ) AS pk_bill_items
    ,
        b_b.xmin AS xmin_bill

    FROM bill.bill b_b;

Index - Schema bill

## Function: bill.get_bill_receiver_identity(integer)

### Returns: integer

### Language: SQL

    select
    	value
    from (
    	select
    		id.pk_id,
    		id.value::integer
    	from
    		dem.v_external_ids4identity id
    			join dem.identity d_i on (id.value = d_i.pk::text)
    	where
    		id.pk_type = (select pk from dem.enum_ext_id_types where name = 'bill receiver' and issuer = 'GNUmed')
    			and
    		id.pk_identity = $1
    	union all
    	select
    		0,
    		$1
    ) me
    limit 1;

## Function: bill.trf_prevent_empty_bills()

### Returns: trigger

### Language: PLPGSQL

Prevent bills to become void of items due to deletions/updates of bill items.

    DECLARE
    	_item_count integer;
    	_msg text;
    BEGIN
    	if TG_OP = 'UPDATE' then
    		if OLD.fk_bill IS NULL then
    			return NULL;
    		end if;
    		if OLD.fk_bill IS NOT DISTINCT FROM NEW.fk_bill then
    			return NULL;
    		end if;
    	else
    		if OLD.fk_bill is NULL then
    			return NULL;
    		end if;
    	end if;
    	-- we now either:
    	--	DELETE with .fk_bill NOT NULL
    	-- or:
    	--	UPDATE with an .fk_bill change (including towards fk_bill = NULL)
    	-- let us check whether the (previous) bill still exists
    	-- at all or whether we are deleting the bill (and thereby
    	-- setting our .fk_bill to NULL)
    	-- only works at or below REPEATABLE READ after deletion of bill
    	perform 1 from bill.bill where pk = OLD.fk_bill;
    	if FOUND is FALSE then
    		return NULL;
    	end if;
    	select count(1) into _item_count
    	from bill.bill_item
    	where
    		fk_bill = OLD.fk_bill
    			and
    		pk != OLD.pk;
    	if _item_count > 0 then
    		return NULL;
    	end if;
    	_msg := '[bill.trf_prevent_empty_bills]: cannot remove (by '
    			|| '<' || TG_OP || '>'
    			||') the only item (bill.bill_item.pk='
    			|| coalesce(OLD.pk::text, '<NULL>'::text)
    			|| ') from bill (bill.bill_item.fk_bill=bill.bill.pk='
    			|| coalesce(OLD.fk_bill::text, '<NULL>'::text)
    			|| ') ';
    	raise exception unique_violation using message = _msg;
    	return NULL;
    END;

## Function: bill.trf_prevent_mislinked_bills()

### Returns: trigger

### Language: PLPGSQL

Prevent bills to link to invoices of another patient.

    DECLARE
    	_doc_patient integer;
    	_bill_patient integer;
    	_msg text;
    BEGIN
    	if NEW.fk_doc IS NULL then
    		return NEW;
    	end if;
    	if TG_OP = 'UPDATE' then
    		if OLD.fk_doc IS NOT DISTINCT FROM NEW.fk_doc then
    			return NEW;
    		end if;
    	end if;
    	-- we now either:
    	--	INSERT with .fk_doc NOT NULL
    	-- or:
    	--	UPDATE with an .fk_bill change to a NON-NULL value
    	select pk_patient into _doc_patient
    	from blobs.v_doc_med
    	where
    		pk_doc = NEW.fk_doc;
    	select pk_patient into _bill_patient
    	from bill.v_bills
    	where
    		pk_bill = NEW.pk;
    	if _doc_patient = _bill_patient then
    		return NEW;
    	end if;
    	_msg := '[bill.trf_prevent_mislinked_bills]: patient mismatch between '
    		|| 'bill (pk=' || NEW.pk || ', patient=' || _bill_patient || ') '
    		|| 'and invoice (pk=' || NEW.fk_doc || ', patient=' || _doc_patient || ')';
    	raise exception integrity_constraint_violation using message = _msg;
    	return NULL;
    END;

# Schema blobs

## Table: blobs.doc_desc

A textual description of the content such as a result summary. Several of these may belong to one document object.

blobs.doc_desc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
blobs.doc_med.pk | fk_doc |  | UNIQUE#1
| text |  | UNIQUE#1
| pk |  | PRIMARY KEY

Table blobs.doc_desc Inherits audit_fields,

blobs.doc_desc Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_doc_desc_fk_doc fk_doc

Index - Schema blobs

## Table: blobs.doc_med

a medical document object possibly containing several data objects such as several pages of a paper document

blobs.doc_med Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
blobs.doc_type.pk | fk_type |  |
clin.episode.pk | fk_episode |  |
| pk |  | PRIMARY KEY
dem.org_unit.pk | fk_org_unit |  |

Table blobs.doc_med Inherits audit_fields,

blobs.doc_med Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- bill.bill

- blobs.doc_desc

- blobs.doc_obj

- blobs.lnk_doc_med2episode

- clin.procedure

Index - Schema blobs

## Table: blobs.doc_obj

possibly several of these form a medical document such as multiple scanned pages/images

blobs.doc_obj Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
blobs.doc_med.pk | fk_doc |  |
dem.staff.pk | fk_intended_reviewer |  |

blobs.doc_obj Constraints
Name | Constraint
--- | ---
doc_obj_filename_check | CHECK ((btrim(COALESCE(filename, 'NULL'::text)) <> ''::text))

Tables referencing this one via Foreign Key Constraints:

- blobs.reviewed_doc_objs

- clin.export_item

Index - Schema blobs

## Table: blobs.doc_type

this table enumerates the document types known to the system

blobs.doc_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| name |  | UNIQUE
| pk |  | PRIMARY KEY

Tables referencing this one via Foreign Key Constraints:

- blobs.doc_med

Index - Schema blobs

## Table: blobs.lnk_doc_med2episode

this allows linking documents to episodes, each document can apply to several episodes but only once each

blobs.lnk_doc_med2episode Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
blobs.doc_med.pk | fk_doc_med |  | UNIQUE#1
clin.episode.pk | fk_episode |  | UNIQUE#1

Table blobs.lnk_doc_med2episode Inherits audit_fields,

blobs.lnk_doc_med2episode Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema blobs

## Table: blobs.reviewed_doc_objs

review table for documents (per object such as a page)

blobs.reviewed_doc_objs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| fk_reviewer |  | UNIQUE#1
blobs.doc_obj.pk | fk_reviewed_row |  | UNIQUE#1
| pk |  | PRIMARY KEY

Table blobs.reviewed_doc_objs Inherits review_root,

blobs.reviewed_doc_objs Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema blobs

## View: blobs.v_doc_desc

aggregates some document data descriptions

blobs.v_doc_desc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT vdm.pk_patient
    ,
        dd.fk_doc AS pk_doc
    ,
        dd.text AS description
    ,
        vdm.pk_encounter
    ,
        vdm.pk_episode
    ,
        vdm.pk_health_issue
    ,
        dd.pk AS pk_doc_desc

    FROM blobs.doc_desc dd
    ,
        blobs.v_doc_med vdm

    WHERE (dd.fk_doc = vdm.pk_doc);

Index - Schema blobs

## View: blobs.v_doc_med

blobs.v_doc_med Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        b_dm.pk AS pk_doc
    ,
        b_dm.clin_when
    ,
        b_dt.name AS type
    ,
        _
    (b_dt.name) AS l10n_type
    ,
        b_dm.ext_ref
    ,
        b_dm.comment
    ,
        c_epi.description AS episode
    ,
        c_hi.description AS health_issue
    ,
        c_epi.is_open AS episode_open
    ,
        d_ou.description AS unit
    ,
        d_o.description AS organization
    ,
        b_dm.unit_is_receiver
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (b_do.seq_idx) AS array_agg

            FROM blobs.doc_obj b_do

           WHERE (b_do.fk_doc = b_dm.pk)
         )
         , ARRAY[]::integer[]
    ) AS seq_idx_list
    ,
        b_dm.fk_type AS pk_type
    ,
        b_dm.fk_encounter AS pk_encounter
    ,
        b_dm.fk_episode AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        d_ou.fk_org AS pk_org
    ,
        b_dm.fk_hospital_stay AS pk_hospital_stay
    ,
        b_dm.fk_org_unit AS pk_org_unit
    ,
        b_dm.modified_when
    ,
        b_dm.modified_by
    ,
        b_dm.xmin AS xmin_doc_med

    FROM (
         (
               (
                     (
                           (
                                 (blobs.doc_med b_dm

                                    JOIN blobs.doc_type b_dt
                                      ON (
                                             (b_dm.fk_type = b_dt.pk)
                                       )
                                 )

                              JOIN clin.encounter c_enc
                                ON (
                                       (b_dm.fk_encounter = c_enc.pk)
                                 )
                           )

                        JOIN clin.episode c_epi
                          ON (
                                 (b_dm.fk_episode = c_epi.pk)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_hi.pk = c_epi.fk_health_issue)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (b_dm.fk_org_unit = d_ou.pk)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_ou.fk_org = d_o.pk)
         )
    );

Index - Schema blobs

## View: blobs.v_doc_med_journal

blobs.v_doc_med_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        b_dm.modified_when
    ,
        b_dm.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = b_dm.modified_by)
         )
         , (
               ('<'::text ||
                     (b_dm.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        NULL::text AS soap_cat
    ,

    ('"'::text ||
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (_
                                                                                             (b_dt.name) || '" '::text
                                                                                       ) || _
                                                                                       ('with'::text)
                                                                                 ) || ' '::text
                                                                           ) ||
                                                                           (
                                                                            SELECT count
                                                                                 (1) AS count

                                                                              FROM blobs.doc_obj b_do

                                                                             WHERE (b_do.fk_doc = b_dm.pk)
                                                                           )
                                                                     ) || ' '::text
                                                               ) || _
                                                               ('part(s)'::text
                                                         )
                                                   ) || '
    '::text
                                             ) || ' '::text
                                       ) || to_char
                                       (b_dm.clin_when
                                             ,'YYYY-MM-DD HH24:MI'::text
                                       )
                                 ) || '
    '::text
                           ) || COALESCE
                           (
                                 (
                                       (' ['::text || b_dm.ext_ref) || ']'::text
                                 )
                                 ,''::text
                           )
                     ) ||
            CASE
                WHEN b_dm.unit_is_receiver THEN COALESCE
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (' '::text || _
                                                               ('sent to'::text)
                                                         ) || d_ou.description
                                                   ) || ' '::text
                                             ) || _
                                             ('of'::text)
                                       ) || ' '::text
                                 ) || d_o.description
                           )
                           ,''::text
                     )
                ELSE COALESCE
                     (
                           (
                                 (
                                       (
                                             (
                                                   (' @ '::text || d_ou.description) || ' '::text
                                             ) || _
                                             ('of'::text)
                                       ) || ' '::text
                                 ) || d_o.description
                           )
                           ,''::text
                     )
            END
               ) || '
    '::text
         ) || COALESCE
         (
               (' '::text || b_dm.comment)
               ,''::text
         )
    )
    )      AS narrative
    ,
        b_dm.fk_encounter AS pk_encounter
    ,
        b_dm.fk_episode AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        b_dm.pk AS src_pk
    ,
        'blobs.doc_med'::text AS src_table
    ,
        b_dm.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (     c_ety.description) AS encounter_l10n_type

    FROM   (
    (
         (
               (
                     (
                           (
                                 (blobs.doc_med b_dm

                                    JOIN clin.encounter c_enc
                                      ON (
                                             (b_dm.fk_encounter = c_enc.pk)
                                       )
                                 )

                              JOIN clin.encounter_type c_ety
                                ON (
                                       (c_enc.fk_type = c_ety.pk)
                                 )
                           )

                        JOIN blobs.doc_type b_dt
                          ON (
                                 (b_dm.fk_type = b_dt.pk)
                           )
                     )

                  JOIN clin.episode c_epi
                    ON (
                           (b_dm.fk_episode = c_epi.pk)
                     )
               )

       LEFT JOIN clin.health_issue c_hi
              ON (
                     (c_epi.fk_health_issue = c_hi.pk)
               )
         )

    LEFT JOIN dem.org_unit d_ou
        ON (
               (b_dm.fk_org_unit = d_ou.pk)
         )
    )

    LEFT JOIN dem.org d_o
    ON (
         (d_ou.fk_org = d_o.pk)
    )
    )     ;

Index - Schema blobs

## View: blobs.v_doc_type

list active document types, those that are activated for use

blobs.v_doc_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT dt.pk AS pk_doc_type
    ,
        dt.name AS type
    ,
        _
    (dt.name) AS l10n_type
    ,

    (NOT
         (EXISTS
               (
                SELECT 1

                  FROM ref.document_type

                 WHERE (document_type.description = dt.name)
               )
         )
    ) AS is_user_defined
    ,

    (EXISTS
         (
          SELECT 1

            FROM blobs.doc_med

           WHERE (doc_med.fk_type = dt.pk)
         )
    ) AS is_in_use
    ,
        dt.xmin AS xmin_doc_type

    FROM blobs.doc_type dt;

Index - Schema blobs

## View: blobs.v_latest_mugshot

shows the latest picture of the patient, currently the highest seq_idx of the newest document of type "patient photograph"

blobs.v_latest_mugshot Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT b_vo4d.pk_patient
    ,
        b_vo4d.doc_comment
    ,
        b_vo4d.date_generated AS date_taken
    ,
        b_vo4d.ext_ref
    ,
        b_vo4d.seq_idx AS obj_seq_idx
    ,
        b_vo4d.obj_comment
    ,
        b_vo4d.pk_doc
    ,
        b_vo4d.pk_obj
    ,
        b_do.data AS image

    FROM blobs.v_obj4doc_no_data b_vo4d
    ,
        blobs.doc_obj b_do

    WHERE (
         (b_vo4d.type = 'patient photograph'::text)
       AND (b_vo4d.seq_idx =
               (
                SELECT max
                     (b_vo4d1.seq_idx) AS max

                  FROM blobs.v_obj4doc_no_data b_vo4d1

                 WHERE (
                           (b_vo4d1.pk_patient = b_vo4d.pk_patient)
                         AND (b_vo4d1.type = 'patient photograph'::text)
                     )

              GROUP BY b_vo4d1.date_generated

              ORDER BY b_vo4d1.date_generated DESC
             LIMIT 1
               )
         )
       AND (b_do.pk = b_vo4d.pk_obj)
    );

Index - Schema blobs

## View: blobs.v_obj4doc_no_data

denormalized metadata for blobs.doc_obj but without the data itself

blobs.v_obj4doc_no_data Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT b_vdm.pk_patient
    ,
        b_do.pk AS pk_obj
    ,
        b_do.seq_idx
    ,
        octet_length
    (COALESCE
         (b_do.data
               ,'\x'::bytea
         )
    ) AS size
    ,
        b_vdm.clin_when AS date_generated
    ,
        b_vdm.type
    ,
        b_vdm.l10n_type
    ,
        b_vdm.ext_ref
    ,
        b_vdm.episode
    ,
        b_vdm.comment AS doc_comment
    ,
        b_do.comment AS obj_comment
    ,
        b_do.filename
    ,
        b_do.fk_intended_reviewer AS pk_intended_reviewer
    ,

    (EXISTS
         (
          SELECT 1

            FROM blobs.reviewed_doc_objs

           WHERE (reviewed_doc_objs.fk_reviewed_row = b_do.pk)
         )
    ) AS reviewed
    ,

    (EXISTS
         (
          SELECT 1

            FROM blobs.reviewed_doc_objs

           WHERE (
                     (reviewed_doc_objs.fk_reviewed_row = b_do.pk)
                   AND (reviewed_doc_objs.fk_reviewer =
                           (
                            SELECT staff.pk

                              FROM dem.staff

                             WHERE (staff.db_user = "current_user"
                                       ()
                                 )
                           )
                     )
               )
         )
    ) AS reviewed_by_you
    ,

    (EXISTS
         (
          SELECT 1

            FROM blobs.reviewed_doc_objs

           WHERE (
                     (reviewed_doc_objs.fk_reviewed_row = b_do.pk)
                   AND (reviewed_doc_objs.fk_reviewer = b_do.fk_intended_reviewer)
               )
         )
    ) AS reviewed_by_intended_reviewer
    ,
        b_vdm.pk_doc
    ,
        b_vdm.pk_type
    ,
        b_vdm.pk_encounter
    ,
        b_vdm.pk_episode
    ,
        b_vdm.pk_health_issue
    ,
        b_vdm.pk_org
    ,
        b_vdm.pk_org_unit
    ,
        b_vdm.pk_hospital_stay
    ,
        b_do.xmin AS xmin_doc_obj

    FROM (blobs.v_doc_med b_vdm

      JOIN blobs.doc_obj b_do
        ON (
               (b_do.fk_doc = b_vdm.pk_doc)
         )
    )

    WHERE (b_vdm.pk_doc = b_do.fk_doc);

Index - Schema blobs

## View: blobs.v_reviewed_doc_objects

blobs.v_reviewed_doc_objects Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT rdo.fk_reviewed_row AS pk_doc_obj
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.pk = rdo.fk_reviewer)
         )
         , (
               ('<#'::text || rdo.fk_reviewer) || '>'::text
         )
    ) AS reviewer
    ,
        rdo.is_technically_abnormal
    ,
        rdo.clinically_relevant
    ,

    (EXISTS
         (
          SELECT 1

            FROM blobs.doc_obj

           WHERE (
                     (doc_obj.pk = rdo.fk_reviewed_row)
                   AND (doc_obj.fk_intended_reviewer = rdo.fk_reviewer)
               )
         )
    ) AS is_review_by_responsible_reviewer
    ,

    (EXISTS
         (
          SELECT 1

            FROM dem.staff

           WHERE (
                     (staff.pk = rdo.fk_reviewer)
                   AND (staff.db_user = "current_user"
                           ()
                     )
               )
         )
    ) AS is_your_review
    ,
        rdo.comment
    ,
        rdo.modified_when AS reviewed_when
    ,
        rdo.modified_by
    ,
        rdo.pk AS pk_review_root
    ,
        rdo.fk_reviewer AS pk_reviewer
    ,

    (
    SELECT v_obj4doc_no_data.pk_patient

      FROM blobs.v_obj4doc_no_data

     WHERE (v_obj4doc_no_data.pk_obj = rdo.fk_reviewed_row)
    ) AS pk_patient
    ,

    (
    SELECT v_obj4doc_no_data.pk_encounter

      FROM blobs.v_obj4doc_no_data

     WHERE (v_obj4doc_no_data.pk_obj = rdo.fk_reviewed_row)
    ) AS pk_encounter
    ,

    (
    SELECT v_obj4doc_no_data.pk_episode

      FROM blobs.v_obj4doc_no_data

     WHERE (v_obj4doc_no_data.pk_obj = rdo.fk_reviewed_row)
    ) AS pk_episode
    ,

    (
    SELECT v_obj4doc_no_data.pk_health_issue

      FROM blobs.v_obj4doc_no_data

     WHERE (v_obj4doc_no_data.pk_obj = rdo.fk_reviewed_row)
    ) AS pk_health_issue

    FROM blobs.reviewed_doc_objs rdo;

Index - Schema blobs

## View: blobs.v_unreviewed_docs

blobs.v_unreviewed_docs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT DISTINCT
    ON (b_do.fk_doc) b_do.fk_doc AS pk_doc
    ,
        min
    (b_do.fk_intended_reviewer) AS pk_intended_reviewer
    ,
        min
    (c_e.fk_patient) AS pk_patient

    FROM (
         (blobs.doc_obj b_do

            JOIN blobs.doc_med b_dm
              ON (
                     (b_dm.pk = b_do.fk_doc)
               )
         )

      JOIN clin.encounter c_e
        ON (
               (b_dm.fk_encounter = c_e.pk)
         )
    )

    WHERE (NOT
         (EXISTS
               (
                SELECT 1

                  FROM blobs.reviewed_doc_objs b_rdo

                 WHERE (b_rdo.fk_reviewed_row = b_do.pk)
               )
         )
    )

    GROUP BY b_do.fk_doc;

Index - Schema blobs

## View: blobs.v_unreviewed_docs_inbox

blobs.v_unreviewed_docs_inbox Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT now
    () AS received_when
    ,
        '<system>'::text AS modified_by
    ,
        NULL::text AS provider
    ,
        0 AS importance
    ,
        'clinical'::text AS category
    ,
        _
    ('clinical'::text) AS l10n_category
    ,
        'review docs'::text AS type
    ,
        _
    ('review docs'::text) AS l10n_type
    ,

    (
    SELECT (
               (
                     (
                           (
                                 (
                                       (b_vuds.no_of_docs || ' '::text) || _
                                       ('unreviewed documents for patient'::text)
                                 ) || ' '::text
                           ) || d_n.lastnames
                     ) ||
                  ', '::text
               ) || d_n.firstnames
         )
    ) AS comment
    ,
        NULL::integer[] AS pk_context
    ,
        NULL::text AS data
    ,
        NULL::integer AS pk_inbox_message
    ,

    (
    SELECT staff.pk

      FROM dem.staff

     WHERE (staff.db_user = "current_user"
               ()
         )
    ) AS pk_staff
    ,

    (
    SELECT v_inbox_item_type.pk_category

      FROM dem.v_inbox_item_type

     WHERE (v_inbox_item_type.type = 'review docs'::text)
    ) AS pk_category
    ,

    (
    SELECT v_inbox_item_type.pk_type

      FROM dem.v_inbox_item_type

     WHERE (v_inbox_item_type.type = 'review docs'::text)
    ) AS pk_type
    ,
        b_vuds.pk_patient
    ,
        true AS is_virtual
    ,

    (now
         () - '01:00:00'::interval
    ) AS due_date
    ,
        NULL::timestamp with time zone AS expiry_date
    ,
        true AS is_overdue
    ,
        false AS is_expired
    ,
        '01:00:00'::interval AS interval_due
    ,
        NULL::integer AS xmin_message_inbox

    FROM (blobs.v_unreviewed_docs_summary b_vuds

      JOIN dem.names d_n
        ON (
               (b_vuds.pk_patient = d_n.id_identity)
         )
    )

    WHERE (d_n.active IS TRUE);

Index - Schema blobs

## View: blobs.v_unreviewed_docs_summary

blobs.v_unreviewed_docs_summary Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT b_vud.pk_patient
    ,
        count
    (1) AS no_of_docs

    FROM blobs.v_unreviewed_docs b_vud

    GROUP BY b_vud.pk_patient;

Index - Schema blobs

## Function: blobs.delete_document(integer, integer)

### Returns: boolean

### Language: PLPGSQL

    DECLARE
    	_pk_doc alias for $1;
    	_pk_encounter alias for $2;
    	_del_note text;
    	_doc_row record;
    	_obj_row record;
    	tmp text;
    BEGIN
    	select * into _doc_row from blobs.doc_med where pk = _pk_doc;
    	_del_note := _('Deletion of document') || E':
    '
    		|| ' '
    			|| to_char(_doc_row.clin_when, 'YYYY-MM-DD HH24:MI')
    			|| ' "' || (select _(dt.name) from blobs.doc_type dt where pk = _doc_row.fk_type) || '"'
    			|| coalesce(' (' || _doc_row.ext_ref || ')', '')
    		|| coalesce(E'
     ' || _doc_row.comment, '')
    	;
    	FOR _obj_row IN select * from blobs.doc_obj where fk_doc = _pk_doc order by seq_idx LOOP
    		_del_note := _del_note || E'
    '
    			|| ' #' || coalesce(_obj_row.seq_idx, '-1') || ': "' || coalesce(_obj_row.comment, '') || E'"
    '
    			|| ' ' || coalesce(_obj_row.filename, '') || E'
    ';
    	end LOOP;
    	insert into clin.clin_narrative
    		(fk_encounter, fk_episode, narrative, soap_cat)
    	values (
    		_pk_encounter,
    		_doc_row.fk_episode,
    		_del_note,
    		NULL
    	);
    	-- should auto-cascade:
    	--delete from blobs.doc_obj where fk_doc = _pk_doc;
    	-- should auto-NULL:
    	--bill.bill.fk_doc
    	delete from blobs.doc_med where pk = _pk_doc;
    	return True;
    END;

## Function: blobs.delete_document_part(integer, integer)

### Returns: boolean

### Language: PLPGSQL

    DECLARE
    	_pk_doc_part alias for $1;
    	_pk_encounter alias for $2;
    	_del_note text;
    	_doc_row record;
    	_obj_row record;
    	tmp text;
    BEGIN
    	select * into _obj_row from blobs.doc_obj where pk = _pk_doc_part;
    	select * into _doc_row from blobs.doc_med where pk = _obj_row.fk_doc;
    	_del_note := _('Deletion of part from document') || E':
    '
    		|| ' '
    			|| to_char(_doc_row.clin_when, 'YYYY-MM-DD HH24:MI')
    			|| ' "' || (select _(dt.name) from blobs.doc_type dt where pk = _doc_row.fk_type) || '"'
    			|| coalesce(' (' || _doc_row.ext_ref || ')', '')
    		|| coalesce(E'
     ' || _doc_row.comment, '')
    		|| E'
    '
    		|| ' #' || coalesce(_obj_row.seq_idx, '-1') || ': "' || coalesce(_obj_row.comment, '') || E'"
    '
    		|| ' ' || coalesce(_obj_row.filename, '') || E'
    '
    	;
    	insert into clin.clin_narrative
    		(fk_encounter, fk_episode, narrative, soap_cat)
    	values (
    		_pk_encounter,
    		_doc_row.fk_episode,
    		_del_note,
    		NULL
    	);
    	delete from blobs.doc_obj where pk = _pk_doc_part;
    	return True;
    END;

## Function: blobs.trf_do_not_duplicate_primary_episode_in_link_table()

### Returns: trigger

### Language: PLPGSQL

This trigger function is called before a lnk_doc_med2episode row is inserted or updated. It makes sure the episode does not duplicate the primary episode for this document listed in doc_med. If it does the insert/update is skipped.

    BEGIN
    	-- if already in doc_med
    	perform 1 from blobs.doc_med dm where dm.fk_episode = NEW.fk_episode and dm.pk = NEW.fk_doc_med;
    	if FOUND then
    		-- skip the insert/update
    		return null;
    	end if;
    	return NEW;
    END;

## Function: blobs.trf_mark_unreviewed_on_doc_obj_update()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	if (NEW.data != OLD.data) or ((NEW.data != OLD.data) is NULL) then
    		delete from blobs.reviewed_doc_objs where fk_reviewed_row = OLD.pk;
    	end if;
    	return NEW;
    END;

## Function: blobs.trf_remove_primary_episode_from_link_table()

### Returns: trigger

### Language: PLPGSQL

This trigger function is called when a doc_med row is inserted or updated. It makes sure the primary episode listed in doc_med is not duplicated in lnk_doc_med2episode for the same document. If it exists in the latter it is removed from there.

    BEGIN
    	-- if update
    	if TG_OP = 'UPDATE' then
    		-- and no change
    		if NEW.fk_episode = OLD.fk_episode then
    			-- then do nothing
    			return NEW;
    		end if;
    	end if;
    	-- if already in link table
    	perform 1 from blobs.lnk_doc_med2episode ldm2e where ldm2e.fk_episode = NEW.fk_episode and ldm2e.fk_doc_med = NEW.pk;
    	if FOUND then
    		-- delete from link table
    		delete from blobs.lnk_doc_med2episode where fk_episode = NEW.fk_episode and fk_doc_med = NEW.pk;
    	end if;
    	return NEW;
    END;

## Function: blobs.trf_set_intended_reviewer()

### Returns: trigger

### Language: PLPGSQL

Set the default on blobs.doc_obj.fk_intended_reviewer.

    DECLARE
    	_pk_patient integer;
    	_pk_provider integer;
    BEGIN
    	-- explicitely set ?
    	if NEW.fk_intended_reviewer is not NULL then
    		return NEW;
    	end if;
    	-- find patient via document
    	select
    		fk_patient into _pk_patient
    	from
    		clin.encounter
    	where
    		clin.encounter.pk = (
    			select fk_encounter from blobs.doc_med where pk = NEW.fk_doc
    		);
    	-- does patient have primary provider ?
    	select
    		fk_primary_provider into _pk_provider
    	from
    		dem.identity
    	where
    		dem.identity.pk = _pk_patient;
    	if _pk_provider is not NULL then
    		NEW.fk_intended_reviewer := _pk_provider;
    		return NEW;
    	end if;
    	-- else use CURRENT_USER
    	select
    		pk into _pk_provider
    	from
    		dem.staff
    	where
    		dem.staff.db_user = current_user;
    	NEW.fk_intended_reviewer := _pk_provider;
    	return NEW;
    END;

## Function: blobs.trf_verify_page_number()

### Returns: trigger

### Language: PLPGSQL

    declare
    	msg text;
    begin
    	if NEW.seq_idx is NULL then
    		return NEW;
    	end if;
    	perform 1 from blobs.doc_obj where pk <> NEW.pk and fk_doc = NEW.fk_doc and seq_idx = NEW.seq_idx;
    	if FOUND then
    		msg := '[blobs.trf_verify_page_number]: uniqueness violation: seq_idx [' || NEW.seq_idx || '] already exists for fk_doc [' || NEW.fk_doc || ']';
    		raise exception '%', msg;
    	end if;
    	return NEW;
    end;

# Schema cfg

This schema holds all the configuration data.

## Table: cfg.cfg_data

stores opaque configuration data, either text or binary, note that it will be difficult to share such options among different types of clients

cfg.cfg_data Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
cfg.cfg_item.pk | fk_item |  |
| pk |  | PRIMARY KEY

Index - Schema cfg

## Table: cfg.cfg_item

this table holds all "instances" of cfg.cfg_template

cfg.cfg_item Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| owner |  | UNIQUE#1
| pk |  | PRIMARY KEY
| workplace |  | UNIQUE#1
| cookie |  | UNIQUE#1
cfg.cfg_template.pk | fk_template |  | UNIQUE#1

Tables referencing this one via Foreign Key Constraints:

- cfg.cfg_data

- cfg.cfg_numeric

- cfg.cfg_str_array

- cfg.cfg_string

Index - Schema cfg

## Table: cfg.cfg_numeric

cfg.cfg_numeric Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
cfg.cfg_item.pk | fk_item |  |
| pk |  | PRIMARY KEY

Index - Schema cfg

## Table: cfg.cfg_str_array

cfg.cfg_str_array Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
cfg.cfg_item.pk | fk_item |  |

Index - Schema cfg

## Table: cfg.cfg_string

cfg.cfg_string Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
cfg.cfg_item.pk | fk_item |  |
| pk |  | PRIMARY KEY

Index - Schema cfg

## Table: cfg.cfg_template

meta definition of config items

cfg.cfg_template Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
cfg.cfg_type_enum.name | type |  |

Tables referencing this one via Foreign Key Constraints:

- cfg.cfg_item

Index - Schema cfg

## Table: cfg.cfg_type_enum

enumeration of config option data types

cfg.cfg_type_enum Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| name |  | UNIQUE

Tables referencing this one via Foreign Key Constraints:

- cfg.cfg_template

Index - Schema cfg

## Table: cfg.config

maps a service name to a database location for a particular user, includes user credentials for that database

cfg.config Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| id |  | PRIMARY KEY

Index - Schema cfg

## Table: cfg.db_logon_banner

Stores a banner to show when clients log on.

cfg.db_logon_banner Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| singularizer |  | UNIQUE

cfg.db_logon_banner Constraints
Name | Constraint
--- | ---
db_logon_banner_message_check | CHECK ((btrim(message) <> ''::text))
db_logon_banner_singularizer_check | CHECK ((singularizer IS TRUE))

Index - Schema cfg

## Table: cfg.report_query

This table stores SQL commands to be used in frontend report style queries.

cfg.report_query Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| label |  | UNIQUE

Table cfg.report_query Inherits audit_fields,

cfg.report_query Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
report_query_cmd_check | CHECK ((btrim(COALESCE(cmd, 'NULL'::text)) <> ''::text))
report_query_label_check | CHECK ((btrim(COALESCE(label, 'NULL'::text)) <> ''::text))

Index - Schema cfg

## View: cfg.v_cfg_options

cfg.v_cfg_options Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT cfg_t.name AS option
    ,
        cfg_t.description
    ,
        cfg_i.owner
    ,
        cfg_i.workplace
    ,
        cfg_i.cookie
    ,
        cfg_t.type
    ,
        cfg_t.cfg_group AS "group"
    ,
        cfg_t.pk AS pk_cfg_template
    ,
        cfg_i.pk AS pk_cfg_item

    FROM cfg.cfg_template cfg_t
    ,
        cfg.cfg_item cfg_i

    WHERE (cfg_i.fk_template = cfg_t.pk);

Index - Schema cfg

## View: cfg.v_cfg_opts_data

cfg.v_cfg_opts_data Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT cfg_t.name AS option
    ,
        cfg_v.value
    ,
        cfg_t.description
    ,
        cfg_i.owner
    ,
        cfg_i.workplace
    ,
        cfg_i.cookie
    ,
        cfg_t.cfg_group AS "group"
    ,
        cfg_t.pk AS pk_cfg_template
    ,
        cfg_i.pk AS pk_cfg_item

    FROM cfg.cfg_template cfg_t
    ,
        cfg.cfg_item cfg_i
    ,
        cfg.cfg_data cfg_v

    WHERE (
         (cfg_i.fk_template = cfg_t.pk)
       AND (cfg_v.fk_item = cfg_i.pk)
    );

Index - Schema cfg

## View: cfg.v_cfg_opts_numeric

cfg.v_cfg_opts_numeric Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT cfg_t.name AS option
    ,
        cfg_v.value
    ,
        cfg_t.description
    ,
        cfg_i.owner
    ,
        cfg_i.workplace
    ,
        cfg_i.cookie
    ,
        cfg_t.cfg_group AS "group"
    ,
        cfg_t.pk AS pk_cfg_template
    ,
        cfg_i.pk AS pk_cfg_item

    FROM cfg.cfg_template cfg_t
    ,
        cfg.cfg_item cfg_i
    ,
        cfg.cfg_numeric cfg_v

    WHERE (
         (cfg_i.fk_template = cfg_t.pk)
       AND (cfg_v.fk_item = cfg_i.pk)
    );

Index - Schema cfg

## View: cfg.v_cfg_opts_str_array

cfg.v_cfg_opts_str_array Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT cfg_t.name AS option
    ,
        cfg_v.value
    ,
        cfg_t.description
    ,
        cfg_i.owner
    ,
        cfg_i.workplace
    ,
        cfg_i.cookie
    ,
        cfg_t.cfg_group AS "group"
    ,
        cfg_t.pk AS pk_cfg_template
    ,
        cfg_i.pk AS pk_cfg_item

    FROM cfg.cfg_template cfg_t
    ,
        cfg.cfg_item cfg_i
    ,
        cfg.cfg_str_array cfg_v

    WHERE (
         (cfg_i.fk_template = cfg_t.pk)
       AND (cfg_v.fk_item = cfg_i.pk)
    );

Index - Schema cfg

## View: cfg.v_cfg_opts_string

cfg.v_cfg_opts_string Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT cfg_t.name AS option
    ,
        cfg_v.value
    ,
        cfg_t.description
    ,
        cfg_i.owner
    ,
        cfg_i.workplace
    ,
        cfg_i.cookie
    ,
        cfg_t.cfg_group AS "group"
    ,
        cfg_t.pk AS pk_cfg_template
    ,
        cfg_i.pk AS pk_cfg_item

    FROM cfg.cfg_template cfg_t
    ,
        cfg.cfg_item cfg_i
    ,
        cfg.cfg_string cfg_v

    WHERE (
         (cfg_i.fk_template = cfg_t.pk)
       AND (cfg_v.fk_item = cfg_i.pk)
    );

Index - Schema cfg

## Function: cfg.create_cfg_item(text, text, text, text, text)

### Returns: integer

### Language: PLPGSQL

    declare
    	_option alias for $1;
    	_val_type alias for $2;
    	_workplace alias for $3;
    	_cookie alias for $4;
    	_owner alias for $5;
    	real_owner text;
    	pk_template integer;
    	pk_item integer;
    begin
    	-- check template
    	select into pk_template pk from cfg.cfg_template where name = _option and type = _val_type;
    	if not FOUND then
    		insert into cfg.cfg_template (name, type) values (_option, _val_type);
    		select into pk_template currval('cfg.cfg_template_pk_seq');
    	end if;
    	if _owner is null then
    		select into real_owner CURRENT_USER;
    	else
    		real_owner := _owner;
    	end if;
    	-- check item
    	if _cookie is NULL then
    		select into pk_item pk from cfg.cfg_item where
    			fk_template = pk_template and
    			owner = real_owner and
    			workplace = _workplace and
    			cookie is null;
    	else
    		select into pk_item pk from cfg.cfg_item where
    			fk_template = pk_template and
    			owner = real_owner and
    			workplace = _workplace and
    			cookie = _cookie;
    	end if;
    	if FOUND then
    		return pk_item;
    	end if;
    	insert into cfg.cfg_item (
    		fk_template, workplace, cookie, owner
    	) values (
    		pk_template,
    		_workplace,
    		_cookie,
    		real_owner
    	);
    	select into pk_item currval('cfg.cfg_item_pk_seq');
    	return pk_item;
    end;

## Function: cfg.set_option(text, anyelement, text, text, text)

### Returns: boolean

### Language: PLPGSQL

set option, owner = NULL means CURRENT_USER

    declare
    	_option alias for $1;
    	_value alias for $2;
    	_workplace alias for $3;
    	_cookie alias for $4;
    	_owner alias for $5;
    	val_type text;
    	pk_item integer;
    	rows integer;
    	cmd text;
    begin
    	-- determine data type
    	if _value is of (text, char, varchar, name) then
    		val_type := 'string';
    	elsif _value is of (smallint, integer, bigint, numeric, boolean) then
    		val_type := 'numeric';
    	elsif _value is of (bytea) then
    		val_type := 'data';
    	elsif _value is of (text[]) then
    		val_type := 'str_array';
    	else
    		raise exception 'cfg.set_option(text, any, text, text, text): invalid type of value';
    	end if;
    	-- create template/item if need be
    	select into pk_item cfg.create_cfg_item(_option, val_type, _workplace, _cookie, _owner);
    	-- set item value
    	cmd := 'select 1 from cfg.cfg_' || val_type || ' where fk_item=' || pk_item || ';';
    	execute cmd;
    	get diagnostics rows = row_count;
    	found := rows <> 0;
    	if FOUND then
    		if val_type = 'str_array' then
    			cmd := 'update cfg.cfg_str_array set value=''{"' || array_to_string(_value, '","') || '"}'' where fk_item=' || pk_item || ';';
    		elsif val_type = 'data' then
    			cmd := 'update cfg.cfg_data set value=''' || encode(_value, 'escape') || ''' where fk_item=' || pk_item || ';';
    		else
    			cmd := 'update cfg.cfg_' || val_type || ' set value=' || quote_literal(_value) || ' where fk_item=' || pk_item || ';';
    		end if;
    		execute cmd;
    		return True;
    	end if;
    	if val_type = 'str_array' then
    		cmd := 'insert into cfg.cfg_str_array(fk_item, value) values (' || pk_item || ', ''{"' || array_to_string(_value, '","') || '"}'');';
    	elsif val_type = 'data' then
    		cmd := 'insert into cfg.cfg_data(fk_item, value) values (' || pk_item || ', ''' || encode(_value, 'escape') || ''');';
    	else
    		cmd := 'insert into cfg.cfg_' || val_type || ' (fk_item, value) values (' || pk_item || ', ' || quote_literal(_value) || ');';
    	end if;
    	execute cmd;
    	return True;
    end;

# Schema clin

## Table: clin._enum_allergy_type

clin._enum_allergy_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| value |  | UNIQUE

Tables referencing this one via Foreign Key Constraints:

- clin.allergy

Index - Schema clin

## View: clin._view_emr_journal_without_suppressed_hints

clin._view_emr_journal_without_suppressed_hints Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT v_emr_journal.pk_patient
    ,
        v_emr_journal.modified_when
    ,
        v_emr_journal.clin_when
    ,
        v_emr_journal.modified_by
    ,
        v_emr_journal.soap_cat
    ,
        v_emr_journal.narrative
    ,
        v_emr_journal.pk_encounter
    ,
        v_emr_journal.pk_episode
    ,
        v_emr_journal.pk_health_issue
    ,
        v_emr_journal.src_pk
    ,
        v_emr_journal.src_table
    ,
        v_emr_journal.row_version
    ,
        v_emr_journal.health_issue
    ,
        v_emr_journal.issue_laterality
    ,
        v_emr_journal.issue_active
    ,
        v_emr_journal.issue_clinically_relevant
    ,
        v_emr_journal.issue_confidential
    ,
        v_emr_journal.episode
    ,
        v_emr_journal.episode_open
    ,
        v_emr_journal.encounter_started
    ,
        v_emr_journal.encounter_last_affirmed
    ,
        v_emr_journal.encounter_type
    ,
        v_emr_journal.encounter_l10n_type

    FROM clin.v_emr_journal

    WHERE (v_emr_journal.src_table <> 'clin.suppressed_hint'::text);

Index - Schema clin

## Table: clin.allergy

patient allergy details

clin.allergy Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
clin._enum_allergy_type.pk | fk_type |  |
| pk |  | PRIMARY KEY
clin.episode.pk | fk_episode |  |

Table clin.allergy Inherits clin_root_item,

clin.allergy Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))

idx_clin_allergy_fk_encounter fk_encounter idx_clin_allergy_fk_episode fk_episode

Index - Schema clin

## Table: clin.allergy_state

clin.allergy_state Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
| pk |  | PRIMARY KEY

Table clin.allergy_state Inherits audit_fields,

clin.allergy_state Constraints
Name | Constraint
--- | ---
allergy_state_check | CHECK (((has_allergy IS NULL) OR ((has_allergy IS NOT NULL) AND (last_confirmed IS NOT NULL))))
allergy_state_has_allergy_check | CHECK ((has_allergy = ANY (ARRAY[NULL::integer, 0, 1])))
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.clin_aux_note

Other tables link to this if they need more free text fields.

clin.clin_aux_note Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
clin.episode.pk | fk_episode |  |
clin.encounter.pk | fk_encounter |  |

Table clin.clin_aux_note Inherits clin_root_item,

clin.clin_aux_note Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))

idx_clin_clin_aux_note_fk_encounter fk_encounter idx_clin_clin_aux_note_fk_episode fk_episode

Index - Schema clin

## Table: clin.clin_diag

stores additional detail on those clin.clin_narrative rows where soap_cat=a that are true diagnoses, true diagnoses DO have a code from one of the coding systems

clin.clin_diag Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
clin.clin_narrative.pk | fk_narrative |  | UNIQUE

Table clin.clin_diag Inherits audit_fields,

clin.clin_diag Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_diag_laterality_check | CHECK (((laterality = ANY (ARRAY['l'::bpchar, 'r'::bpchar, 'b'::bpchar, '?'::bpchar])) OR (laterality IS NULL)))
if_active_then_relevant | CHECK (((is_active = false) OR ((is_active = true) AND (clinically_relevant = true))))

Index - Schema clin

## Table: clin.clin_item_type

stores arbitrary types for tagging clinical items

clin.clin_item_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| type |  | UNIQUE
| code |  | UNIQUE

Table clin.clin_item_type Inherits audit_fields,

clin.clin_item_type Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_type2item

Index - Schema clin

## Table: clin.clin_narrative

Used to store clinical free text *not* associated with any other table. Used to implement a simple SOAP structure. Also other tags can be associated via link tables.

clin.clin_narrative Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
clin.episode.pk | fk_episode |  |
clin.encounter.pk | fk_encounter |  |

Table clin.clin_narrative Inherits clin_root_item,

clin.clin_narrative Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))
narrative_neither_null_nor_empty | CHECK ((btrim(COALESCE(narrative, ''::text)) <> ''::text))

Tables referencing this one via Foreign Key Constraints:

- clin.clin_diag

- clin.lnk_code2narrative

idx_clin_clin_narrative_fk_encounter fk_encounter idx_clin_clin_narrative_fk_episode fk_episode idx_narrative_modified_by modified_by idx_narrative_soap_cat soap_cat) WHERE (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text])

Index - Schema clin

## Table: clin.clin_root_item

ancestor table for clinical items of any kind, basic unit of clinical information, do *not* store data in here directly, use child tables, contains all the clinical narrative aggregated for full text search, ancestor for all tables that want to store clinical free text

clin.clin_root_item Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
| pk_item |  | PRIMARY KEY
clin.episode.pk | fk_episode |  |

Table clin.clin_root_item Inherits audit_fields,

clin.clin_root_item Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))

idx_cri_encounter fk_encounter idx_cri_episode fk_episode

Index - Schema clin

## Table: clin.encounter

a clinical encounter between a person and the health care system

clin.encounter Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
clin.encounter_type.pk | fk_type |  |
clin.patient.fk_identity | fk_patient |  |
dem.org_unit.pk | fk_location |  |

Table clin.encounter Inherits audit_fields,

clin.encounter Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_enc_sane_duration | CHECK ((last_affirmed >= started))
encounter_assessment_of_encounter_check | CHECK ((btrim(COALESCE(assessment_of_encounter, 'xxxDEFAULTxxx'::text)) <> ''::text))
encounter_reason_for_encounter_check | CHECK ((btrim(COALESCE(reason_for_encounter, 'xxxDEFAULTxxx'::text)) <> ''::text))

Tables referencing this one via Foreign Key Constraints:

- au.referral

- bill.bill_item

- blobs.doc_med

- clin.allergy

- clin.allergy_state

- clin.clin_aux_note

- clin.clin_narrative

- clin.clin_root_item

- clin.episode

- clin.external_care

- clin.family_history

- clin.form_instances

- clin.health_issue

- clin.hospital_stay

- clin.lab_request

- clin.lnk_code2aoe

- clin.lnk_code2rfe

- clin.procedure

- clin.substance_intake

- clin.suppressed_hint

- clin.test_result

- clin.vaccination

idx_clin_encounter_fk_location fk_location idx_encounter_affirmed last_affirmed idx_encounter_modified_by modified_by idx_encounter_started started idx_pat_per_encounter fk_patient

Index - Schema clin

## Table: clin.encounter_type

these are the types of encounter

clin.encounter_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| description |  | UNIQUE
| pk |  | PRIMARY KEY

Tables referencing this one via Foreign Key Constraints:

- bill.lnk_enc_type2billable

- clin.encounter

Index - Schema clin

## Table: clin.episode

Clinical episodes such as "Otitis media", "traffic accident 7/99", "Hepatitis B". This covers a range of time in which activity of illness was noted for the problem episode.description.

clin.episode Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
clin.health_issue.pk | fk_health_issue |  |
| pk |  | PRIMARY KEY

Table clin.episode Inherits audit_fields,

clin.episode Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
episode_sane_summary | CHECK (gm.is_null_or_non_empty_string(summary))
sane_description | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))
valid_diagnostic_certainty_classification | CHECK ((diagnostic_certainty_classification = ANY (ARRAY['A'::text, 'B'::text, 'C'::text, 'D'::text, NULL::text])))

Tables referencing this one via Foreign Key Constraints:

- au.referral

- blobs.doc_med

- blobs.lnk_doc_med2episode

- clin.allergy

- clin.clin_aux_note

- clin.clin_narrative

- clin.clin_root_item

- clin.family_history

- clin.form_instances

- clin.hospital_stay

- clin.lab_request

- clin.lnk_code2episode

- clin.lnk_substance2episode

- clin.procedure

- clin.substance_intake

- clin.test_result

- clin.vaccination

idx_episode_fk_encounter fk_encounter idx_episode_issue fk_health_issue idx_episode_modified_by modified_by idx_episode_with_issue fk_health_issue) WHERE (fk_health_issue IS NOT NULL idx_episode_without_issue fk_health_issue) WHERE (fk_health_issue IS NULL

Index - Schema clin

## Table: clin.export_item

A table to hold binary data for patients intended for export as print/mail/fax/removable media/...

clin.export_item Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.patient.fk_identity | fk_identity |  | UNIQUE#1
| description |  | UNIQUE#1
| pk |  | PRIMARY KEY
blobs.doc_obj.pk | fk_doc_obj |  | UNIQUE

clin.export_item Constraints
Name | Constraint
--- | ---
clin_export_item_fk_obj_or_data | CHECK ((((data IS NULL) AND (fk_doc_obj IS NOT NULL)) OR ((data IS NOT NULL) AND (fk_doc_obj IS NULL))))
clin_export_item_fk_obj_or_filename | CHECK ((((filename IS NULL) AND (fk_doc_obj IS NOT NULL)) OR ((filename IS NOT NULL) AND (fk_doc_obj IS NULL))))
clin_export_item_sane_by | CHECK ((length((created_by)::text) > 0))
clin_export_item_sane_data | CHECK (((data IS NULL) OR (length(data) > 0)))
clin_export_item_sane_description | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))
clin_export_item_sane_designation | CHECK ((gm.is_null_or_non_empty_string(designation) IS TRUE))
clin_export_item_sane_filename | CHECK ((gm.is_null_or_non_empty_string(filename) IS TRUE))

Index - Schema clin

## Table: clin.external_care

lists external care situations for patients

clin.external_care Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
clin.health_issue.pk | fk_health_issue |  | UNIQUE#1
| pk |  | PRIMARY KEY
dem.org_unit.pk | fk_org_unit |  | UNIQUE#1

Table clin.external_care Inherits audit_fields,

clin.external_care Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_ext_care_issue_xor_fk_issue | CHECK ((((fk_health_issue IS NULL) AND (issue IS NOT NULL)) OR ((fk_health_issue IS NOT NULL) AND (issue IS NULL))))
clin_ext_care_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
clin_ext_care_sane_issue | CHECK ((gm.is_null_or_non_empty_string(issue) IS TRUE))
clin_ext_care_sane_provider | CHECK ((gm.is_null_or_non_empty_string(provider) IS TRUE))

idx_external_care_fk_encounter fk_encounter idx_external_care_fk_health_issue fk_health_issue idx_external_care_fk_org_unit fk_org_unit

Index - Schema clin

## Table: clin.family_history

This table stores family history items on persons not otherwise in the database.

clin.family_history Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
| pk |  | PRIMARY KEY
clin.fhx_relation_type.pk | fk_relation_type |  |
clin.episode.pk | fk_episode |  |

Table clin.family_history Inherits clin_root_item,

clin.family_history Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
c_family_history_sane_age_noted | CHECK ((gm.is_null_or_non_empty_string(age_noted) IS TRUE))
c_family_history_sane_condition | CHECK ((gm.is_null_or_blank_string(narrative) IS FALSE))
c_family_history_sane_name | CHECK ((gm.is_null_or_non_empty_string(name_relative) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))
narrative_neither_null_nor_empty | CHECK ((btrim(COALESCE(narrative, ''::text)) <> ''::text))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_code2fhx

idx_clin_family_history_fk_encounter fk_encounter idx_clin_family_history_fk_episode fk_episode

Index - Schema clin

## Table: clin.fhx_relation_type

Enumerates inter-person relations for family history linking.

clin.fhx_relation_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| is_genetic |  | UNIQUE#1
| pk |  | PRIMARY KEY
| description |  | UNIQUE#1

Table clin.fhx_relation_type Inherits audit_fields,

clin.fhx_relation_type Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
c_fhx_relation_type_sane_desc | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- clin.family_history

Index - Schema clin

## Table: clin.form_data

holds the values used in form instances, for later re-use/validation

clin.form_data Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
public.form_fields.pk | fk_form_field |  | UNIQUE#1
| pk |  | PRIMARY KEY
clin.form_instances.pk | fk_instance |  | UNIQUE#1

Table clin.form_data Inherits audit_fields,

clin.form_data Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.form_instances

instances of forms, like a log of all processed forms

clin.form_instances Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.episode.pk | fk_episode |  |
| pk |  | PRIMARY KEY
ref.paperwork_templates.pk | fk_form_def |  |
clin.encounter.pk | fk_encounter |  |

Table clin.form_instances Inherits clin_root_item,

clin.form_instances Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))
form_is_plan | CHECK ((soap_cat = 'p'::text))

Tables referencing this one via Foreign Key Constraints:

- au.referral

- clin.form_data

- public.form_job_queue

idx_clin_form_instances_fk_encounter fk_encounter idx_clin_form_instances_fk_episode fk_episode

Index - Schema clin

## Table: clin.health_issue

This is pretty much what others would call "Past Medical History" or "Foundational illness", eg. longer-ranging, underlying, encompassing issues with one's health such as "immunodeficiency", "type 2 diabetes". In Belgium it is called "problem". L.L.Weed includes lots of little things into it, we do not.

clin.health_issue Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
| pk |  | PRIMARY KEY

Table clin.health_issue Inherits audit_fields,

clin.health_issue Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
health_issue_laterality_check | CHECK (((laterality)::text = ANY (ARRAY[(NULL::character varying)::text, ('s'::character varying)::text, ('d'::character varying)::text, ('sd'::character varying)::text, ('na'::character varying)::text])))
health_issue_sane_summary | CHECK (gm.is_null_or_non_empty_string(summary))
issue_name_not_empty | CHECK ((btrim(description) <> ''::text))
sane_grouping | CHECK (gm.is_null_or_non_empty_string("grouping"))
valid_diagnostic_certainty_classification | CHECK ((diagnostic_certainty_classification = ANY (ARRAY['A'::text, 'B'::text, 'C'::text, 'D'::text, NULL::text])))

Tables referencing this one via Foreign Key Constraints:

- clin.episode

- clin.external_care

- clin.lnk_code2h_issue

idx_health_issue_modified_by modified_by

Index - Schema clin

## Table: clin.hospital_stay

collects data on hospitalisations of patients, reasons are linked via a link table

clin.hospital_stay Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.org_unit.pk | fk_org_unit |  |
| pk |  | PRIMARY KEY
clin.episode.pk | fk_episode |  |
clin.encounter.pk | fk_encounter |  |

Table clin.hospital_stay Inherits clin_root_item,

clin.hospital_stay Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))
sane_duration | CHECK (((discharge IS NULL) OR (discharge > clin_when)))
sane_hospital | CHECK (gm.is_null_or_non_empty_string(narrative))

Tables referencing this one via Foreign Key Constraints:

- clin.procedure

idx_clin_hospital_stay_fk_encounter fk_encounter idx_clin_hospital_stay_fk_episode fk_episode

Index - Schema clin

## Table: clin.incoming_data_unmatchable

this table holds test results that could not be matched to any patient, it is intended to prevent overflow of incoming_data_unmatched with unmatchable data

clin.incoming_data_unmatchable Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

Table clin.incoming_data_unmatchable Inherits audit_fields,

clin.incoming_data_unmatchable Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.incoming_data_unmatched

this table holds incoming data (lab results, documents) that could not be matched to one single patient automatically, it is intended to facilitate manual matching, - use "modified_when" for import time

clin.incoming_data_unmatched Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.patient.fk_identity | fk_identity_disambiguated |  |
| pk |  | PRIMARY KEY
dem.staff.pk | fk_provider_disambiguated |  |

Table clin.incoming_data_unmatched Inherits audit_fields,

clin.incoming_data_unmatched Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
unmatched_data_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))

Index - Schema clin

## Table: clin.lab_request

test request metadata

clin.lab_request Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
dem.identity.pk | fk_requestor |  |
| request_id |  | UNIQUE#1
clin.episode.pk | fk_episode |  |
clin.encounter.pk | fk_encounter |  |
clin.test_org.pk | fk_test_org |  | UNIQUE#1

Table clin.lab_request Inherits clin_root_item,

clin.lab_request Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_lab_req_sane_test_org_note | CHECK ((gm.is_null_or_non_empty_string(note_test_org) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))
lab_request_request_id_check | CHECK ((btrim(request_id) <> ''::text))
lab_request_request_status_check | CHECK ((request_status = ANY (ARRAY['pending'::text, 'preliminary'::text, 'partial'::text, 'final'::text])))

Tables referencing this one via Foreign Key Constraints:

- clin.test_result

idx_clin_lab_request_fk_encounter fk_encounter idx_clin_lab_request_fk_episode fk_episode

Index - Schema clin

## Table: clin.lnk_code2aoe

Links codes to encounter.aoe.

clin.lnk_code2aoe Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_item |  | UNIQUE#1
| fk_generic_code |  | UNIQUE#1
| pk |  | PRIMARY KEY

Table clin.lnk_code2aoe Inherits lnk_code2item_root,

clin.lnk_code2aoe Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_c_lc2aoe_fk_item fk_item

Index - Schema clin

## Table: clin.lnk_code2episode

Links codes to episodes.

clin.lnk_code2episode Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
clin.episode.pk | fk_item |  | UNIQUE#1
| fk_generic_code |  | UNIQUE#1

Table clin.lnk_code2episode Inherits lnk_code2item_root,

clin.lnk_code2episode Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_c_lc2epi_fk_item fk_item

Index - Schema clin

## Table: clin.lnk_code2fhx

Links codes to family history items.

clin.lnk_code2fhx Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| fk_generic_code |  | UNIQUE#1
clin.family_history.pk | fk_item |  | UNIQUE#1

Table clin.lnk_code2fhx Inherits lnk_code2item_root,

clin.lnk_code2fhx Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_c_lc2fhx_fk_item fk_item

Index - Schema clin

## Table: clin.lnk_code2h_issue

Links codes to health issues.

clin.lnk_code2h_issue Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
clin.health_issue.pk | fk_item |  | UNIQUE#1
| fk_generic_code |  | UNIQUE#1

Table clin.lnk_code2h_issue Inherits lnk_code2item_root,

clin.lnk_code2h_issue Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_c_lc2iss_fk_item fk_item

Index - Schema clin

## Table: clin.lnk_code2item_root

The parent table of all tables linking codes to EMR structures. Coding tables check this table for existence of their PK in .fk_generic_code in order to prevent cascading DELETEs/UPDATEs from breaking referential integrity. EMR structure tables foreign key into children of this table in order to link structures to codes.

clin.lnk_code2item_root Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_lnk_code2item |  | PRIMARY KEY

Table clin.lnk_code2item_root Inherits audit_fields,

clin.lnk_code2item_root Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.lnk_code2narrative

Links codes to SOAP narrative.

clin.lnk_code2narrative Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| fk_generic_code |  | UNIQUE#1
clin.clin_narrative.pk | fk_item |  | UNIQUE#1

Table clin.lnk_code2narrative Inherits lnk_code2item_root,

clin.lnk_code2narrative Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_c_lc2narr_fk_item fk_item

Index - Schema clin

## Table: clin.lnk_code2procedure

Links codes to procedures. OPS comes to mind.

clin.lnk_code2procedure Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| fk_generic_code |  | UNIQUE#1
clin.procedure.pk | fk_item |  | UNIQUE#1

Table clin.lnk_code2procedure Inherits lnk_code2item_root,

clin.lnk_code2procedure Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_c_lc2proc_fk_item fk_item

Index - Schema clin

## Table: clin.lnk_code2rfe

Links codes to encounters.

clin.lnk_code2rfe Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_item |  | UNIQUE#1
| fk_generic_code |  | UNIQUE#1
| pk |  | PRIMARY KEY

Table clin.lnk_code2rfe Inherits lnk_code2item_root,

clin.lnk_code2rfe Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_c_lc2rfe_fk_item fk_item

Index - Schema clin

## Table: clin.lnk_code2tst_pnl

Links codes to test panels.

clin.lnk_code2tst_pnl Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| fk_generic_code |  | UNIQUE#1
clin.test_panel.pk | fk_item |  | UNIQUE#1

Table clin.lnk_code2tst_pnl Inherits lnk_code2item_root,

clin.lnk_code2tst_pnl Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_c_lc2tp_fk_item fk_item

Index - Schema clin

## Table: clin.lnk_constraint2vacc_course

links constraints to courses

clin.lnk_constraint2vacc_course Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.vaccination_course.pk | fk_vaccination_course |  | UNIQUE#1
| pk |  | PRIMARY KEY
clin.vaccination_course_constraint.pk | fk_constraint |  | UNIQUE#1

Table clin.lnk_constraint2vacc_course Inherits audit_fields,

clin.lnk_constraint2vacc_course Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.lnk_loinc2test_panel

Links LOINC codes to test panels which thusly become part of said panel.

clin.lnk_loinc2test_panel Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
clin.test_panel.pk | fk_test_panel |  |

Table clin.lnk_loinc2test_panel Inherits audit_fields,

clin.lnk_loinc2test_panel Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_ll2tp_sane_loinc | CHECK ((gm.is_null_or_blank_string(loinc) IS FALSE))

Index - Schema clin

## Table: clin.lnk_pat2vaccination_course

links patients to vaccination courses they are actually on, this allows for per-patient selection of courses to be followed, eg. children at different ages may be on different vaccination courses or some people are on a course due to a trip abroad while most others are not

clin.lnk_pat2vaccination_course Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
clin.patient.fk_identity | fk_patient |  | UNIQUE#1
clin.vaccination_course.pk | fk_course |  | UNIQUE#1

Table clin.lnk_pat2vaccination_course Inherits audit_fields,

clin.lnk_pat2vaccination_course Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.lnk_substance2episode

clin.lnk_substance2episode Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.substance_intake.pk | fk_substance |  |
clin.episode.pk | fk_episode |  |
| pk |  | PRIMARY KEY

Table clin.lnk_substance2episode Inherits audit_fields,

clin.lnk_substance2episode Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.lnk_tst2norm

links test result evaluation norms to tests

clin.lnk_tst2norm Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| id_norm |  | UNIQUE#1
clin.test_type.pk | id_test |  | UNIQUE#1
| id |  | PRIMARY KEY

Table clin.lnk_tst2norm Inherits audit_fields,

clin.lnk_tst2norm Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.lnk_type2item

allow to link many-to-many between clin.clin_root_item and clin.clin_item_type

clin.lnk_type2item Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| fk_item |  | UNIQUE#1
clin.clin_item_type.pk | fk_type |  | UNIQUE#1
| pk |  | PRIMARY KEY

Table clin.lnk_type2item Inherits audit_fields,

clin.lnk_type2item Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.lnk_vaccination_course2schedule

this table links vaccination courses for a single epitope into schedules defined and recommended by a vaccination council or similar entity

clin.lnk_vaccination_course2schedule Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.vaccination_course.pk | fk_course |  | UNIQUE
clin.vaccination_schedule.pk | fk_schedule |  |
| pk |  | PRIMARY KEY

Table clin.lnk_vaccination_course2schedule Inherits audit_fields,

clin.lnk_vaccination_course2schedule Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.meta_test_type

this table merges test types from various test orgs which are intended to measure the same value but have differing names into one logical test type, this is not intended to be used for aggregating semantically different test types into "profiles"

clin.meta_test_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| abbrev |  | UNIQUE#1
| name |  | UNIQUE#1
| pk |  | PRIMARY KEY

Tables referencing this one via Foreign Key Constraints:

- clin.test_type

Index - Schema clin

## Table: clin.patient

A table to hold unique-per-identity *clinical* items, such as Expected Due Date.

clin.patient Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
dem.identity.pk | fk_identity |  | UNIQUE

Table clin.patient Inherits audit_fields,

clin.patient Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_patient_sane_edc | CHECK (((edc IS NULL) OR ((clin.get_dod(fk_identity) IS NULL) AND ((clin.get_dob(fk_identity) IS NULL) OR (edc > (clin.get_dob(fk_identity) + '5 years'::interval))))))

Tables referencing this one via Foreign Key Constraints:

- clin.encounter

- clin.export_item

- clin.incoming_data_unmatched

- clin.lnk_pat2vaccination_course

Index - Schema clin

## Table: clin.procedure

This table holds procedure/operations performed on the patient both in hospital or in community care.

clin.procedure Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
clin.hospital_stay.pk | fk_hospital_stay |  |
blobs.doc_med.pk | fk_doc |  |
clin.episode.pk | fk_episode |  |
dem.org_unit.pk | fk_org_unit |  |
| pk |  | PRIMARY KEY

Table clin.procedure Inherits clin_root_item,

clin.procedure Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_procedure_lnk_org_or_stay | CHECK ((((fk_hospital_stay IS NULL) AND (fk_org_unit IS NOT NULL)) OR ((fk_hospital_stay IS NOT NULL) AND (fk_org_unit IS NULL))))
clin_procedure_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))
procedure_sane_end | CHECK (((clin_end IS NULL) OR (clin_end >= clin_when)))
sane_procedure | CHECK ((gm.is_null_or_blank_string(narrative) IS FALSE))
sane_soap_cat | CHECK ((soap_cat = ANY (ARRAY['a'::text, 'p'::text])))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_code2procedure

idx_clin_procedure_fk_encounter fk_encounter idx_clin_procedure_fk_episode fk_episode

Index - Schema clin

## Table: clin.review_root

this table tracks whether a particular clinical item was reviewed by a clinician or not

clin.review_root Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
dem.staff.pk | fk_reviewer |  | UNIQUE#1
| fk_reviewed_row |  | UNIQUE#1

Table clin.review_root Inherits audit_fields,

clin.review_root Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema clin

## Table: clin.reviewed_test_results

review table for test results

clin.reviewed_test_results Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
clin.test_result.pk | fk_reviewed_row |  | UNIQUE#1 UNIQUE
dem.staff.pk | fk_reviewer |  | UNIQUE#1

Table clin.reviewed_test_results Inherits review_root,

clin.reviewed_test_results Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_rtr_fk_reviewer fk_reviewer

Index - Schema clin

## Table: clin.soap_cat_ranks

clin.soap_cat_ranks Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

clin.soap_cat_ranks Constraints
Name | Constraint
--- | ---
clin_soap_cat_ranks_sane_cats | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::bpchar, 'o'::bpchar, 'a'::bpchar, 'p'::bpchar, 'u'::bpchar]))))
clin_soap_cat_ranks_sane_ranks | CHECK ((rank = ANY (ARRAY[1, 2, 3, 4, 5, 6])))

Index - Schema clin

## Table: clin.substance_intake

The substances a patient is actually currently taking.

clin.substance_intake Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
ref.lnk_dose2drug.pk | fk_drug_component |  |
| pk |  | PRIMARY KEY
clin.episode.pk | fk_episode |  |

Table clin.substance_intake Inherits clin_root_item,

clin.substance_intake Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_patient_sane_use_type | CHECK (((harmful_use_type IS NULL) OR ((harmful_use_type >= 0) AND (harmful_use_type <= 3))))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))
clin_substance_intake_sane_start_comment | CHECK (gm.is_null_or_non_empty_string(comment_on_start))
discontinued_after_started | CHECK (((harmful_use_type IS NOT NULL) OR (clin_when IS NULL) OR (discontinued IS NULL) OR ((discontinued >= clin_when) AND (discontinued <= now()))))
medication_is_plan | CHECK ((soap_cat = 'p'::text))
sane_aim | CHECK ((gm.is_null_or_non_empty_string(aim) IS TRUE))
sane_discontinue_reason | CHECK ((((discontinued IS NULL) AND (discontinue_reason IS NULL)) OR ((discontinued IS NOT NULL) AND (gm.is_null_or_non_empty_string(discontinue_reason) IS TRUE))))
sane_schedule | CHECK ((gm.is_null_or_non_empty_string(schedule) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_substance2episode

idx_c_subst_int_fk_drug_comp fk_drug_component idx_clin_substance_intake_fk_encounter fk_encounter idx_clin_substance_intake_fk_episode fk_episode

Index - Schema clin

## Table: clin.suppressed_hint

A table to hold hints suppressed per patient

clin.suppressed_hint Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.auto_hint.pk | fk_hint |  |
clin.encounter.pk | fk_encounter |  |
| pk |  | PRIMARY KEY

Table clin.suppressed_hint Inherits audit_fields,

clin.suppressed_hint Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_suppressed_hint_sane_by | CHECK ((length((suppressed_by)::text) > 0))
clin_suppressed_hint_sane_md5 | CHECK ((gm.is_null_or_blank_string(md5_sum) IS FALSE))
clin_suppressed_hint_sane_rationale | CHECK ((gm.is_null_or_blank_string(rationale) IS FALSE))

idx_suppressed_hint_fk_encounter fk_encounter idx_suppressed_hint_fk_hint fk_hint

Index - Schema clin

## Table: clin.test_org

organisation providing results

clin.test_org Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.identity.pk | fk_med_contact |  |
dem.identity.pk | fk_adm_contact |  |
| pk |  | PRIMARY KEY
dem.org_unit.pk | fk_org_unit |  | UNIQUE

Table clin.test_org Inherits audit_fields,

clin.test_org Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
sane_contact | CHECK ((gm.is_null_or_non_empty_string(contact) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- clin.lab_request

- clin.test_type

- staging.lab_request

Index - Schema clin

## Table: clin.test_panel

Panels of tests. The same test can appear in several panels.

clin.test_panel Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

Table clin.test_panel Inherits audit_fields,

clin.test_panel Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_test_panel_sane_cmt | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
clin_test_panel_sane_desc | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_code2tst_pnl

- clin.lnk_loinc2test_panel

Index - Schema clin

## Table: clin.test_result

the results of a single measurement

clin.test_result Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
dem.staff.pk | fk_intended_reviewer |  |
clin.lab_request.pk | fk_request |  |
clin.test_type.pk | fk_type |  |
clin.episode.pk | fk_episode |  |
| pk |  | PRIMARY KEY

Table clin.test_result Inherits clin_root_item,

clin.test_result Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))
clin_test_result_sane_source_data | CHECK (gm.is_null_or_non_empty_string(source_data))
clin_test_result_sane_status | CHECK (gm.is_null_or_non_empty_string(status))
clin_test_result_sane_val_grouping | CHECK (gm.is_null_or_non_empty_string(val_grouping))
numval_needs_unit | CHECK ((((val_num IS NOT NULL) AND (btrim(COALESCE(val_unit, ''::text)) <> ''::text)) OR (val_num IS NULL)))
test_result_check | CHECK (((val_num IS NOT NULL) OR (val_alpha IS NOT NULL) OR ((val_num IS NULL) AND (val_alpha <> ''::text) AND (val_alpha IS NOT NULL))))

Tables referencing this one via Foreign Key Constraints:

- clin.reviewed_test_results

idx_clin_test_result_fk_encounter fk_encounter idx_clin_test_result_fk_episode fk_episode idx_test_result_fk_type fk_type idx_test_result_status status idx_test_result_unit val_unit

Index - Schema clin

## Table: clin.test_type

measurement type, like a "method" in a lab

clin.test_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.test_org.pk | fk_test_org |  | UNIQUE#1 UNIQUE#2
clin.meta_test_type.pk | fk_meta_test_type |  |
| abbrev |  | UNIQUE#1
| pk |  | PRIMARY KEY
| name |  | UNIQUE#2

Table clin.test_type Inherits audit_fields,

clin.test_type Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_tst2norm

- clin.test_result

- de_de.lab_test_gnr

idx_test_type_fk_meta_test_type fk_meta_test_type idx_test_type_fk_test_org fk_test_org idx_test_type_loinc loinc) WHERE (loinc IS NOT NULL

Index - Schema clin

## View: clin.v_candidate_diagnoses

Candidates for diagnoses.

clin.v_candidate_diagnoses Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT (
    SELECT c_enc.fk_patient

      FROM clin.encounter c_enc

     WHERE (c_enc.pk = c_hi.fk_encounter)
    ) AS pk_patient
    ,

    (c_hi.description || COALESCE
         (
               (
                     (
                        ' ('::text ||
                                 (c_hi.laterality)::text
                           ) ||
                   ')'::text
               )
               ,''::text
         )
    ) AS diagnosis
    ,
        c_hi.is_confidential AS explicitely_confidential
    ,
        c_hi.diagnostic_certainty_classification
    ,
        'clin.health_issue'::text AS source

    FROM clin.health_issue c_hi

    UNION ALL

    SELECT (
    SELECT c_enc.fk_patient

      FROM clin.encounter c_enc

     WHERE (c_enc.pk = c_epi.fk_encounter)
    ) AS pk_patient
    ,
        c_epi.description AS diagnosis
    ,
        COALESCE
    (
         (
          SELECT c_hi.is_confidential

            FROM clin.health_issue c_hi

           WHERE (c_hi.pk = c_epi.fk_health_issue)
         )
         , false
    ) AS explicitely_confidential
    ,
        c_epi.diagnostic_certainty_classification
    ,
        'clin.episode'::text AS source

    FROM clin.episode c_epi

    WHERE (c_epi.is_open IS TRUE)
    UNION ALL

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_enc.assessment_of_encounter AS diagnosis
    ,
        false AS explicitely_confidential
    ,
        NULL::text AS diagnostic_certainty_classification
    ,
        'clin.encounter'::text AS source

    FROM clin.encounter c_enc

    WHERE (
         (c_enc.assessment_of_encounter IS NOT NULL)
       AND (c_enc.pk IN
               (
                SELECT c_cri.fk_encounter

                  FROM clin.clin_root_item c_cri

                 WHERE (c_cri.fk_episode IN
                           (
                            SELECT c_epi.pk

                              FROM clin.episode c_epi

                             WHERE (c_epi.is_open IS TRUE)
                           )
                     )
               )
         )
    )
    UNION ALL

    SELECT (
    SELECT c_enc.fk_patient

      FROM clin.encounter c_enc

     WHERE (c_enc.pk = c_cn.fk_encounter)
    ) AS pk_patient
    ,
        c_cn.narrative AS diagnosis
    ,
        false AS explicitely_confidential
    ,
        NULL::text AS diagnostic_certainty_classification
    ,
        'clin.clin_narrative'::text AS source

    FROM clin.clin_narrative c_cn

    WHERE (
         (c_cn.soap_cat = 'a'::text)
       AND (c_cn.fk_episode IN
               (
                SELECT c_epi.pk

                  FROM clin.episode c_epi

                 WHERE (c_epi.is_open IS TRUE)
               )
         )
    );

Index - Schema clin

## View: clin.v_edc_journal

clin.v_edc_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_p.fk_identity AS pk_patient
    ,
        c_p.modified_when
    ,
        c_p.modified_when AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_p.modified_by)
         )
         , (
               ('<'::text ||
                     (c_p.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        's'::text AS soap_cat
    ,

    (_
         ('EDC'::text) || to_char
         (
               (c_p.edc)::timestamp with time zone
               ,': YYYY Mon DD'::text
         )
    ) AS narrative
    ,

    (
    SELECT c_e.pk

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = c_p.fk_identity)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS pk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        NULL::integer AS pk_health_issue
    ,
        c_p.pk AS src_pk
    ,
        'clin.patient'::text AS src_table
    ,
        c_p.row_version
    ,
        NULL::text AS health_issue
    ,
        NULL::text AS issue_laterality
    ,
        NULL::boolean AS issue_active
    ,
        NULL::boolean AS issue_clinically_relevant
    ,
        NULL::boolean AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,
        NULL::timestamp with time zone AS encounter_started
    ,
        NULL::timestamp with time zone AS encounter_last_affirmed
    ,
        NULL::text AS encounter_type
    ,
        NULL::text AS encounter_l10n_type

    FROM clin.patient c_p

    WHERE (c_p.edc IS NOT NULL);

Index - Schema clin

## View: clin.v_emr_journal

Clinical patient data formatted into one string per clinical entity even if it constains several user- visible fields. Mainly useful for display as a simple EMR journal.

clin.v_emr_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT v_pat_narrative_journal.pk_patient
    ,
        v_pat_narrative_journal.modified_when
    ,
        v_pat_narrative_journal.clin_when
    ,
        v_pat_narrative_journal.modified_by
    ,
        v_pat_narrative_journal.soap_cat
    ,
        v_pat_narrative_journal.narrative
    ,
        v_pat_narrative_journal.pk_encounter
    ,
        v_pat_narrative_journal.pk_episode
    ,
        v_pat_narrative_journal.pk_health_issue
    ,
        v_pat_narrative_journal.src_pk
    ,
        v_pat_narrative_journal.src_table
    ,
        v_pat_narrative_journal.row_version
    ,
        v_pat_narrative_journal.health_issue
    ,
        v_pat_narrative_journal.issue_laterality
    ,
        v_pat_narrative_journal.issue_active
    ,
        v_pat_narrative_journal.issue_clinically_relevant
    ,
        v_pat_narrative_journal.issue_confidential
    ,
        v_pat_narrative_journal.episode
    ,
        v_pat_narrative_journal.episode_open
    ,
        v_pat_narrative_journal.encounter_started
    ,
        v_pat_narrative_journal.encounter_last_affirmed
    ,
        v_pat_narrative_journal.encounter_type
    ,
        v_pat_narrative_journal.encounter_l10n_type

    FROM clin.v_pat_narrative_journal

    UNION ALL

    SELECT v_health_issues_journal.pk_patient
    ,
        v_health_issues_journal.modified_when
    ,
        v_health_issues_journal.clin_when
    ,
        v_health_issues_journal.modified_by
    ,
        v_health_issues_journal.soap_cat
    ,
        v_health_issues_journal.narrative
    ,
        v_health_issues_journal.pk_encounter
    ,
        v_health_issues_journal.pk_episode
    ,
        v_health_issues_journal.pk_health_issue
    ,
        v_health_issues_journal.src_pk
    ,
        v_health_issues_journal.src_table
    ,
        v_health_issues_journal.row_version
    ,
        v_health_issues_journal.health_issue
    ,
        v_health_issues_journal.issue_laterality
    ,
        v_health_issues_journal.issue_active
    ,
        v_health_issues_journal.issue_clinically_relevant
    ,
        v_health_issues_journal.issue_confidential
    ,
        v_health_issues_journal.episode
    ,
        v_health_issues_journal.episode_open
    ,
        v_health_issues_journal.encounter_started
    ,
        v_health_issues_journal.encounter_last_affirmed
    ,
        v_health_issues_journal.encounter_type
    ,
        v_health_issues_journal.encounter_l10n_type

    FROM clin.v_health_issues_journal

    UNION ALL

    SELECT v_pat_encounters_journal.pk_patient
    ,
        v_pat_encounters_journal.modified_when
    ,
        v_pat_encounters_journal.clin_when
    ,
        v_pat_encounters_journal.modified_by
    ,
        v_pat_encounters_journal.soap_cat
    ,
        v_pat_encounters_journal.narrative
    ,
        v_pat_encounters_journal.pk_encounter
    ,
        v_pat_encounters_journal.pk_episode
    ,
        v_pat_encounters_journal.pk_health_issue
    ,
        v_pat_encounters_journal.src_pk
    ,
        v_pat_encounters_journal.src_table
    ,
        v_pat_encounters_journal.row_version
    ,
        v_pat_encounters_journal.health_issue
    ,
        v_pat_encounters_journal.issue_laterality
    ,
        v_pat_encounters_journal.issue_active
    ,
        v_pat_encounters_journal.issue_clinically_relevant
    ,
        v_pat_encounters_journal.issue_confidential
    ,
        v_pat_encounters_journal.episode
    ,
        v_pat_encounters_journal.episode_open
    ,
        v_pat_encounters_journal.encounter_started
    ,
        v_pat_encounters_journal.encounter_last_affirmed
    ,
        v_pat_encounters_journal.encounter_type
    ,
        v_pat_encounters_journal.encounter_l10n_type

    FROM clin.v_pat_encounters_journal

    UNION ALL

    SELECT v_pat_episodes_journal.pk_patient
    ,
        v_pat_episodes_journal.modified_when
    ,
        v_pat_episodes_journal.clin_when
    ,
        v_pat_episodes_journal.modified_by
    ,
        v_pat_episodes_journal.soap_cat
    ,
        v_pat_episodes_journal.narrative
    ,
        v_pat_episodes_journal.pk_encounter
    ,
        v_pat_episodes_journal.pk_episode
    ,
        v_pat_episodes_journal.pk_health_issue
    ,
        v_pat_episodes_journal.src_pk
    ,
        v_pat_episodes_journal.src_table
    ,
        v_pat_episodes_journal.row_version
    ,
        v_pat_episodes_journal.health_issue
    ,
        v_pat_episodes_journal.issue_laterality
    ,
        v_pat_episodes_journal.issue_active
    ,
        v_pat_episodes_journal.issue_clinically_relevant
    ,
        v_pat_episodes_journal.issue_confidential
    ,
        v_pat_episodes_journal.episode
    ,
        v_pat_episodes_journal.episode_open
    ,
        v_pat_episodes_journal.encounter_started
    ,
        v_pat_episodes_journal.encounter_last_affirmed
    ,
        v_pat_episodes_journal.encounter_type
    ,
        v_pat_episodes_journal.encounter_l10n_type

    FROM clin.v_pat_episodes_journal

    UNION ALL

    SELECT v_family_history_journal.pk_patient
    ,
        v_family_history_journal.modified_when
    ,
        v_family_history_journal.clin_when
    ,
        v_family_history_journal.modified_by
    ,
        v_family_history_journal.soap_cat
    ,
        v_family_history_journal.narrative
    ,
        v_family_history_journal.pk_encounter
    ,
        v_family_history_journal.pk_episode
    ,
        v_family_history_journal.pk_health_issue
    ,
        v_family_history_journal.src_pk
    ,
        v_family_history_journal.src_table
    ,
        v_family_history_journal.row_version
    ,
        v_family_history_journal.health_issue
    ,
        v_family_history_journal.issue_laterality
    ,
        v_family_history_journal.issue_active
    ,
        v_family_history_journal.issue_clinically_relevant
    ,
        v_family_history_journal.issue_confidential
    ,
        v_family_history_journal.episode
    ,
        v_family_history_journal.episode_open
    ,
        v_family_history_journal.encounter_started
    ,
        v_family_history_journal.encounter_last_affirmed
    ,
        v_family_history_journal.encounter_type
    ,
        v_family_history_journal.encounter_l10n_type

    FROM clin.v_family_history_journal

    UNION ALL

    SELECT v_pat_allergies_journal.pk_patient
    ,
        v_pat_allergies_journal.modified_when
    ,
        v_pat_allergies_journal.clin_when
    ,
        v_pat_allergies_journal.modified_by
    ,
        v_pat_allergies_journal.soap_cat
    ,
        v_pat_allergies_journal.narrative
    ,
        v_pat_allergies_journal.pk_encounter
    ,
        v_pat_allergies_journal.pk_episode
    ,
        v_pat_allergies_journal.pk_health_issue
    ,
        v_pat_allergies_journal.src_pk
    ,
        v_pat_allergies_journal.src_table
    ,
        v_pat_allergies_journal.row_version
    ,
        v_pat_allergies_journal.health_issue
    ,
        v_pat_allergies_journal.issue_laterality
    ,
        v_pat_allergies_journal.issue_active
    ,
        v_pat_allergies_journal.issue_clinically_relevant
    ,
        v_pat_allergies_journal.issue_confidential
    ,
        v_pat_allergies_journal.episode
    ,
        v_pat_allergies_journal.episode_open
    ,
        v_pat_allergies_journal.encounter_started
    ,
        v_pat_allergies_journal.encounter_last_affirmed
    ,
        v_pat_allergies_journal.encounter_type
    ,
        v_pat_allergies_journal.encounter_l10n_type

    FROM clin.v_pat_allergies_journal

    UNION ALL

    SELECT v_pat_allergy_state_journal.pk_patient
    ,
        v_pat_allergy_state_journal.modified_when
    ,
        v_pat_allergy_state_journal.clin_when
    ,
        v_pat_allergy_state_journal.modified_by
    ,
        v_pat_allergy_state_journal.soap_cat
    ,
        v_pat_allergy_state_journal.narrative
    ,
        v_pat_allergy_state_journal.pk_encounter
    ,
        v_pat_allergy_state_journal.pk_episode
    ,
        v_pat_allergy_state_journal.pk_health_issue
    ,
        v_pat_allergy_state_journal.src_pk
    ,
        v_pat_allergy_state_journal.src_table
    ,
        v_pat_allergy_state_journal.row_version
    ,
        v_pat_allergy_state_journal.health_issue
    ,
        v_pat_allergy_state_journal.issue_laterality
    ,
        v_pat_allergy_state_journal.issue_active
    ,
        v_pat_allergy_state_journal.issue_clinically_relevant
    ,
        v_pat_allergy_state_journal.issue_confidential
    ,
        v_pat_allergy_state_journal.episode
    ,
        v_pat_allergy_state_journal.episode_open
    ,
        v_pat_allergy_state_journal.encounter_started
    ,
        v_pat_allergy_state_journal.encounter_last_affirmed
    ,
        v_pat_allergy_state_journal.encounter_type
    ,
        v_pat_allergy_state_journal.encounter_l10n_type

    FROM clin.v_pat_allergy_state_journal

    UNION ALL

    SELECT v_test_results_journal.pk_patient
    ,
        v_test_results_journal.modified_when
    ,
        v_test_results_journal.clin_when
    ,
        v_test_results_journal.modified_by
    ,
        v_test_results_journal.soap_cat
    ,
        v_test_results_journal.narrative
    ,
        v_test_results_journal.pk_encounter
    ,
        v_test_results_journal.pk_episode
    ,
        v_test_results_journal.pk_health_issue
    ,
        v_test_results_journal.src_pk
    ,
        v_test_results_journal.src_table
    ,
        v_test_results_journal.row_version
    ,
        v_test_results_journal.health_issue
    ,
        v_test_results_journal.issue_laterality
    ,
        v_test_results_journal.issue_active
    ,
        v_test_results_journal.issue_clinically_relevant
    ,
        v_test_results_journal.issue_confidential
    ,
        v_test_results_journal.episode
    ,
        v_test_results_journal.episode_open
    ,
        v_test_results_journal.encounter_started
    ,
        v_test_results_journal.encounter_last_affirmed
    ,
        v_test_results_journal.encounter_type
    ,
        v_test_results_journal.encounter_l10n_type

    FROM clin.v_test_results_journal

    UNION ALL

    SELECT v_hospital_stays_journal.pk_patient
    ,
        v_hospital_stays_journal.modified_when
    ,
        v_hospital_stays_journal.clin_when
    ,
        v_hospital_stays_journal.modified_by
    ,
        v_hospital_stays_journal.soap_cat
    ,
        v_hospital_stays_journal.narrative
    ,
        v_hospital_stays_journal.pk_encounter
    ,
        v_hospital_stays_journal.pk_episode
    ,
        v_hospital_stays_journal.pk_health_issue
    ,
        v_hospital_stays_journal.src_pk
    ,
        v_hospital_stays_journal.src_table
    ,
        v_hospital_stays_journal.row_version
    ,
        v_hospital_stays_journal.health_issue
    ,
        v_hospital_stays_journal.issue_laterality
    ,
        v_hospital_stays_journal.issue_active
    ,
        v_hospital_stays_journal.issue_clinically_relevant
    ,
        v_hospital_stays_journal.issue_confidential
    ,
        v_hospital_stays_journal.episode
    ,
        v_hospital_stays_journal.episode_open
    ,
        v_hospital_stays_journal.encounter_started
    ,
        v_hospital_stays_journal.encounter_last_affirmed
    ,
        v_hospital_stays_journal.encounter_type
    ,
        v_hospital_stays_journal.encounter_l10n_type

    FROM clin.v_hospital_stays_journal

    UNION ALL

    SELECT v_doc_med_journal.pk_patient
    ,
        v_doc_med_journal.modified_when
    ,
        v_doc_med_journal.clin_when
    ,
        v_doc_med_journal.modified_by
    ,
        v_doc_med_journal.soap_cat
    ,
        v_doc_med_journal.narrative
    ,
        v_doc_med_journal.pk_encounter
    ,
        v_doc_med_journal.pk_episode
    ,
        v_doc_med_journal.pk_health_issue
    ,
        v_doc_med_journal.src_pk
    ,
        v_doc_med_journal.src_table
    ,
        v_doc_med_journal.row_version
    ,
        v_doc_med_journal.health_issue
    ,
        v_doc_med_journal.issue_laterality
    ,
        v_doc_med_journal.issue_active
    ,
        v_doc_med_journal.issue_clinically_relevant
    ,
        v_doc_med_journal.issue_confidential
    ,
        v_doc_med_journal.episode
    ,
        v_doc_med_journal.episode_open
    ,
        v_doc_med_journal.encounter_started
    ,
        v_doc_med_journal.encounter_last_affirmed
    ,
        v_doc_med_journal.encounter_type
    ,
        v_doc_med_journal.encounter_l10n_type

    FROM blobs.v_doc_med_journal

    UNION ALL

    SELECT v_substance_intake_journal.pk_patient
    ,
        v_substance_intake_journal.modified_when
    ,
        v_substance_intake_journal.clin_when
    ,
        v_substance_intake_journal.modified_by
    ,
        v_substance_intake_journal.soap_cat
    ,
        v_substance_intake_journal.narrative
    ,
        v_substance_intake_journal.pk_encounter
    ,
        v_substance_intake_journal.pk_episode
    ,
        v_substance_intake_journal.pk_health_issue
    ,
        v_substance_intake_journal.src_pk
    ,
        v_substance_intake_journal.src_table
    ,
        v_substance_intake_journal.row_version
    ,
        v_substance_intake_journal.health_issue
    ,
        v_substance_intake_journal.issue_laterality
    ,
        v_substance_intake_journal.issue_active
    ,
        v_substance_intake_journal.issue_clinically_relevant
    ,
        v_substance_intake_journal.issue_confidential
    ,
        v_substance_intake_journal.episode
    ,
        v_substance_intake_journal.episode_open
    ,
        v_substance_intake_journal.encounter_started
    ,
        v_substance_intake_journal.encounter_last_affirmed
    ,
        v_substance_intake_journal.encounter_type
    ,
        v_substance_intake_journal.encounter_l10n_type

    FROM clin.v_substance_intake_journal

    UNION ALL

    SELECT v_procedures_journal.pk_patient
    ,
        v_procedures_journal.modified_when
    ,
        v_procedures_journal.clin_when
    ,
        v_procedures_journal.modified_by
    ,
        v_procedures_journal.soap_cat
    ,
        v_procedures_journal.narrative
    ,
        v_procedures_journal.pk_encounter
    ,
        v_procedures_journal.pk_episode
    ,
        v_procedures_journal.pk_health_issue
    ,
        v_procedures_journal.src_pk
    ,
        v_procedures_journal.src_table
    ,
        v_procedures_journal.row_version
    ,
        v_procedures_journal.health_issue
    ,
        v_procedures_journal.issue_laterality
    ,
        v_procedures_journal.issue_active
    ,
        v_procedures_journal.issue_clinically_relevant
    ,
        v_procedures_journal.issue_confidential
    ,
        v_procedures_journal.episode
    ,
        v_procedures_journal.episode_open
    ,
        v_procedures_journal.encounter_started
    ,
        v_procedures_journal.encounter_last_affirmed
    ,
        v_procedures_journal.encounter_type
    ,
        v_procedures_journal.encounter_l10n_type

    FROM clin.v_procedures_journal

    UNION ALL

    SELECT v_vaccinations_journal.pk_patient
    ,
        v_vaccinations_journal.modified_when
    ,
        v_vaccinations_journal.clin_when
    ,
        v_vaccinations_journal.modified_by
    ,
        v_vaccinations_journal.soap_cat
    ,
        v_vaccinations_journal.narrative
    ,
        v_vaccinations_journal.pk_encounter
    ,
        v_vaccinations_journal.pk_episode
    ,
        v_vaccinations_journal.pk_health_issue
    ,
        v_vaccinations_journal.src_pk
    ,
        v_vaccinations_journal.src_table
    ,
        v_vaccinations_journal.row_version
    ,
        v_vaccinations_journal.health_issue
    ,
        v_vaccinations_journal.issue_laterality
    ,
        v_vaccinations_journal.issue_active
    ,
        v_vaccinations_journal.issue_clinically_relevant
    ,
        v_vaccinations_journal.issue_confidential
    ,
        v_vaccinations_journal.episode
    ,
        v_vaccinations_journal.episode_open
    ,
        v_vaccinations_journal.encounter_started
    ,
        v_vaccinations_journal.encounter_last_affirmed
    ,
        v_vaccinations_journal.encounter_type
    ,
        v_vaccinations_journal.encounter_l10n_type

    FROM clin.v_vaccinations_journal

    UNION ALL

    SELECT v_suppressed_hints_journal.pk_patient
    ,
        v_suppressed_hints_journal.modified_when
    ,
        v_suppressed_hints_journal.clin_when
    ,
        v_suppressed_hints_journal.modified_by
    ,
        v_suppressed_hints_journal.soap_cat
    ,
        v_suppressed_hints_journal.narrative
    ,
        v_suppressed_hints_journal.fk_encounter AS pk_encounter
    ,
        v_suppressed_hints_journal.pk_episode
    ,
        v_suppressed_hints_journal.pk_health_issue
    ,
        v_suppressed_hints_journal.src_pk
    ,
        v_suppressed_hints_journal.src_table
    ,
        v_suppressed_hints_journal.row_version
    ,
        v_suppressed_hints_journal.health_issue
    ,
        v_suppressed_hints_journal.issue_laterality
    ,
        v_suppressed_hints_journal.issue_active
    ,
        v_suppressed_hints_journal.issue_clinically_relevant
    ,
        v_suppressed_hints_journal.issue_confidential
    ,
        v_suppressed_hints_journal.episode
    ,
        v_suppressed_hints_journal.episode_open
    ,
        v_suppressed_hints_journal.encounter_started
    ,
        v_suppressed_hints_journal.encounter_last_affirmed
    ,
        v_suppressed_hints_journal.encounter_type
    ,
        v_suppressed_hints_journal.encounter_l10n_type

    FROM clin.v_suppressed_hints_journal

    UNION ALL

    SELECT v_external_care_journal.pk_patient
    ,
        v_external_care_journal.modified_when
    ,
        v_external_care_journal.clin_when
    ,
        v_external_care_journal.modified_by
    ,
        v_external_care_journal.soap_cat
    ,
        v_external_care_journal.narrative
    ,
        v_external_care_journal.pk_encounter
    ,
        v_external_care_journal.pk_episode
    ,
        v_external_care_journal.pk_health_issue
    ,
        v_external_care_journal.src_pk
    ,
        v_external_care_journal.src_table
    ,
        v_external_care_journal.row_version
    ,
        v_external_care_journal.health_issue
    ,
        v_external_care_journal.issue_laterality
    ,
        v_external_care_journal.issue_active
    ,
        v_external_care_journal.issue_clinically_relevant
    ,
        v_external_care_journal.issue_confidential
    ,
        v_external_care_journal.episode
    ,
        v_external_care_journal.episode_open
    ,
        v_external_care_journal.encounter_started
    ,
        v_external_care_journal.encounter_last_affirmed
    ,
        v_external_care_journal.encounter_type
    ,
        v_external_care_journal.encounter_l10n_type

    FROM clin.v_external_care_journal

    UNION ALL

    SELECT v_edc_journal.pk_patient
    ,
        v_edc_journal.modified_when
    ,
        v_edc_journal.clin_when
    ,
        v_edc_journal.modified_by
    ,
        v_edc_journal.soap_cat
    ,
        v_edc_journal.narrative
    ,
        v_edc_journal.pk_encounter
    ,
        v_edc_journal.pk_episode
    ,
        v_edc_journal.pk_health_issue
    ,
        v_edc_journal.src_pk
    ,
        v_edc_journal.src_table
    ,
        v_edc_journal.row_version
    ,
        v_edc_journal.health_issue
    ,
        v_edc_journal.issue_laterality
    ,
        v_edc_journal.issue_active
    ,
        v_edc_journal.issue_clinically_relevant
    ,
        v_edc_journal.issue_confidential
    ,
        v_edc_journal.episode
    ,
        v_edc_journal.episode_open
    ,
        v_edc_journal.encounter_started
    ,
        v_edc_journal.encounter_last_affirmed
    ,
        v_edc_journal.encounter_type
    ,
        v_edc_journal.encounter_l10n_type

    FROM clin.v_edc_journal

    UNION ALL

    SELECT v_reminders_journal.pk_patient
    ,
        v_reminders_journal.modified_when
    ,
        v_reminders_journal.clin_when
    ,
        v_reminders_journal.modified_by
    ,
        v_reminders_journal.soap_cat
    ,
        v_reminders_journal.narrative
    ,
        v_reminders_journal.pk_encounter
    ,
        v_reminders_journal.pk_episode
    ,
        v_reminders_journal.pk_health_issue
    ,
        v_reminders_journal.src_pk
    ,
        v_reminders_journal.src_table
    ,
        v_reminders_journal.row_version
    ,
        v_reminders_journal.health_issue
    ,
        v_reminders_journal.issue_laterality
    ,
        v_reminders_journal.issue_active
    ,
        v_reminders_journal.issue_clinically_relevant
    ,
        v_reminders_journal.issue_confidential
    ,
        v_reminders_journal.episode
    ,
        v_reminders_journal.episode_open
    ,
        v_reminders_journal.encounter_started
    ,
        v_reminders_journal.encounter_last_affirmed
    ,
        v_reminders_journal.encounter_type
    ,
        v_reminders_journal.encounter_l10n_type

    FROM clin.v_reminders_journal;

Index - Schema clin

## View: clin.v_export_items

clin.v_export_items Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT inner_export_items.pk_export_item
    ,
        inner_export_items.pk_identity
    ,
        inner_export_items.created_by
    ,
        inner_export_items.created_when
    ,
        inner_export_items.designation
    ,
        inner_export_items.description
    ,
        inner_export_items.pk_doc_obj
    ,
        inner_export_items.md5_sum
    ,
        inner_export_items.size
    ,
        inner_export_items.filename
    ,
        inner_export_items.pk_identity_raw
    ,
        inner_export_items.xmin_export_item
    ,

    (inner_export_items.pk_identity IS DISTINCT
      FROM inner_export_items.pk_identity_raw
    ) AS pk_identity_raw_needs_update
    ,
        d_vp.title
    ,
        d_vp.firstnames
    ,
        d_vp.lastnames
    ,
        d_vp.preferred
    ,
        d_vp.gender
    ,
        d_vp.dob

    FROM (
         (
          SELECT c_ei.pk AS pk_export_item
               ,
                    CASE
                        WHEN
               (c_ei.fk_doc_obj IS NULL) THEN c_ei.fk_identity
                        ELSE
               (
                SELECT encounter.fk_patient

                  FROM clin.encounter

                 WHERE (encounter.pk =
                           (
                            SELECT doc_med.fk_encounter

                              FROM blobs.doc_med

                             WHERE (doc_med.pk =
                                       (
                                        SELECT doc_obj.fk_doc

                                          FROM blobs.doc_obj

                                         WHERE (doc_obj.pk = c_ei.fk_doc_obj)
                                       )
                                 )
                           )
                     )
               )
                    END AS pk_identity
               ,
                COALESCE
               (
                     (
                      SELECT staff.short_alias

                        FROM dem.staff

                       WHERE (staff.db_user = c_ei.created_by)
                     )
                     , (c_ei.created_by)::text
               ) AS created_by
               ,
                c_ei.created_when
               ,
                c_ei.designation
               ,
                c_ei.description
               ,
                c_ei.fk_doc_obj AS pk_doc_obj
               ,
                md5
               (COALESCE
                     (c_ei.data
                           , COALESCE
                           (
                                 (
                                  SELECT b_do.data

                                    FROM blobs.doc_obj b_do

                                   WHERE (b_do.pk = c_ei.fk_doc_obj)
                                 )
                                 ,'\x'::bytea
                           )
                     )
               ) AS md5_sum
               ,
                octet_length
               (COALESCE
                     (c_ei.data
                           ,'\x'::bytea
                     )
               ) AS size
               ,
                COALESCE
               (c_ei.filename
                     , (
                      SELECT b_do.filename

                        FROM blobs.doc_obj b_do

                       WHERE (b_do.pk = c_ei.fk_doc_obj)
                     )
               ) AS filename
               ,
                c_ei.fk_identity AS pk_identity_raw
               ,
                c_ei.xmin AS xmin_export_item

            FROM clin.export_item c_ei
         ) inner_export_items

      JOIN dem.v_all_persons d_vp
        ON (
               (d_vp.pk_identity = inner_export_items.pk_identity)
         )
    );

Index - Schema clin

## View: clin.v_external_care

clin.v_external_care Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_ec.pk AS pk_external_care
    ,

    (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = c_ec.fk_encounter)
    ) AS pk_identity
    ,
        COALESCE
    (c_ec.issue
         , c_hi.description
    ) AS issue
    ,
        c_ec.provider
    ,
        d_ou.description AS unit
    ,
        d_o.description AS organization
    ,
        c_ec.comment
    ,
        c_ec.inactive
    ,
        c_ec.fk_health_issue AS pk_health_issue
    ,
        c_ec.fk_org_unit AS pk_org_unit
    ,
        c_ec.fk_encounter AS pk_encounter
    ,
        c_ec.xmin AS xmin_external_care
    ,
        c_ec.modified_when
    ,
        c_ec.modified_by
    ,
        c_ec.row_version

    FROM (
         (
               (clin.external_care c_ec

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_hi.pk = c_ec.fk_health_issue)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (c_ec.fk_org_unit = d_ou.pk)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_ou.fk_org = d_o.pk)
         )
    );

Index - Schema clin

## View: clin.v_external_care_journal

clin.v_external_care_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_ec.modified_when
    ,
        c_ec.modified_when AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_ec.modified_by)
         )
         , (
               ('<'::text ||
                     (c_ec.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        's'::text AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (_
                                                                                       ('External care'::text) ||
            CASE
                WHEN c_ec.inactive THEN
                                                                                       (
                                                                                             (
                                                                                                ' ('::text || _
                                                                                                         ('inactive'::text)
                                                                                                   ) ||
                                                                                           ')'::text
                                                                                       )
                ELSE ''::text
            END
                                                                                 ) || COALESCE
                                                                                 (
                                                                                       (
                                                                                             (
                                                                                                   (' '::text || _
                                                                                                         ('by'::text)
                                                                                                   ) || ' '::text
                                                                                             ) || c_ec.provider
                                                                                       )
                                                                                       ,''::text
                                                                                 )
                                                                           ) || ' @ '::text
                                                                     ) || d_ou.description
                                                               ) || ' '::text
                                                         ) || _
                                                         ('of'::text)
                                                   ) || ' '::text
                                             ) || d_o.description
                                       ) || '
    '::text
                                 ) || _
                                 ('Issue:'::text)
                           ) || ' '::text
                     ) || COALESCE
                     (c_hi.description
                           , c_ec.issue
                     )
               ) || '
    '::text
         ) || COALESCE
         (
               (
                     (_
                           ('Comment:'::text) || ' '::text
                     ) || c_ec.comment
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_ec.fk_encounter AS pk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        c_ec.fk_health_issue AS pk_health_issue
    ,
        c_ec.pk AS src_pk
    ,
        'clin.external_care'::text AS src_table
    ,
        c_ec.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (clin.external_care c_ec

                              JOIN clin.encounter c_enc
                                ON (
                                       (c_ec.fk_encounter = c_enc.pk)
                                 )
                           )

                        JOIN clin.encounter_type c_ety
                          ON (
                                 (c_enc.fk_type = c_ety.pk)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_ec.fk_health_issue = c_hi.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (c_ec.fk_org_unit = d_ou.pk)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_ou.fk_org = d_o.pk)
         )
    );

Index - Schema clin

## View: clin.v_family_history

family history denormalized

clin.v_family_history Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_fh.pk AS pk_family_history
    ,
        cenc.fk_patient AS pk_patient
    ,
        c_fh.soap_cat
    ,
        c_fhrt.description AS relation
    ,
        _
    (c_fhrt.description) AS l10n_relation
    ,
        c_fh.narrative AS condition
    ,
        c_fh.age_noted
    ,
        c_fh.age_of_death
    ,
        c_fh.contributed_to_death
    ,
        c_fh.comment
    ,
        cep.description AS episode
    ,
        c_fh.clin_when AS when_known_to_patient
    ,
        c_fh.name_relative
    ,
        c_fh.dob_relative
    ,
        c_fhrt.is_genetic AS is_genetic_relative
    ,
        c_fh.fk_encounter AS pk_encounter
    ,
        c_fh.fk_episode AS pk_episode
    ,
        cep.fk_health_issue AS pk_health_issue
    ,
        c_fhrt.pk AS pk_fhx_relation_type
    ,
        c_fh.modified_when
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2fhx.fk_generic_code) AS array_agg

            FROM clin.lnk_code2fhx c_lc2fhx

           WHERE (c_lc2fhx.fk_item = c_fh.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    ,
        c_fh.xmin AS xmin_family_history

    FROM (
         (
               (clin.family_history c_fh

                  JOIN clin.encounter cenc
                    ON (
                           (c_fh.fk_encounter = cenc.pk)
                     )
               )

            JOIN clin.episode cep
              ON (
                     (c_fh.fk_episode = cep.pk)
               )
         )

    LEFT JOIN clin.fhx_relation_type c_fhrt
        ON (
               (c_fh.fk_relation_type = c_fhrt.pk)
         )
    );

Index - Schema clin

## View: clin.v_family_history_journal

clin.v_family_history_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_fh.modified_when
    ,
        c_fh.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_fh.modified_by)
         )
         , (
               ('<'::text ||
                     (c_fh.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_fh.soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (_
                                                                           (c_fhrt.description) || COALESCE
                                                                           (
                                                                                 (' @ '::text || c_fh.age_noted)
                                                                                 ,''::text
                                                                           )
                                                                     ) || ': '::text
                                                               ) || c_fh.narrative
                                                         ) || '
    '::text
                                                   ) || ' '::text
                                             ) ||
            CASE
                WHEN
                                             (c_fh.contributed_to_death IS TRUE) THEN
                                             (_
                                                   ('contributed to death'::text) || ' '::text
                                             )
                ELSE ''::text
            END
                                       ) || COALESCE
                                       (
                                             ('@ '::text ||
                                                   (justify_interval
                                                         (c_fh.age_of_death)
                                                   )::text
                                             )
                                             ,''::text
                                       )
                                 ) || '
    '::text
                           ) || COALESCE
                           (
                                 (
                                       (' '::text || c_fh.name_relative) ||
                                     ','::text
                                 )
                                 ,''::text
                           )
                     ) || COALESCE
                     (
                           (' '::text || to_char
                                 (c_fh.dob_relative
                                       ,'YYYY-MM-DD'::text
                                 )
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     ('
     '::text || c_fh.comment)
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (';
    '::text || array_to_string
                           (
                                 (
                                  SELECT array_agg
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (r_csr.code ||
                                                                                          ' ('::text) || r_ds.name_short
                                                                                       ) || ' - '::text
                                                                                 ) || r_ds.version
                                                                           ) || ' - '::text
                                                                     ) || r_ds.lang
                                                               ) ||
                                                     '): '::text
                                                   ) || r_csr.term
                                             )
                                       ) AS array_agg

                                    FROM (
                                             (clin.lnk_code2fhx c_lc2fhx

                                                JOIN ref.coding_system_root r_csr
                                                  ON (
                                                         (c_lc2fhx.fk_generic_code = r_csr.pk_coding_system)
                                                   )
                                             )

                                          JOIN ref.data_source r_ds
                                            ON (
                                                   (r_ds.pk = r_csr.fk_data_source)
                                             )
                                       )

                                   WHERE (c_lc2fhx.fk_item = c_fh.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_fh.fk_encounter AS pk_encounter
    ,
        c_fh.fk_episode AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        c_fh.pk AS src_pk
    ,
        'clin.family_history'::text AS src_table
    ,
        c_fh.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (clin.family_history c_fh

                              JOIN clin.encounter c_enc
                                ON (
                                       (c_fh.fk_encounter = c_enc.pk)
                                 )
                           )

                        JOIN clin.encounter_type c_ety
                          ON (
                                 (c_enc.fk_type = c_ety.pk)
                           )
                     )

                  JOIN clin.episode c_epi
                    ON (
                           (c_fh.fk_episode = c_epi.pk)
                     )
               )

       LEFT JOIN clin.fhx_relation_type c_fhrt
              ON (
                     (c_fh.fk_relation_type = c_fhrt.pk)
               )
         )

    LEFT JOIN clin.health_issue c_hi
        ON (
               (c_epi.fk_health_issue = c_hi.pk)
         )
    );

Index - Schema clin

## View: clin.v_health_issues

clin.v_health_issues Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = c_hi.fk_encounter)
    ) AS pk_patient
    ,
        c_hi.pk AS pk_health_issue
    ,
        c_hi.description
    ,
        c_hi.summary
    ,
        c_hi.laterality
    ,
        c_hi.age_noted
    ,
        c_hi.is_active
    ,
        c_hi.clinically_relevant
    ,
        c_hi.is_confidential
    ,
        c_hi.is_cause_of_death
    ,
        c_hi.fk_encounter AS pk_encounter
    ,
        c_hi.modified_when
    ,
        c_hi.modified_by
    ,
        c_hi.row_version
    ,
        c_hi."grouping"
    ,
        c_hi.diagnostic_certainty_classification
    ,

    (EXISTS
         (
          SELECT 1

            FROM clin.episode c_ep

           WHERE (
                     (c_ep.fk_health_issue = c_hi.pk)
                   AND (c_ep.is_open IS TRUE)
               )
             LIMIT 1
         )
    ) AS has_open_episode
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2h.fk_generic_code) AS array_agg

            FROM clin.lnk_code2h_issue c_lc2h

           WHERE (c_lc2h.fk_item = c_hi.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    ,
        c_hi.xmin AS xmin_health_issue

    FROM clin.health_issue c_hi;

Index - Schema clin

## View: clin.v_health_issues_journal

clin.v_health_issues_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_hi.modified_when
    ,
        COALESCE
    (
         (
          SELECT (identity.dob + c_hi.age_noted)

            FROM dem.identity

           WHERE (identity.pk =
                     (
                      SELECT encounter.fk_patient

                        FROM clin.encounter

                       WHERE (encounter.pk = c_hi.fk_encounter)
                     )
               )
         )
         , c_enc.started
    ) AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_hi.modified_by)
         )
         , (
               ('<'::text ||
                     (c_hi.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        'a'::text AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (_
                                                                                 ('Health Issue'::text) ||
                                                                              ' ('::text) ||
            CASE
                WHEN c_hi.is_active THEN _
                                                                                 ('active'::text)
                ELSE _
                                                                                 ('inactive'::text)
            END
                                                                           ) ||
                                                                        ', '::text
                                                                     ) ||
            CASE
                WHEN c_hi.clinically_relevant THEN _
                                                                     ('clinically relevant'::text)
                ELSE _
                                                                     ('clinically not relevant'::text)
            END
                                                               ) || COALESCE
                                                               (
                                                                     (
                                                                        ', '::text || c_hi.diagnostic_certainty_classification
                                                                     )
                                                                     ,''::text
                                                               )
                                                         ) ||
                                               '): '::text
                                             ) || c_hi.description
                                       ) || COALESCE
                                       (
                                             (
                                                   (
                                                         (
                                                               (';
    '::text || _
                                                                     ('noted at age'::text)
                                                               ) || ': '::text
                                                         ) ||
                                                         (c_hi.age_noted)::text
                                                   ) || ';
    '::text
                                             )
                                             ,';
    '::text
                                       )
                                 ) || COALESCE
                                 (
                                       (
                                             (
                                                   (_
                                                         ('Laterality'::text) || ': '::text
                                                   ) ||
                                                   (c_hi.laterality)::text
                                             ) || ' / '::text
                                       )
                                       ,''::text
                                 )
                           ) ||
            CASE
                WHEN c_hi.is_confidential THEN
                           (_
                                 ('confidential'::text) || ' / '::text
                           )
                ELSE ''::text
            END
                     ) ||
            CASE
                WHEN c_hi.is_cause_of_death THEN _
                     ('cause of death'::text)
                ELSE ''::text
            END
               ) || COALESCE
               (
                     (
                           (
                                 (';
    '::text || _
                                       ('Summary'::text)
                                 ) || ':
    '::text
                           ) || c_hi.summary
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (';
    '::text || array_to_string
                           (
                                 (
                                  SELECT array_agg
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (r_csr.code ||
                                                                                          ' ('::text) || r_ds.name_short
                                                                                       ) || ' - '::text
                                                                                 ) || r_ds.version
                                                                           ) || ' - '::text
                                                                     ) || r_ds.lang
                                                               ) ||
                                                     '): '::text
                                                   ) || r_csr.term
                                             )
                                       ) AS array_agg

                                    FROM (
                                             (clin.lnk_code2h_issue c_lc2h

                                                JOIN ref.coding_system_root r_csr
                                                  ON (
                                                         (c_lc2h.fk_generic_code = r_csr.pk_coding_system)
                                                   )
                                             )

                                          JOIN ref.data_source r_ds
                                            ON (
                                                   (r_ds.pk = r_csr.fk_data_source)
                                             )
                                       )

                                   WHERE (c_lc2h.fk_item = c_hi.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_hi.fk_encounter AS pk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        c_hi.pk AS pk_health_issue
    ,
        c_hi.pk AS src_pk
    ,
        'clin.health_issue'::text AS src_table
    ,
        c_hi.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (clin.health_issue c_hi

            JOIN clin.encounter c_enc
              ON (
                     (c_hi.fk_encounter = c_enc.pk)
               )
         )

      JOIN clin.encounter_type c_ety
        ON (
               (c_enc.fk_type = c_ety.pk)
         )
    );

Index - Schema clin

## View: clin.v_hospital_stays

clin.v_hospital_stays Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_hs.pk AS pk_hospital_stay
    ,

    (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = c_hs.fk_encounter)
    ) AS pk_patient
    ,
        d_o.description AS hospital
    ,
        d_ou.description AS ward
    ,
        c_hs.narrative AS comment
    ,
        c_hs.clin_when AS admission
    ,
        c_hs.discharge
    ,
        c_hs.soap_cat
    ,
        c_e.description AS episode
    ,
        c_hi.description AS health_issue
    ,
        c_hs.fk_encounter AS pk_encounter
    ,
        c_hs.fk_episode AS pk_episode
    ,
        c_hi.pk AS pk_health_issue
    ,
        c_hs.fk_org_unit AS pk_org_unit
    ,
        d_o.pk AS pk_org
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (b_dm.pk) AS array_agg

            FROM blobs.doc_med b_dm

           WHERE (b_dm.fk_hospital_stay = c_hs.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_documents
    ,
        c_hs.modified_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_hs.modified_by)
         )
         , (
               ('<'::text ||
                     (c_hs.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_hs.row_version
    ,
        c_hs.xmin AS xmin_hospital_stay

    FROM (
         (
               (
                     (clin.hospital_stay c_hs

                   LEFT JOIN clin.episode c_e
                          ON (
                                 (c_e.pk = c_hs.fk_episode)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_hi.pk = c_e.fk_health_issue)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (d_ou.pk = c_hs.fk_org_unit)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_o.pk = d_ou.fk_org)
         )
    );

Index - Schema clin

## View: clin.v_hospital_stays_journal

clin.v_hospital_stays_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT v_hospital_stays_journal_no_discharge.pk_patient
    ,
        v_hospital_stays_journal_no_discharge.modified_when
    ,
        v_hospital_stays_journal_no_discharge.clin_when
    ,
        v_hospital_stays_journal_no_discharge.modified_by
    ,
        v_hospital_stays_journal_no_discharge.soap_cat
    ,
        v_hospital_stays_journal_no_discharge.narrative
    ,
        v_hospital_stays_journal_no_discharge.pk_encounter
    ,
        v_hospital_stays_journal_no_discharge.pk_episode
    ,
        v_hospital_stays_journal_no_discharge.pk_health_issue
    ,
        v_hospital_stays_journal_no_discharge.src_pk
    ,
        v_hospital_stays_journal_no_discharge.src_table
    ,
        v_hospital_stays_journal_no_discharge.row_version
    ,
        v_hospital_stays_journal_no_discharge.health_issue
    ,
        v_hospital_stays_journal_no_discharge.issue_laterality
    ,
        v_hospital_stays_journal_no_discharge.issue_active
    ,
        v_hospital_stays_journal_no_discharge.issue_clinically_relevant
    ,
        v_hospital_stays_journal_no_discharge.issue_confidential
    ,
        v_hospital_stays_journal_no_discharge.episode
    ,
        v_hospital_stays_journal_no_discharge.episode_open
    ,
        v_hospital_stays_journal_no_discharge.encounter_started
    ,
        v_hospital_stays_journal_no_discharge.encounter_last_affirmed
    ,
        v_hospital_stays_journal_no_discharge.encounter_type
    ,
        v_hospital_stays_journal_no_discharge.encounter_l10n_type

    FROM clin.v_hospital_stays_journal_no_discharge

    UNION ALL

    SELECT v_hospital_stays_journal_one_day.pk_patient
    ,
        v_hospital_stays_journal_one_day.modified_when
    ,
        v_hospital_stays_journal_one_day.clin_when
    ,
        v_hospital_stays_journal_one_day.modified_by
    ,
        v_hospital_stays_journal_one_day.soap_cat
    ,
        v_hospital_stays_journal_one_day.narrative
    ,
        v_hospital_stays_journal_one_day.pk_encounter
    ,
        v_hospital_stays_journal_one_day.pk_episode
    ,
        v_hospital_stays_journal_one_day.pk_health_issue
    ,
        v_hospital_stays_journal_one_day.src_pk
    ,
        v_hospital_stays_journal_one_day.src_table
    ,
        v_hospital_stays_journal_one_day.row_version
    ,
        v_hospital_stays_journal_one_day.health_issue
    ,
        v_hospital_stays_journal_one_day.issue_laterality
    ,
        v_hospital_stays_journal_one_day.issue_active
    ,
        v_hospital_stays_journal_one_day.issue_clinically_relevant
    ,
        v_hospital_stays_journal_one_day.issue_confidential
    ,
        v_hospital_stays_journal_one_day.episode
    ,
        v_hospital_stays_journal_one_day.episode_open
    ,
        v_hospital_stays_journal_one_day.encounter_started
    ,
        v_hospital_stays_journal_one_day.encounter_last_affirmed
    ,
        v_hospital_stays_journal_one_day.encounter_type
    ,
        v_hospital_stays_journal_one_day.encounter_l10n_type

    FROM clin.v_hospital_stays_journal_one_day

    UNION ALL

    SELECT v_hospital_stays_journal_multi_day_adm.pk_patient
    ,
        v_hospital_stays_journal_multi_day_adm.modified_when
    ,
        v_hospital_stays_journal_multi_day_adm.clin_when
    ,
        v_hospital_stays_journal_multi_day_adm.modified_by
    ,
        v_hospital_stays_journal_multi_day_adm.soap_cat
    ,
        v_hospital_stays_journal_multi_day_adm.narrative
    ,
        v_hospital_stays_journal_multi_day_adm.pk_encounter
    ,
        v_hospital_stays_journal_multi_day_adm.pk_episode
    ,
        v_hospital_stays_journal_multi_day_adm.pk_health_issue
    ,
        v_hospital_stays_journal_multi_day_adm.src_pk
    ,
        v_hospital_stays_journal_multi_day_adm.src_table
    ,
        v_hospital_stays_journal_multi_day_adm.row_version
    ,
        v_hospital_stays_journal_multi_day_adm.health_issue
    ,
        v_hospital_stays_journal_multi_day_adm.issue_laterality
    ,
        v_hospital_stays_journal_multi_day_adm.issue_active
    ,
        v_hospital_stays_journal_multi_day_adm.issue_clinically_relevant
    ,
        v_hospital_stays_journal_multi_day_adm.issue_confidential
    ,
        v_hospital_stays_journal_multi_day_adm.episode
    ,
        v_hospital_stays_journal_multi_day_adm.episode_open
    ,
        v_hospital_stays_journal_multi_day_adm.encounter_started
    ,
        v_hospital_stays_journal_multi_day_adm.encounter_last_affirmed
    ,
        v_hospital_stays_journal_multi_day_adm.encounter_type
    ,
        v_hospital_stays_journal_multi_day_adm.encounter_l10n_type

    FROM clin.v_hospital_stays_journal_multi_day_adm

    UNION ALL

    SELECT v_hospital_stays_journal_multi_day_dis.pk_patient
    ,
        v_hospital_stays_journal_multi_day_dis.modified_when
    ,
        v_hospital_stays_journal_multi_day_dis.clin_when
    ,
        v_hospital_stays_journal_multi_day_dis.modified_by
    ,
        v_hospital_stays_journal_multi_day_dis.soap_cat
    ,
        v_hospital_stays_journal_multi_day_dis.narrative
    ,
        v_hospital_stays_journal_multi_day_dis.pk_encounter
    ,
        v_hospital_stays_journal_multi_day_dis.pk_episode
    ,
        v_hospital_stays_journal_multi_day_dis.pk_health_issue
    ,
        v_hospital_stays_journal_multi_day_dis.src_pk
    ,
        v_hospital_stays_journal_multi_day_dis.src_table
    ,
        v_hospital_stays_journal_multi_day_dis.row_version
    ,
        v_hospital_stays_journal_multi_day_dis.health_issue
    ,
        v_hospital_stays_journal_multi_day_dis.issue_laterality
    ,
        v_hospital_stays_journal_multi_day_dis.issue_active
    ,
        v_hospital_stays_journal_multi_day_dis.issue_clinically_relevant
    ,
        v_hospital_stays_journal_multi_day_dis.issue_confidential
    ,
        v_hospital_stays_journal_multi_day_dis.episode
    ,
        v_hospital_stays_journal_multi_day_dis.episode_open
    ,
        v_hospital_stays_journal_multi_day_dis.encounter_started
    ,
        v_hospital_stays_journal_multi_day_dis.encounter_last_affirmed
    ,
        v_hospital_stays_journal_multi_day_dis.encounter_type
    ,
        v_hospital_stays_journal_multi_day_dis.encounter_l10n_type

    FROM clin.v_hospital_stays_journal_multi_day_dis;

Index - Schema clin

## View: clin.v_hospital_stays_journal_multi_day_adm

clin.v_hospital_stays_journal_multi_day_adm Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_hs.modified_when
    ,
        c_hs.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_hs.modified_by)
         )
         , (
               ('<'::text ||
                     (c_hs.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_hs.soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (
                                                                                             (
                                                                                                   (
                                                                                                         (
                                                                                                               (
                                                                                                                     (_
                                                                                                                           ('hospital stay'::text) || '
    '::text
                                                                                                                     ) || ' '::text
                                                                                                               ) || _
                                                                                                               ('admitted'::text)
                                                                                                         ) || ': '::text
                                                                                                   ) || to_char
                                                                                                   (c_hs.clin_when
                                                                                                         ,'YYYY-MM-DD'::text
                                                                                                   )
                                                                                             ) || '
    '::text
                                                                                       ) || ' '::text
                                                                                 ) || _
                                                                                 ('discharged'::text)
                                                                           ) || ': '::text
                                                                     ) || to_char
                                                                     (c_hs.discharge
                                                                           ,'YYYY-MM-DD'::text
                                                                     )
                                                               ) || '
    '::text
                                                         ) || ' '::text
                                                   ) || _
                                                   ('hospital'::text)
                                             ) || ': "'::text
                                       ) || d_ou.description
                                 ) || ' @ '::text
                           ) || d_o.description
                     ) || '"'::text
               ) || '
    '::text
         ) || COALESCE
         (
               ('
     '::text || c_hs.narrative)
               ,''::text
         )
    ) AS narrative
    ,
        c_hs.fk_encounter AS pk_encounter
    ,
        c_hs.fk_episode AS pk_episode
    ,

    (
    SELECT episode.fk_health_issue

      FROM clin.episode

     WHERE (episode.pk = c_hs.fk_episode)
    ) AS pk_health_issue
    ,
        c_hs.pk AS src_pk
    ,
        'clin.hospital_stay'::text AS src_table
    ,
        c_hs.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (
                                 (clin.hospital_stay c_hs

                                    JOIN clin.encounter c_enc
                                      ON (
                                             (c_hs.fk_encounter = c_enc.pk)
                                       )
                                 )

                              JOIN clin.encounter_type c_ety
                                ON (
                                       (c_enc.fk_type = c_ety.pk)
                                 )
                           )

                        JOIN clin.episode c_epi
                          ON (
                                 (c_hs.fk_episode = c_epi.pk)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_epi.fk_health_issue = c_hi.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (d_ou.pk = c_hs.fk_org_unit)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_o.pk = d_ou.fk_org)
         )
    )

    WHERE (
         (c_hs.discharge IS NOT NULL)
       AND (to_char
               (c_hs.clin_when
                     ,'YYYYMMDD'::text
               ) <> to_char
               (c_hs.discharge
                     ,'YYYYMMDD'::text
               )
         )
    );

Index - Schema clin

## View: clin.v_hospital_stays_journal_multi_day_dis

clin.v_hospital_stays_journal_multi_day_dis Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_hs.modified_when
    ,
        c_hs.discharge AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_hs.modified_by)
         )
         , (
               ('<'::text ||
                     (c_hs.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_hs.soap_cat
    ,

    (
         (
               (
                     (
                           (_
                                 ('discharged from'::text) || ' "'::text
                           ) || d_ou.description
                     ) || ' @ '::text
               ) || d_o.description
         ) || '"'::text
    ) AS narrative
    ,
        c_hs.fk_encounter AS pk_encounter
    ,
        c_hs.fk_episode AS pk_episode
    ,

    (
    SELECT episode.fk_health_issue

      FROM clin.episode

     WHERE (episode.pk = c_hs.fk_episode)
    ) AS pk_health_issue
    ,
        c_hs.pk AS src_pk
    ,
        'clin.hospital_stay'::text AS src_table
    ,
        c_hs.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (
                                 (clin.hospital_stay c_hs

                                    JOIN clin.encounter c_enc
                                      ON (
                                             (c_hs.fk_encounter = c_enc.pk)
                                       )
                                 )

                              JOIN clin.encounter_type c_ety
                                ON (
                                       (c_enc.fk_type = c_ety.pk)
                                 )
                           )

                        JOIN clin.episode c_epi
                          ON (
                                 (c_hs.fk_episode = c_epi.pk)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_epi.fk_health_issue = c_hi.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (d_ou.pk = c_hs.fk_org_unit)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_o.pk = d_ou.fk_org)
         )
    )

    WHERE (
         (c_hs.discharge IS NOT NULL)
       AND (to_char
               (c_hs.clin_when
                     ,'YYYYMMDD'::text
               ) <> to_char
               (c_hs.discharge
                     ,'YYYYMMDD'::text
               )
         )
    );

Index - Schema clin

## View: clin.v_hospital_stays_journal_no_discharge

clin.v_hospital_stays_journal_no_discharge Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_hs.modified_when
    ,
        c_hs.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_hs.modified_by)
         )
         , (
               ('<'::text ||
                     (c_hs.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_hs.soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (_
                                                                                       ('hospital stay'::text) || '
    '::text
                                                                                 ) || ' '::text
                                                                           ) || _
                                                                           ('admitted'::text)
                                                                     ) || ': '::text
                                                               ) || to_char
                                                               (c_hs.clin_when
                                                                     ,'YYYY-MM-DD'::text
                                                               )
                                                         ) || '
    '::text
                                                   ) || ' '::text
                                             ) || _
                                             ('hospital'::text)
                                       ) || ': "'::text
                                 ) || d_ou.description
                           ) || ' @ '::text
                     ) || d_o.description
               ) || '"'::text
         ) || COALESCE
         (
               ('
     '::text || c_hs.narrative)
               ,''::text
         )
    ) AS narrative
    ,
        c_hs.fk_encounter AS pk_encounter
    ,
        c_hs.fk_episode AS pk_episode
    ,

    (
    SELECT episode.fk_health_issue

      FROM clin.episode

     WHERE (episode.pk = c_hs.fk_episode)
    ) AS pk_health_issue
    ,
        c_hs.pk AS src_pk
    ,
        'clin.hospital_stay'::text AS src_table
    ,
        c_hs.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (
                                 (clin.hospital_stay c_hs

                                    JOIN clin.encounter c_enc
                                      ON (
                                             (c_hs.fk_encounter = c_enc.pk)
                                       )
                                 )

                              JOIN clin.encounter_type c_ety
                                ON (
                                       (c_enc.fk_type = c_ety.pk)
                                 )
                           )

                        JOIN clin.episode c_epi
                          ON (
                                 (c_hs.fk_episode = c_epi.pk)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_epi.fk_health_issue = c_hi.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (d_ou.pk = c_hs.fk_org_unit)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_o.pk = d_ou.fk_org)
         )
    )

    WHERE (c_hs.discharge IS NULL);

Index - Schema clin

## View: clin.v_hospital_stays_journal_one_day

clin.v_hospital_stays_journal_one_day Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_hs.modified_when
    ,
        c_hs.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_hs.modified_by)
         )
         , (
               ('<'::text ||
                     (c_hs.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_hs.soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (_
                                                                                             ('hospital stay'::text) || '
    '::text
                                                                                       ) || ' '::text
                                                                                 ) || _
                                                                                 ('admitted/discharged'::text)
                                                                           ) || ': '::text
                                                                     ) || to_char
                                                                     (c_hs.clin_when
                                                                           ,'YYYY-MM-DD'::text
                                                                     )
                                                               ) || '
    '::text
                                                         ) || ' '::text
                                                   ) || _
                                                   ('hospital'::text)
                                             ) || ': "'::text
                                       ) || d_ou.description
                                 ) || ' @ '::text
                           ) || d_o.description
                     ) || '"'::text
               ) || '
    '::text
         ) || COALESCE
         (
               ('
     '::text || c_hs.narrative)
               ,''::text
         )
    ) AS narrative
    ,
        c_hs.fk_encounter AS pk_encounter
    ,
        c_hs.fk_episode AS pk_episode
    ,

    (
    SELECT episode.fk_health_issue

      FROM clin.episode

     WHERE (episode.pk = c_hs.fk_episode)
    ) AS pk_health_issue
    ,
        c_hs.pk AS src_pk
    ,
        'clin.hospital_stay'::text AS src_table
    ,
        c_hs.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (
                                 (clin.hospital_stay c_hs

                                    JOIN clin.encounter c_enc
                                      ON (
                                             (c_hs.fk_encounter = c_enc.pk)
                                       )
                                 )

                              JOIN clin.encounter_type c_ety
                                ON (
                                       (c_enc.fk_type = c_ety.pk)
                                 )
                           )

                        JOIN clin.episode c_epi
                          ON (
                                 (c_hs.fk_episode = c_epi.pk)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_epi.fk_health_issue = c_hi.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (d_ou.pk = c_hs.fk_org_unit)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_o.pk = d_ou.fk_org)
         )
    )

    WHERE (
         (c_hs.discharge IS NOT NULL)
       AND (to_char
               (c_hs.clin_when
                     ,'YYYYMMDD'::text
               ) = to_char
               (c_hs.discharge
                     ,'YYYYMMDD'::text
               )
         )
    );

Index - Schema clin

## View: clin.v_incoming_data_unmatched

Shows incoming data but w/o the data field.

clin.v_incoming_data_unmatched Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_idu.pk AS pk_incoming_data_unmatched
    ,
        c_idu.fk_patient_candidates AS pk_patient_candidates
    ,
        c_idu.firstnames
    ,
        c_idu.lastnames
    ,
        c_idu.dob
    ,
        c_idu.gender
    ,
        c_idu.postcode
    ,
        c_idu.other_info
    ,
        c_idu.request_id
    ,
        c_idu.requestor
    ,
        c_idu.external_data_id
    ,
        c_idu.comment
    ,
        c_idu.fk_identity_disambiguated AS pk_identity_disambiguated
    ,
        c_idu.fk_provider_disambiguated AS pk_provider_disambiguated
    ,
        c_idu.type AS data_type
    ,
        md5
    (c_idu.data) AS md5_sum
    ,
        octet_length
    (c_idu.data) AS data_size
    ,
        c_idu.xmin AS xmin_incoming_data_unmatched

    FROM clin.incoming_data_unmatched c_idu;

Index - Schema clin

## View: clin.v_linked_codes

Denormalized codes linked to EMR structures.

clin.v_linked_codes Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_lc2ir.fk_item AS pk_item
    ,

    (c_lc2ir.tableoid)::regclass AS item_table
    ,

    (r_csr.code || COALESCE
         (c_lc2ir.code_modifier
               ,''::text
         )
    ) AS code
    ,
        r_csr.code AS base_code
    ,
        c_lc2ir.code_modifier
    ,
        r_csr.term
    ,
        r_ds.name_long
    ,
        r_ds.name_short
    ,
        r_ds.version
    ,
        r_ds.lang
    ,

    (r_csr.tableoid)::regclass AS code_table
    ,
        r_csr.pk_coding_system AS pk_generic_code
    ,
        r_csr.fk_data_source AS pk_data_source
    ,
        c_lc2ir.pk_lnk_code2item

    FROM (
         (clin.lnk_code2item_root c_lc2ir

            JOIN ref.coding_system_root r_csr
              ON (
                     (r_csr.pk_coding_system = c_lc2ir.fk_generic_code)
               )
         )

      JOIN ref.data_source r_ds
        ON (
               (r_ds.pk = r_csr.fk_data_source)
         )
    );

Index - Schema clin

## View: clin.v_most_recent_encounters

Lists the most recent encounters per patient. Logic of "most recent" is: for a patient: 1) select encounters with latest "last_affirmed", 2) from those select encounters with latest "started" 3) limit those to 1 if there are duplicates (same start and end of encounter!)

clin.v_most_recent_encounters Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT ce1.pk AS pk_encounter
    ,
        ce1.fk_patient AS pk_patient
    ,
        ce1.reason_for_encounter
    ,
        ce1.assessment_of_encounter
    ,
        et.description AS type
    ,
        _
    (et.description) AS l10n_type
    ,
        ce1.started
    ,
        ce1.last_affirmed
    ,
        ce1.fk_type AS pk_type
    ,
        ce1.fk_location AS pk_location

    FROM clin.encounter ce1
    ,
        clin.encounter_type et

    WHERE (
         (ce1.fk_type = et.pk)
       AND (ce1.started =
               (
                SELECT max
                     (ce2.started) AS max

                  FROM clin.encounter ce2

                 WHERE (ce2.last_affirmed =
                           (
                            SELECT max
                                 (ce3.last_affirmed) AS max

                              FROM clin.encounter ce3

                             WHERE (ce3.fk_patient = ce1.fk_patient)
                           )
                     )
             LIMIT 1
               )
         )
    );

Index - Schema clin

## View: clin.v_narrative

patient narrative with denormalized context added

clin.v_narrative Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_n.clin_when AS date
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_n.modified_by)
         )
         , (
               ('<'::text ||
                     (c_n.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_n.soap_cat
    ,
        c_n.narrative
    ,
        c_epi.description AS episode
    ,
        c_hi.description AS health_issue
    ,
        c_n.pk_item
    ,
        c_n.pk AS pk_narrative
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        c_n.fk_episode AS pk_episode
    ,
        c_n.fk_encounter AS pk_encounter
    ,
        c_n.xmin AS xmin_clin_narrative
    ,
        c_n.modified_when
    ,
        c_n.row_version
    ,
        c_n.pk_audit
    ,
        c_n.modified_by AS modified_by_raw
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2n.fk_generic_code) AS array_agg

            FROM clin.lnk_code2narrative c_lc2n

           WHERE (c_lc2n.fk_item = c_n.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes

    FROM (
         (
               (clin.clin_narrative c_n

             LEFT JOIN clin.encounter c_enc
                    ON (
                           (c_n.fk_encounter = c_enc.pk)
                     )
               )

       LEFT JOIN clin.episode c_epi
              ON (
                     (c_n.fk_episode = c_epi.pk)
               )
         )

    LEFT JOIN clin.health_issue c_hi
        ON (
               (c_epi.fk_health_issue = c_hi.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_allergies

denormalizes clin.allergy

clin.v_pat_allergies Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT a.pk AS pk_allergy
    ,

    (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = a.fk_encounter)
    ) AS pk_patient
    ,
        a.soap_cat
    ,
            CASE
                WHEN
    (COALESCE
         (btrim
               (a.allergene)
               ,''::text
         ) = ''::text
    ) THEN a.substance
                ELSE a.allergene
            END AS descriptor
    ,
        a.allergene
    ,
        a.substance
    ,
        a.substance_code
    ,
        a.generics
    ,
        a.generic_specific
    ,
        a.atc_code
    ,
        at.value AS type
    ,
        _
    (at.value) AS l10n_type
    ,
        a.definite
    ,
        a.narrative AS reaction
    ,
        a.fk_type AS pk_type
    ,
        a.pk_item
    ,
        a.clin_when AS date
    ,

    (
    SELECT episode.fk_health_issue

      FROM clin.episode

     WHERE (episode.pk = a.fk_episode)
    ) AS pk_health_issue
    ,
        a.fk_episode AS pk_episode
    ,
        a.fk_encounter AS pk_encounter
    ,
        a.modified_when
    ,
        a.modified_by
    ,
        a.xmin AS xmin_allergy

    FROM clin.allergy a
    ,
        clin._enum_allergy_type at

    WHERE (at.pk = a.fk_type);

Index - Schema clin

## View: clin.v_pat_allergies_journal

clin.v_pat_allergies_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_all.modified_when
    ,
        c_all.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_all.modified_by)
         )
         , (
               ('<'::text ||
                     (c_all.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_all.soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (_
                                                                           ('Allergy'::text) ||
                                                                        ' ('::text) || _
                                                                           (c_at.value)
                                                                     ) ||
                                                           '): '::text
                                                         ) || COALESCE
                                                         (c_all.narrative
                                                               ,''::text
                                                         )
                                                   ) || '
    '::text
                                             ) || _
                                             ('substance'::text)
                                       ) || ': '::text
                                 ) || c_all.substance
                           ) || '; '::text
                     ) || COALESCE
                     (
                           (
                                 (
                                       (_
                                             ('allergene'::text) || ': '::text
                                       ) || c_all.allergene
                                 ) || '; '::text
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           (
                                 (_
                                       ('generic'::text) || ': '::text
                                 ) || c_all.generics
                           ) || '; '::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (
                           (_
                                 ('ATC code'::text) || ': '::text
                           ) || c_all.atc_code
                     ) || '; '::text
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_all.fk_encounter AS pk_encounter
    ,
        c_all.fk_episode AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        c_all.pk AS src_pk
    ,
        'clin.allergy'::text AS src_table
    ,
        c_all.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (clin.allergy c_all

                              JOIN clin._enum_allergy_type c_at
                                ON (
                                       (c_all.fk_type = c_at.pk)
                                 )
                           )

                        JOIN clin.encounter c_enc
                          ON (
                                 (c_all.fk_encounter = c_enc.pk)
                           )
                     )

                  JOIN clin.encounter_type c_ety
                    ON (
                           (c_enc.fk_type = c_ety.pk)
                     )
               )

            JOIN clin.episode c_epi
              ON (
                     (c_all.fk_episode = c_epi.pk)
               )
         )

    LEFT JOIN clin.health_issue c_hi
        ON (
               (c_epi.fk_health_issue = c_hi.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_allergy_state

clin.v_pat_allergy_state Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = a.fk_encounter)
    ) AS pk_patient
    ,
        a.modified_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = a.modified_by)
         )
         , (
               ('<'::text ||
                     (a.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        a.last_confirmed
    ,
        a.has_allergy
    ,
        a.comment
    ,
        a.fk_encounter AS pk_encounter
    ,
        a.pk AS pk_allergy_state
    ,
        a.xmin AS xmin_allergy_state

    FROM clin.allergy_state a;

Index - Schema clin

## View: clin.v_pat_allergy_state_journal

clin.v_pat_allergy_state_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_ast.modified_when
    ,
        COALESCE
    (c_ast.last_confirmed
         , c_ast.modified_when
    ) AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_ast.modified_by)
         )
         , (
               ('<'::text ||
                     (c_ast.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        'o'::text AS soap_cat
    ,

    (
         (
               (
                     (_
                           ('Allergy state'::text) || ': '::text
                     ) ||
            CASE
                WHEN
                     (c_ast.has_allergy IS NULL) THEN _
                     (
          'unknown, unasked'::text
                     )
                WHEN
                     (c_ast.has_allergy = 0) THEN _
                     ('no known allergies'::text)
                WHEN
                     (c_ast.has_allergy = 1) THEN _
                     ('does have allergies'::text)
                ELSE NULL::text
            END
               ) || COALESCE
               (
                     (
                           (
                                 (
                                    ' ('::text || _
                                             ('last confirmed'::text)
                                       ) || to_char
                                       (c_ast.last_confirmed
                                             ,' YYYY-MM-DD HH24:MI'::text
                                       )
                                 ) ||
                         ')'::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               ('
     '::text || c_ast.comment)
               ,''::text
         )
    ) AS narrative
    ,
        c_ast.fk_encounter AS pk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        NULL::integer AS pk_health_issue
    ,
        c_ast.pk AS src_pk
    ,
        'clin.allergy_state'::text AS src_table
    ,
        c_ast.row_version
    ,
        NULL::text AS health_issue
    ,
        NULL::text AS issue_laterality
    ,
        NULL::boolean AS issue_active
    ,
        NULL::boolean AS issue_clinically_relevant
    ,
        NULL::boolean AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (clin.allergy_state c_ast

            JOIN clin.encounter c_enc
              ON (
                     (c_ast.fk_encounter = c_enc.pk)
               )
         )

      JOIN clin.encounter_type c_ety
        ON (
               (c_enc.fk_type = c_ety.pk)
         )
    )
    UNION ALL

    SELECT c_enc.fk_patient AS pk_patient
    ,
        now
    () AS modified_when
    ,
        now
    () AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_ast.modified_by)
         )
         , (
               ('<'::text ||
                     (c_ast.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        'o'::text AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (_
                                                         ('Allergy state'::text) ||
                                                      ' ('::text) || _
                                                         ('copy'::text)
                                                   ) ||
                                         '): '::text
                                       ) ||
            CASE
                WHEN
                                       (c_ast.has_allergy IS NULL) THEN _
                                       (
                            'unknown, unasked'::text
                                       )
                WHEN
                                       (c_ast.has_allergy = 0) THEN _
                                       ('no known allergies'::text)
                WHEN
                                       (c_ast.has_allergy = 1) THEN _
                                       ('does have allergies'::text)
                ELSE NULL::text
            END
                                 ) || COALESCE
                                 (
                                       ('
     '::text || c_ast.comment)
                                       ,''::text
                                 )
                           ) || COALESCE
                           (
                                 (
                                       ('
     '::text || _
                                             ('last confirmed'::text)
                                       ) || to_char
                                       (c_ast.last_confirmed
                                             ,' YYYY-MM-DD HH24:MI'::text
                                       )
                                 )
                                 ,''::text
                           )
                     ) || COALESCE
                     (
                           (
                                 ('
     '::text || _
                                       ('entry last modified'::text)
                                 ) || to_char
                                 (c_ast.modified_when
                                       ,' YYYY-MM-DD HH24:MI'::text
                                 )
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           ('
     '::text || _
                                 ('encounter started'::text)
                           ) || to_char
                           (c_enc.started
                                 ,' YYYY-MM-DD HH24:MI'::text
                           )
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     ('
     '::text || _
                           ('encounter last affirmed'::text)
                     ) || to_char
                     (c_enc.last_affirmed
                           ,' YYYY-MM-DD HH24:MI'::text
                     )
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_ast.fk_encounter AS pk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        NULL::integer AS pk_health_issue
    ,
        c_ast.pk AS src_pk
    ,
        'clin.allergy_state'::text AS src_table
    ,
        c_ast.row_version
    ,
        NULL::text AS health_issue
    ,
        NULL::text AS issue_laterality
    ,
        NULL::boolean AS issue_active
    ,
        NULL::boolean AS issue_clinically_relevant
    ,
        NULL::boolean AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,
        now
    () AS encounter_started
    ,
        now
    () AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (clin.allergy_state c_ast

            JOIN clin.encounter c_enc
              ON (
                     (c_ast.fk_encounter = c_enc.pk)
               )
         )

      JOIN clin.encounter_type c_ety
        ON (
               (c_enc.fk_type = c_ety.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_encounters

Details on encounters.

clin.v_pat_encounters Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.pk AS pk_encounter
    ,
        c_enc.fk_patient AS pk_patient
    ,
        c_enc.started
    ,
        c_et.description AS type
    ,
        _
    (c_et.description) AS l10n_type
    ,
        c_enc.reason_for_encounter
    ,
        c_enc.assessment_of_encounter
    ,
        c_enc.last_affirmed
    ,
        c_enc.source_time_zone
    ,

    (
    SELECT timezone
         (
               (
                SELECT c_enc1.source_time_zone

                  FROM clin.encounter c_enc1

                 WHERE (c_enc1.pk = c_enc.pk)
               )
               , c_enc.started
         ) AS timezone
    ) AS started_original_tz
    ,

    (
    SELECT timezone
         (
               (
                SELECT c_enc1.source_time_zone

                  FROM clin.encounter c_enc1

                 WHERE (c_enc1.pk = c_enc.pk)
               )
               , c_enc.last_affirmed
         ) AS timezone
    ) AS last_affirmed_original_tz
    ,
        COALESCE
    (d_ou.description
         ,'?'::text
    ) AS praxis_branch
    ,
        COALESCE
    (d_o.description
         ,'?'::text
    ) AS praxis
    ,
        c_enc.fk_location AS pk_org_unit
    ,
        d_ou.fk_org AS pk_org
    ,
        d_ou.fk_category AS pk_unit_type
    ,
        d_o.fk_category AS pk_org_type
    ,
        c_enc.fk_type AS pk_type
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2r.fk_generic_code) AS array_agg

            FROM clin.lnk_code2rfe c_lc2r

           WHERE (c_lc2r.fk_item = c_enc.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes_rfe
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2a.fk_generic_code) AS array_agg

            FROM clin.lnk_code2aoe c_lc2a

           WHERE (c_lc2a.fk_item = c_enc.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes_aoe
    ,
        c_enc.xmin AS xmin_encounter
    ,
        c_enc.row_version
    ,
        c_enc.pk_audit
    ,
        c_enc.modified_when
    ,
        c_enc.modified_by AS modified_by_raw
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_enc.modified_by)
         )
         , (
               ('<'::text ||
                     (c_enc.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by

    FROM (
         (
               (clin.encounter c_enc

             LEFT JOIN clin.encounter_type c_et
                    ON (
                           (c_enc.fk_type = c_et.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (c_enc.fk_location = d_ou.pk)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_ou.fk_org = d_o.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_encounters_journal

clin.v_pat_encounters_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_enc.modified_when
    ,
        c_enc.started AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_enc.modified_by)
         )
         , (
               ('<'::text ||
                     (c_enc.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        NULL::text AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (_
                                                         ('Encounter'::text) || ': '::text
                                                   ) ||
                                                   (
                                                    SELECT _
                                                         (encounter_type.description) AS _

                                                      FROM clin.encounter_type

                                                     WHERE (encounter_type.pk = c_enc.fk_type)
                                                   )
                                             ) || to_char
                                             (c_enc.started
                                                   ,' YYYY-MM-DD HH24:MI'::text
                                             )
                                       ) || to_char
                                       (c_enc.last_affirmed
                                             ,' - HH24:MI'::text
                                       )
                                 ) || COALESCE
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 ('
     @ '::text || _
                                                                                       ('branch'::text)
                                                                                 ) || ' "'::text
                                                                           ) || d_ou.description
                                                                     ) || '" '::text
                                                               ) || _
                                                               ('of'::text)
                                                         ) || ' "'::text
                                                   ) || d_o.description
                                             ) || '"'::text
                                       )
                                       ,''::text
                                 )
                           ) || COALESCE
                           (
                                 (
                                       (
                                             ('
     '::text || _
                                                   ('RFE'::text)
                                             ) || ': '::text
                                       ) || c_enc.reason_for_encounter
                                 )
                                 ,''::text
                           )
                     ) || COALESCE
                     (
                           (
                                 ('
    '::text || array_to_string
                                       (
                                             (
                                              SELECT array_agg
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (
                                                                                             (
                                                                                                   (r_csr.code ||
                                                                                                      ' ('::text) || r_ds.name_short
                                                                                                   ) || ' - '::text
                                                                                             ) || r_ds.version
                                                                                       ) || ' - '::text
                                                                                 ) || r_ds.lang
                                                                           ) ||
                                                                 '): '::text
                                                               ) || r_csr.term
                                                         )
                                                   ) AS array_agg

                                                FROM (
                                                         (clin.lnk_code2rfe c_lc2r

                                                            JOIN ref.coding_system_root r_csr
                                                              ON (
                                                                     (c_lc2r.fk_generic_code = r_csr.pk_coding_system)
                                                               )
                                                         )

                                                      JOIN ref.data_source r_ds
                                                        ON (
                                                               (r_ds.pk = r_csr.fk_data_source)
                                                         )
                                                   )

                                               WHERE (c_lc2r.fk_item = c_enc.pk)
                                             )
                                             ,'; '::text
                                       )
                                 ) || ';'::text
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           (
                                 ('
     '::text || _
                                       ('AOE'::text)
                                 ) || ': '::text
                           ) || c_enc.assessment_of_encounter
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     ('
    '::text || array_to_string
                           (
                                 (
                                  SELECT array_agg
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (r_csr.code ||
                                                                                          ' ('::text) || r_ds.name_short
                                                                                       ) || ' - '::text
                                                                                 ) || r_ds.version
                                                                           ) || ' - '::text
                                                                     ) || r_ds.lang
                                                               ) ||
                                                     '): '::text
                                                   ) || r_csr.term
                                             )
                                       ) AS array_agg

                                    FROM (
                                             (clin.lnk_code2aoe c_lc2a

                                                JOIN ref.coding_system_root r_csr
                                                  ON (
                                                         (c_lc2a.fk_generic_code = r_csr.pk_coding_system)
                                                   )
                                             )

                                          JOIN ref.data_source r_ds
                                            ON (
                                                   (r_ds.pk = r_csr.fk_data_source)
                                             )
                                       )

                                   WHERE (c_lc2a.fk_item = c_enc.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_enc.pk AS pk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        NULL::integer AS pk_health_issue
    ,
        c_enc.pk AS src_pk
    ,
        'clin.encounter'::text AS src_table
    ,
        c_enc.row_version
    ,
        NULL::text AS health_issue
    ,
        NULL::text AS issue_laterality
    ,
        NULL::boolean AS issue_active
    ,
        NULL::boolean AS issue_clinically_relevant
    ,
        NULL::boolean AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (clin.encounter c_enc

                  JOIN clin.encounter_type c_ety
                    ON (
                           (c_enc.fk_type = c_ety.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (c_enc.fk_location = d_ou.pk)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_ou.fk_org = d_o.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_episodes

clin.v_pat_episodes Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT cenc.fk_patient AS pk_patient
    ,
        cep.description
    ,
        cep.summary
    ,
        cep.is_open AS episode_open
    ,
        NULL::text AS health_issue
    ,
        NULL::boolean AS issue_active
    ,
        NULL::boolean AS issue_clinically_relevant
    ,

    (
    SELECT min
         (cle.started) AS min

      FROM clin.encounter cle

     WHERE (cle.pk = cep.fk_encounter)
             LIMIT 1
    ) AS started_first
    ,

    (
    SELECT max
         (cle.started) AS max

      FROM clin.encounter cle

     WHERE (cle.pk = cep.fk_encounter)
             LIMIT 1
    ) AS started_last
    ,

    (
    SELECT max
         (cle.last_affirmed) AS max

      FROM clin.encounter cle

     WHERE (cle.pk = cep.fk_encounter)
             LIMIT 1
    ) AS last_affirmed
    ,
        cep.pk AS pk_episode
    ,
        cep.fk_encounter AS pk_encounter
    ,
        NULL::integer AS pk_health_issue
    ,
        cep.modified_when AS episode_modified_when
    ,
        cep.modified_by AS episode_modified_by
    ,
        cep.diagnostic_certainty_classification
    ,
        NULL::text AS diagnostic_certainty_classification_issue
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2e.fk_generic_code) AS array_agg

            FROM clin.lnk_code2episode c_lc2e

           WHERE (c_lc2e.fk_item = cep.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    ,
        cep.xmin AS xmin_episode

    FROM (clin.episode cep

      JOIN clin.encounter cenc
        ON (
               (cep.fk_encounter = cenc.pk)
         )
    )

    WHERE (cep.fk_health_issue IS NULL)
    UNION ALL

    SELECT cenc.fk_patient AS pk_patient
    ,
        cep.description
    ,
        cep.summary
    ,
        cep.is_open AS episode_open
    ,
        chi.description AS health_issue
    ,
        chi.is_active AS issue_active
    ,
        chi.clinically_relevant AS issue_clinically_relevant
    ,

    (
    SELECT min
         (cle.started) AS min

      FROM clin.encounter cle

     WHERE (cle.pk = cep.fk_encounter)
             LIMIT 1
    ) AS started_first
    ,

    (
    SELECT max
         (cle.started) AS max

      FROM clin.encounter cle

     WHERE (cle.pk = cep.fk_encounter)
             LIMIT 1
    ) AS started_last
    ,

    (
    SELECT max
         (cle.last_affirmed) AS max

      FROM clin.encounter cle

     WHERE (cle.pk = cep.fk_encounter)
             LIMIT 1
    ) AS last_affirmed
    ,
        cep.pk AS pk_episode
    ,
        cep.fk_encounter AS pk_encounter
    ,
        cep.fk_health_issue AS pk_health_issue
    ,
        cep.modified_when AS episode_modified_when
    ,
        cep.modified_by AS episode_modified_by
    ,
        cep.diagnostic_certainty_classification
    ,
        chi.diagnostic_certainty_classification AS diagnostic_certainty_classification_issue
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2e.fk_generic_code) AS array_agg

            FROM clin.lnk_code2episode c_lc2e

           WHERE (c_lc2e.fk_item = cep.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    ,
        cep.xmin AS xmin_episode

    FROM (
         (clin.episode cep

            JOIN clin.encounter cenc
              ON (
                     (cep.fk_encounter = cenc.pk)
               )
         )

      JOIN clin.health_issue chi
        ON (
               (cep.fk_health_issue = chi.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_episodes_journal

clin.v_pat_episodes_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_epi.modified_when
    ,
        c_enc.started AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_epi.modified_by)
         )
         , (
               ('<'::text ||
                     (c_epi.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        'a'::text AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (_
                                                   ('Episode'::text) ||
                                                ' ('::text) ||
            CASE
                WHEN c_epi.is_open THEN _
                                                   ('open'::text)
                ELSE _
                                                   ('closed'::text)
            END
                                             ) || COALESCE
                                             (
                                                   (
                                                      ', '::text || c_epi.diagnostic_certainty_classification
                                                   )
                                                   ,''::text
                                             )
                                       ) ||
                             '): '::text
                           ) || c_epi.description
                     ) || ';'::text
               ) || COALESCE
               (
                     (
                           (
                                 (
                                       ('
     '::text || _
                                             ('Synopsis'::text)
                                       ) || ': '::text
                                 ) || c_epi.summary
                           ) || ';'::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     ('
    '::text || array_to_string
                           (
                                 (
                                  SELECT array_agg
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (r_csr.code ||
                                                                                          ' ('::text) || r_ds.name_short
                                                                                       ) || ' - '::text
                                                                                 ) || r_ds.version
                                                                           ) || ' - '::text
                                                                     ) || r_ds.lang
                                                               ) ||
                                                     '): '::text
                                                   ) || r_csr.term
                                             )
                                       ) AS array_agg

                                    FROM (
                                             (clin.lnk_code2episode c_lc2e

                                                JOIN ref.coding_system_root r_csr
                                                  ON (
                                                         (c_lc2e.fk_generic_code = r_csr.pk_coding_system)
                                                   )
                                             )

                                          JOIN ref.data_source r_ds
                                            ON (
                                                   (r_ds.pk = r_csr.fk_data_source)
                                             )
                                       )

                                   WHERE (c_lc2e.fk_item = c_epi.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_epi.fk_encounter AS pk_encounter
    ,
        c_epi.pk AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        c_epi.pk AS src_pk
    ,
        'clin.episode'::text AS src_table
    ,
        c_epi.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (clin.episode c_epi

                  JOIN clin.encounter c_enc
                    ON (
                           (c_epi.fk_encounter = c_enc.pk)
                     )
               )

            JOIN clin.encounter_type c_ety
              ON (
                     (c_enc.fk_type = c_ety.pk)
               )
         )

    LEFT JOIN clin.health_issue c_hi
        ON (
               (c_epi.fk_health_issue = c_hi.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_items

clin.v_pat_items Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT cri.modified_when
    ,
        cri.modified_by
    ,
        cri.clin_when
    ,
            CASE cri.row_version
                WHEN 0 THEN false
                ELSE true
            END AS is_modified
    ,
        cenc.fk_patient AS pk_patient
    ,
        cri.pk_item
    ,
        cri.fk_encounter AS pk_encounter
    ,
        cri.fk_episode AS pk_episode
    ,
        cepi.fk_health_issue AS pk_health_issue
    ,
        cri.soap_cat
    ,
        cri.narrative
    ,

    (
         (
               (pgn.nspname)::text || '.'::text
         ) ||
         (pgc.relname)::text
    ) AS src_table

    FROM clin.clin_root_item cri
    ,
        clin.encounter cenc
    ,
        clin.episode cepi
    ,

    (pg_class pgc

    LEFT JOIN pg_namespace pgn
        ON (
               (pgc.relnamespace = pgn.oid)
         )
    )

    WHERE (
         (cri.fk_encounter = cenc.pk)
       AND (cri.fk_episode = cepi.pk)
       AND (cri.tableoid = pgc.oid)
    );

Index - Schema clin

## View: clin.v_pat_last_vacc4indication

Lists *latest* vaccinations with total count per indication.

clin.v_pat_last_vacc4indication Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_vpv4i.pk_patient
    ,
        c_vpv4i.pk_vaccination
    ,
        c_vpv4i.date_given
    ,
        c_vpv4i.vaccine
    ,
        c_vpv4i.indication
    ,
        c_vpv4i.l10n_indication
    ,
        c_vpv4i.site
    ,
        c_vpv4i.batch_no
    ,
        c_vpv4i.reaction
    ,
        c_vpv4i.comment
    ,
        c_vpv4i.soap_cat
    ,
        c_vpv4i.modified_when
    ,
        c_vpv4i.modified_by
    ,
        c_vpv4i.row_version
    ,
        c_vpv4i.pk_vaccine
    ,
        c_vpv4i.atc_indication
    ,
        c_vpv4i.pk_provider
    ,
        c_vpv4i.pk_encounter
    ,
        c_vpv4i.pk_episode
    ,
        c_vpv4i.xmin_vaccination
    ,
        shots_per_ind.no_of_shots

    FROM (clin.v_pat_vaccs4indication c_vpv4i

      JOIN (
          SELECT count
               (1) AS no_of_shots
               ,
                v_pat_vaccs4indication.pk_patient
               ,
                v_pat_vaccs4indication.atc_indication

            FROM clin.v_pat_vaccs4indication

        GROUP BY v_pat_vaccs4indication.pk_patient
               , v_pat_vaccs4indication.atc_indication
         ) shots_per_ind
        ON (
               (
                     (c_vpv4i.pk_patient = shots_per_ind.pk_patient)
                   AND (c_vpv4i.atc_indication = shots_per_ind.atc_indication)
               )
         )
    )

    WHERE (c_vpv4i.date_given =
         (
          SELECT max
               (c_vpv4i_2.date_given) AS max

            FROM clin.v_pat_vaccs4indication c_vpv4i_2

           WHERE (
                     (c_vpv4i.pk_patient = c_vpv4i_2.pk_patient)
                   AND (c_vpv4i.atc_indication = c_vpv4i_2.atc_indication)
               )
         )
    );

Index - Schema clin

## View: clin.v_pat_narrative_journal

clin.v_pat_narrative_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_n.modified_when
    ,
            CASE
                WHEN
    (c_n.soap_cat = ANY
         (ARRAY['s'::text
               ,'o'::text
               ,'u'::text]
         )
    ) THEN c_enc.started
                WHEN
    (c_n.soap_cat IS NULL) THEN c_enc.last_affirmed
                WHEN
    (c_n.soap_cat = ANY
         (ARRAY['a'::text
               ,'p'::text]
         )
    ) THEN c_enc.last_affirmed
                ELSE NULL::timestamp with time zone
            END AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_n.modified_by)
         )
         , (
               ('<'::text ||
                     (c_n.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_n.soap_cat
    ,
        c_n.narrative
    ,
        c_n.fk_encounter AS pk_encounter
    ,
        c_n.fk_episode AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        c_n.pk AS src_pk
    ,
        'clin.clin_narrative'::text AS src_table
    ,
        c_n.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (clin.clin_narrative c_n

                        JOIN clin.encounter c_enc
                          ON (
                                 (c_n.fk_encounter = c_enc.pk)
                           )
                     )

                  JOIN clin.encounter_type c_ety
                    ON (
                           (c_enc.fk_type = c_ety.pk)
                     )
               )

            JOIN clin.episode c_epi
              ON (
                     (c_n.fk_episode = c_epi.pk)
               )
         )

    LEFT JOIN clin.health_issue c_hi
        ON (
               (c_epi.fk_health_issue = c_hi.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_vaccs4indication

Lists all vaccinations for each indication for patients

clin.v_pat_vaccs4indication Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_shot.pk AS pk_vaccination
    ,
        c_shot.clin_when AS date_given
    ,
        r_dp.description AS vaccine
    ,
        _
    (
         (r_s.atc || '-target'::text)
         ,'en'::text
    ) AS indication
    ,
            CASE
                WHEN
    (_
         (
               (r_s.atc || '-target'::text)
         ) =
         (r_s.atc || '-target'::text)
    ) THEN _
    (
         (r_s.atc || '-target'::text)
         ,'en'::text
    )
                ELSE _
    (
         (r_s.atc || '-target'::text)
    )
            END AS l10n_indication
    ,
        c_shot.site
    ,
        c_shot.batch_no
    ,
        c_shot.reaction
    ,
        c_shot.narrative AS comment
    ,
        c_shot.soap_cat
    ,
        c_shot.modified_when
    ,
        c_shot.modified_by
    ,
        c_shot.row_version
    ,
        c_shot.fk_vaccine AS pk_vaccine
    ,
        r_s.atc AS atc_indication
    ,
        c_shot.fk_provider AS pk_provider
    ,
        c_shot.fk_encounter AS pk_encounter
    ,
        c_shot.fk_episode AS pk_episode
    ,
        c_shot.xmin AS xmin_vaccination

    FROM (
         (
               (
                     (
                           (
                                 (clin.vaccination c_shot

                                    JOIN clin.encounter c_enc
                                      ON (
                                             (c_enc.pk = c_shot.fk_encounter)
                                       )
                                 )

                              JOIN ref.vaccine r_v
                                ON (
                                       (r_v.pk = c_shot.fk_vaccine)
                                 )
                           )

                        JOIN ref.drug_product r_dp
                          ON (
                                 (r_dp.pk = r_v.fk_drug_product)
                           )
                     )

                  JOIN ref.lnk_dose2drug r_ld2d
                    ON (
                           (r_ld2d.fk_drug_product = r_dp.pk)
                     )
               )

            JOIN ref.dose r_d
              ON (
                     (r_d.pk = r_ld2d.fk_dose)
               )
         )

      JOIN ref.substance r_s
        ON (
               (r_s.pk = r_d.fk_substance)
         )
    );

Index - Schema clin

## View: clin.v_potential_problem_list

clin.v_potential_problem_list Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = cep.fk_encounter)
    ) AS pk_patient
    ,
        cep.description AS problem
    ,
        cep.summary
    ,
        'episode'::text AS type
    ,
        _
    ('episode'::text) AS l10n_type
    ,
        false AS problem_active
    ,
        false AS clinically_relevant
    ,
        cep.pk AS pk_episode
    ,
        cep.fk_health_issue AS pk_health_issue
    ,
        cep.diagnostic_certainty_classification
    ,
        cep.fk_encounter AS pk_encounter
    ,
        cep.modified_when

    FROM clin.episode cep

    WHERE (cep.is_open IS FALSE)
    UNION

    SELECT (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = chi.fk_encounter)
    ) AS pk_patient
    ,
        chi.description AS problem
    ,
        chi.summary
    ,
        'issue'::text AS type
    ,
        _
    ('health issue'::text) AS l10n_type
    ,
        chi.is_active AS problem_active
    ,
        false AS clinically_relevant
    ,
        NULL::integer AS pk_episode
    ,
        chi.pk AS pk_health_issue
    ,
        chi.diagnostic_certainty_classification
    ,
        chi.fk_encounter AS pk_encounter
    ,
        chi.modified_when

    FROM clin.health_issue chi

    WHERE (chi.clinically_relevant IS FALSE);

Index - Schema clin

## View: clin.v_problem_list

clin.v_problem_list Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = cep.fk_encounter)
    ) AS pk_patient
    ,
        cep.description AS problem
    ,
        cep.summary
    ,
        'episode'::text AS type
    ,
        _
    ('episode'::text) AS l10n_type
    ,
        true AS problem_active
    ,
        true AS clinically_relevant
    ,
        cep.pk AS pk_episode
    ,
        cep.fk_health_issue AS pk_health_issue
    ,
        cep.diagnostic_certainty_classification
    ,
        cep.fk_encounter AS pk_encounter
    ,
        cep.modified_when

    FROM clin.episode cep

    WHERE (cep.is_open IS TRUE)
    UNION

    SELECT (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = chi.fk_encounter)
    ) AS pk_patient
    ,
        chi.description AS problem
    ,
        chi.summary
    ,
        'issue'::text AS type
    ,
        _
    ('health issue'::text) AS l10n_type
    ,
        chi.is_active AS problem_active
    ,
        true AS clinically_relevant
    ,
        NULL::integer AS pk_episode
    ,
        chi.pk AS pk_health_issue
    ,
        chi.diagnostic_certainty_classification
    ,
        chi.fk_encounter AS pk_encounter
    ,
        chi.modified_when

    FROM clin.health_issue chi

    WHERE (chi.clinically_relevant IS TRUE);

Index - Schema clin

## View: clin.v_procedures

clin.v_procedures Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT v_procedures_at_hospital.pk_procedure
    ,
        v_procedures_at_hospital.pk_patient
    ,
        v_procedures_at_hospital.soap_cat
    ,
        v_procedures_at_hospital.clin_when
    ,
        v_procedures_at_hospital.clin_end
    ,
        v_procedures_at_hospital.is_ongoing
    ,
        v_procedures_at_hospital.performed_procedure
    ,
        v_procedures_at_hospital.comment
    ,
        v_procedures_at_hospital.unit
    ,
        v_procedures_at_hospital.organization
    ,
        v_procedures_at_hospital.episode
    ,
        v_procedures_at_hospital.health_issue
    ,
        v_procedures_at_hospital.modified_when
    ,
        v_procedures_at_hospital.modified_by
    ,
        v_procedures_at_hospital.row_version
    ,
        v_procedures_at_hospital.pk_encounter
    ,
        v_procedures_at_hospital.pk_episode
    ,
        v_procedures_at_hospital.pk_hospital_stay
    ,
        v_procedures_at_hospital.pk_health_issue
    ,
        v_procedures_at_hospital.pk_doc
    ,
        v_procedures_at_hospital.pk_org
    ,
        v_procedures_at_hospital.pk_org_unit
    ,
        v_procedures_at_hospital.pk_generic_codes
    ,
        v_procedures_at_hospital.xmin_procedure

    FROM clin.v_procedures_at_hospital

    UNION ALL

    SELECT v_procedures_not_at_hospital.pk_procedure
    ,
        v_procedures_not_at_hospital.pk_patient
    ,
        v_procedures_not_at_hospital.soap_cat
    ,
        v_procedures_not_at_hospital.clin_when
    ,
        v_procedures_not_at_hospital.clin_end
    ,
        v_procedures_not_at_hospital.is_ongoing
    ,
        v_procedures_not_at_hospital.performed_procedure
    ,
        v_procedures_not_at_hospital.comment
    ,
        v_procedures_not_at_hospital.unit
    ,
        v_procedures_not_at_hospital.organization
    ,
        v_procedures_not_at_hospital.episode
    ,
        v_procedures_not_at_hospital.health_issue
    ,
        v_procedures_not_at_hospital.modified_when
    ,
        v_procedures_not_at_hospital.modified_by
    ,
        v_procedures_not_at_hospital.row_version
    ,
        v_procedures_not_at_hospital.pk_encounter
    ,
        v_procedures_not_at_hospital.pk_episode
    ,
        v_procedures_not_at_hospital.pk_hospital_stay
    ,
        v_procedures_not_at_hospital.pk_health_issue
    ,
        v_procedures_not_at_hospital.pk_doc
    ,
        v_procedures_not_at_hospital.pk_org
    ,
        v_procedures_not_at_hospital.pk_org_unit
    ,
        v_procedures_not_at_hospital.pk_generic_codes
    ,
        v_procedures_not_at_hospital.xmin_procedure

    FROM clin.v_procedures_not_at_hospital;

Index - Schema clin

## View: clin.v_procedures_at_hospital

clin.v_procedures_at_hospital Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_pr.pk AS pk_procedure
    ,
        c_enc.fk_patient AS pk_patient
    ,
        c_pr.soap_cat
    ,
        c_pr.clin_when
    ,
        c_pr.clin_end
    ,
        c_pr.is_ongoing
    ,
        c_pr.narrative AS performed_procedure
    ,
        c_pr.comment
    ,
        c_vhs.ward AS unit
    ,
        c_vhs.hospital AS organization
    ,
        c_ep.description AS episode
    ,
        c_hi.description AS health_issue
    ,
        c_pr.modified_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_pr.modified_by)
         )
         , (
               ('<'::text ||
                     (c_pr.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_pr.row_version
    ,
        c_pr.fk_encounter AS pk_encounter
    ,
        c_pr.fk_episode AS pk_episode
    ,
        c_pr.fk_hospital_stay AS pk_hospital_stay
    ,
        c_ep.fk_health_issue AS pk_health_issue
    ,
        c_pr.fk_doc AS pk_doc
    ,
        c_vhs.pk_org
    ,
        c_vhs.pk_org_unit
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2p.fk_generic_code) AS array_agg

            FROM clin.lnk_code2procedure c_lc2p

           WHERE (c_lc2p.fk_item = c_pr.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    ,
        c_pr.xmin AS xmin_procedure

    FROM (
         (
               (
                     (clin.procedure c_pr

                        JOIN clin.encounter c_enc
                          ON (
                                 (c_pr.fk_encounter = c_enc.pk)
                           )
                     )

                  JOIN clin.episode c_ep
                    ON (
                           (c_pr.fk_episode = c_ep.pk)
                     )
               )

       LEFT JOIN clin.health_issue c_hi
              ON (
                     (c_ep.fk_health_issue = c_hi.pk)
               )
         )

    LEFT JOIN clin.v_hospital_stays c_vhs
        ON (
               (c_pr.fk_hospital_stay = c_vhs.pk_hospital_stay)
         )
    )

    WHERE (c_pr.fk_hospital_stay IS NOT NULL);

Index - Schema clin

## View: clin.v_procedures_at_hospital_journal

clin.v_procedures_at_hospital_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_pr.modified_when
    ,
        c_pr.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_pr.modified_by)
         )
         , (
               ('<'::text ||
                     (c_pr.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
            CASE
                WHEN
    (c_pr.is_ongoing IS TRUE) THEN 'p'::text
                ELSE 'o'::text
            END AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (_
                                                                           ('Procedure'::text) || ' "'::text
                                                                     ) || c_pr.narrative
                                                               ) || '"'::text
                                                         ) ||
                                                      ' ('::text) || d_ou.description
                                                   ) || ' @ '::text
                                             ) || d_o.description
                                       ) || COALESCE
                                       (
                                             (
                                                   (
                                                         (
                                                            ', '::text || _
                                                               ('until'::text)
                                                         ) || ' '::text
                                                   ) || to_char
                                                   (c_pr.clin_end
                                                         ,'YYYY Mon DD'::text
                                                   )
                                             )
                                             ,
            CASE
                WHEN
                                             (c_pr.is_ongoing IS TRUE) THEN
                                             (
                                                ', '::text || _
                                                   ('ongoing'::text)
                                             )
                ELSE ''::text
            END
                                       )
                                 ) ||
                         ')'::text
                     ) || COALESCE
                     (
                           ('
     '::text || c_pr.comment)
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           ('
     '::text || _
                                 ('document #'::text)
                           ) || c_pr.fk_doc
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     ('
    '::text || array_to_string
                           (
                                 (
                                  SELECT array_agg
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (r_csr.code ||
                                                                                          ' ('::text) || r_ds.name_short
                                                                                       ) || ' - '::text
                                                                                 ) || r_ds.version
                                                                           ) || ' - '::text
                                                                     ) || r_ds.lang
                                                               ) ||
                                                     '): '::text
                                                   ) || r_csr.term
                                             )
                                       ) AS array_agg

                                    FROM (
                                             (clin.lnk_code2procedure c_lc2p

                                                JOIN ref.coding_system_root r_csr
                                                  ON (
                                                         (c_lc2p.fk_generic_code = r_csr.pk_coding_system)
                                                   )
                                             )

                                          JOIN ref.data_source r_ds
                                            ON (
                                                   (r_ds.pk = r_csr.fk_data_source)
                                             )
                                       )

                                   WHERE (c_lc2p.fk_item = c_pr.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_pr.fk_encounter AS pk_encounter
    ,
        c_pr.fk_episode AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        c_pr.pk AS src_pk
    ,
        'clin.procedure'::text AS src_table
    ,
        c_pr.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (
                                 (
                                       (clin.procedure c_pr

                                          JOIN clin.encounter c_enc
                                            ON (
                                                   (c_pr.fk_encounter = c_enc.pk)
                                             )
                                       )

                                    JOIN clin.encounter_type c_ety
                                      ON (
                                             (c_enc.fk_type = c_ety.pk)
                                       )
                                 )

                              JOIN clin.episode c_epi
                                ON (
                                       (c_pr.fk_episode = c_epi.pk)
                                 )
                           )

                   LEFT JOIN clin.health_issue c_hi
                          ON (
                                 (c_epi.fk_health_issue = c_hi.pk)
                           )
                     )

             LEFT JOIN clin.hospital_stay c_hs
                    ON (
                           (c_pr.fk_hospital_stay = c_hs.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (c_hs.fk_org_unit = d_ou.pk)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_ou.fk_org = d_o.pk)
         )
    )

    WHERE (c_pr.fk_hospital_stay IS NOT NULL);

Index - Schema clin

## View: clin.v_procedures_journal

clin.v_procedures_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT v_procedures_at_hospital_journal.pk_patient
    ,
        v_procedures_at_hospital_journal.modified_when
    ,
        v_procedures_at_hospital_journal.clin_when
    ,
        v_procedures_at_hospital_journal.modified_by
    ,
        v_procedures_at_hospital_journal.soap_cat
    ,
        v_procedures_at_hospital_journal.narrative
    ,
        v_procedures_at_hospital_journal.pk_encounter
    ,
        v_procedures_at_hospital_journal.pk_episode
    ,
        v_procedures_at_hospital_journal.pk_health_issue
    ,
        v_procedures_at_hospital_journal.src_pk
    ,
        v_procedures_at_hospital_journal.src_table
    ,
        v_procedures_at_hospital_journal.row_version
    ,
        v_procedures_at_hospital_journal.health_issue
    ,
        v_procedures_at_hospital_journal.issue_laterality
    ,
        v_procedures_at_hospital_journal.issue_active
    ,
        v_procedures_at_hospital_journal.issue_clinically_relevant
    ,
        v_procedures_at_hospital_journal.issue_confidential
    ,
        v_procedures_at_hospital_journal.episode
    ,
        v_procedures_at_hospital_journal.episode_open
    ,
        v_procedures_at_hospital_journal.encounter_started
    ,
        v_procedures_at_hospital_journal.encounter_last_affirmed
    ,
        v_procedures_at_hospital_journal.encounter_type
    ,
        v_procedures_at_hospital_journal.encounter_l10n_type

    FROM clin.v_procedures_at_hospital_journal

    UNION ALL

    SELECT v_procedures_not_at_hospital_journal.pk_patient
    ,
        v_procedures_not_at_hospital_journal.modified_when
    ,
        v_procedures_not_at_hospital_journal.clin_when
    ,
        v_procedures_not_at_hospital_journal.modified_by
    ,
        v_procedures_not_at_hospital_journal.soap_cat
    ,
        v_procedures_not_at_hospital_journal.narrative
    ,
        v_procedures_not_at_hospital_journal.pk_encounter
    ,
        v_procedures_not_at_hospital_journal.pk_episode
    ,
        v_procedures_not_at_hospital_journal.pk_health_issue
    ,
        v_procedures_not_at_hospital_journal.src_pk
    ,
        v_procedures_not_at_hospital_journal.src_table
    ,
        v_procedures_not_at_hospital_journal.row_version
    ,
        v_procedures_not_at_hospital_journal.health_issue
    ,
        v_procedures_not_at_hospital_journal.issue_laterality
    ,
        v_procedures_not_at_hospital_journal.issue_active
    ,
        v_procedures_not_at_hospital_journal.issue_clinically_relevant
    ,
        v_procedures_not_at_hospital_journal.issue_confidential
    ,
        v_procedures_not_at_hospital_journal.episode
    ,
        v_procedures_not_at_hospital_journal.episode_open
    ,
        v_procedures_not_at_hospital_journal.encounter_started
    ,
        v_procedures_not_at_hospital_journal.encounter_last_affirmed
    ,
        v_procedures_not_at_hospital_journal.encounter_type
    ,
        v_procedures_not_at_hospital_journal.encounter_l10n_type

    FROM clin.v_procedures_not_at_hospital_journal;

Index - Schema clin

## View: clin.v_procedures_not_at_hospital

clin.v_procedures_not_at_hospital Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_pr.pk AS pk_procedure
    ,
        c_enc.fk_patient AS pk_patient
    ,
        c_pr.soap_cat
    ,
        c_pr.clin_when
    ,
        c_pr.clin_end
    ,
        c_pr.is_ongoing
    ,
        c_pr.narrative AS performed_procedure
    ,
        c_pr.comment
    ,
        d_ou.description AS unit
    ,
        d_o.description AS organization
    ,
        c_ep.description AS episode
    ,
        c_hi.description AS health_issue
    ,
        c_pr.modified_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_pr.modified_by)
         )
         , (
               ('<'::text ||
                     (c_pr.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_pr.row_version
    ,
        c_pr.fk_encounter AS pk_encounter
    ,
        c_pr.fk_episode AS pk_episode
    ,
        c_pr.fk_hospital_stay AS pk_hospital_stay
    ,
        c_ep.fk_health_issue AS pk_health_issue
    ,
        c_pr.fk_doc AS pk_doc
    ,
        d_o.pk AS pk_org
    ,
        d_ou.pk AS pk_org_unit
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2p.fk_generic_code) AS array_agg

            FROM clin.lnk_code2procedure c_lc2p

           WHERE (c_lc2p.fk_item = c_pr.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    ,
        c_pr.xmin AS xmin_procedure

    FROM (
         (
               (
                     (
                           (clin.procedure c_pr

                              JOIN clin.encounter c_enc
                                ON (
                                       (c_pr.fk_encounter = c_enc.pk)
                                 )
                           )

                        JOIN clin.episode c_ep
                          ON (
                                 (c_pr.fk_episode = c_ep.pk)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_ep.fk_health_issue = c_hi.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (d_ou.pk = c_pr.fk_org_unit)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_o.pk = d_ou.fk_org)
         )
    )

    WHERE (c_pr.fk_hospital_stay IS NULL);

Index - Schema clin

## View: clin.v_procedures_not_at_hospital_journal

clin.v_procedures_not_at_hospital_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_pr.modified_when
    ,
        c_pr.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_pr.modified_by)
         )
         , (
               ('<'::text ||
                     (c_pr.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
            CASE
                WHEN
    (c_pr.is_ongoing IS TRUE) THEN 'p'::text
                ELSE 'o'::text
            END AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (_
                                                                           ('Procedure'::text) || ' "'::text
                                                                     ) || c_pr.narrative
                                                               ) || '"'::text
                                                         ) ||
                                                      ' ('::text) || d_ou.description
                                                   ) || ' @ '::text
                                             ) || d_o.description
                                       ) || COALESCE
                                       (
                                             (
                                                   (
                                                         (
                                                            ', '::text || _
                                                               ('until'::text)
                                                         ) || ' '::text
                                                   ) || to_char
                                                   (c_pr.clin_end
                                                         ,'YYYY Mon DD'::text
                                                   )
                                             )
                                             ,
            CASE
                WHEN
                                             (c_pr.is_ongoing IS TRUE) THEN
                                             (
                                                ', '::text || _
                                                   ('ongoing'::text)
                                             )
                ELSE ''::text
            END
                                       )
                                 ) ||
                         ')'::text
                     ) || COALESCE
                     (
                           ('
     '::text || c_pr.comment)
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           ('
     '::text || _
                                 ('document #'::text)
                           ) || c_pr.fk_doc
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     ('
    '::text || array_to_string
                           (
                                 (
                                  SELECT array_agg
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (r_csr.code ||
                                                                                          ' ('::text) || r_ds.name_short
                                                                                       ) || ' - '::text
                                                                                 ) || r_ds.version
                                                                           ) || ' - '::text
                                                                     ) || r_ds.lang
                                                               ) ||
                                                     '): '::text
                                                   ) || r_csr.term
                                             )
                                       ) AS array_agg

                                    FROM (
                                             (clin.lnk_code2procedure c_lc2p

                                                JOIN ref.coding_system_root r_csr
                                                  ON (
                                                         (c_lc2p.fk_generic_code = r_csr.pk_coding_system)
                                                   )
                                             )

                                          JOIN ref.data_source r_ds
                                            ON (
                                                   (r_ds.pk = r_csr.fk_data_source)
                                             )
                                       )

                                   WHERE (c_lc2p.fk_item = c_pr.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_pr.fk_encounter AS pk_encounter
    ,
        c_pr.fk_episode AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        c_pr.pk AS src_pk
    ,
        'clin.procedure'::text AS src_table
    ,
        c_pr.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (
                                 (clin.procedure c_pr

                                    JOIN clin.encounter c_enc
                                      ON (
                                             (c_pr.fk_encounter = c_enc.pk)
                                       )
                                 )

                              JOIN clin.encounter_type c_ety
                                ON (
                                       (c_enc.fk_type = c_ety.pk)
                                 )
                           )

                        JOIN clin.episode c_epi
                          ON (
                                 (c_pr.fk_episode = c_epi.pk)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_epi.fk_health_issue = c_hi.pk)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (c_pr.fk_org_unit = d_ou.pk)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_ou.fk_org = d_o.pk)
         )
    )

    WHERE (c_pr.fk_hospital_stay IS NULL);

Index - Schema clin

## View: clin.v_reminders_journal

clin.v_reminders_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_mi.fk_patient AS pk_patient
    ,
        d_mi.modified_when
    ,
        d_mi.due_date AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = d_mi.modified_by)
         )
         , (
               ('<'::text ||
                     (d_mi.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        NULL::text AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (
                                                                                             (_
                                                                                                   ('Due today'::text) ||
                                                                                                ' ('::text) || d_vit.l10n_category
                                                                                             ) || ' - '::text
                                                                                       ) || d_vit.l10n_type
                                                                                 ) ||
                                                                         ')'::text
                                                                     ) || '
    '::text
                                                               ) || COALESCE
                                                               (
                                                                     (
                                                                           (' '::text || d_mi.comment) || '
    '::text
                                                                     )
                                                                     ,''::text
                                                               )
                                                         ) || COALESCE
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (' '::text || _
                                                                                       ('Will expire:'::text)
                                                                                 ) || ' '::text
                                                                           ) || to_char
                                                                           (
                                                                                 (d_mi.expiry_date)::timestamp with time zone
                                                                                 ,'YYYY-MM-DD'::text
                                                                           )
                                                                     ) || '
    '::text
                                                               )
                                                               ,''::text
                                                         )
                                                   ) || ' '::text
                                             ) || _
                                             ('Importance:'::text)
                                       ) || ' '::text
                                 ) || d_mi.importance
                           ) || '
    '::text
                     ) || COALESCE
                     (
                           (
                                 (
                                       (
                                             (' '::text || _
                                                   ('Context:'::text)
                                             ) || ' '::text
                                       ) || array_to_string
                                       (d_mi.ufk_context
                                             ,','::text
                                             ,'?'::text
                                       )
                                 ) || '
    '::text
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           (
                                 (
                                       (' '::text || _
                                             ('Data:'::text)
                                       ) || ' '::text
                                 ) || d_mi.data
                           ) || '
    '::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (
                           (' '::text || _
                                 ('Provider:'::text)
                           ) || ' '::text
                     ) || d_st.short_alias
               )
               ,''::text
         )
    ) AS narrative
    ,

    (
    SELECT c_e.pk

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = d_mi.fk_patient)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS pk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        NULL::integer AS pk_health_issue
    ,
        d_mi.pk AS src_pk
    ,
        'dem.message_inbox'::text AS src_table
    ,
        d_mi.row_version
    ,
        NULL::text AS health_issue
    ,
        NULL::text AS issue_laterality
    ,
        NULL::boolean AS issue_active
    ,
        NULL::boolean AS issue_clinically_relevant
    ,
        NULL::boolean AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,

    (
    SELECT c_e.started

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = d_mi.fk_patient)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS encounter_started
    ,

    (
    SELECT c_e.last_affirmed

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = d_mi.fk_patient)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS encounter_last_affirmed
    ,
        NULL::text AS encounter_type
    ,
        NULL::text AS encounter_l10n_type

    FROM (
         (dem.message_inbox d_mi

            JOIN dem.v_inbox_item_type d_vit
              ON (
                     (d_mi.fk_inbox_item_type = d_vit.pk_type)
               )
         )

    LEFT JOIN dem.staff d_st
        ON (
               (d_mi.fk_staff = d_st.pk)
         )
    )

    WHERE (
         (d_mi.fk_patient IS NOT NULL)
       AND (d_vit.category = 'clinical'::text)
       AND (d_mi.due_date IS NOT NULL)
    )
    UNION

    SELECT d_mi.fk_patient AS pk_patient
    ,
        d_mi.modified_when
    ,
        d_mi.expiry_date AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = d_mi.modified_by)
         )
         , (
               ('<'::text ||
                     (d_mi.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        NULL::text AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (
                                                                                             (_
                                                                                                   ('Epires today'::text) ||
                                                                                                ' ('::text) || d_vit.l10n_category
                                                                                             ) || ' - '::text
                                                                                       ) || d_vit.l10n_type
                                                                                 ) ||
                                                                         ')'::text
                                                                     ) || '
    '::text
                                                               ) || COALESCE
                                                               (
                                                                     (
                                                                           (' '::text || d_mi.comment) || '
    '::text
                                                                     )
                                                                     ,''::text
                                                               )
                                                         ) || COALESCE
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (' '::text || _
                                                                                       ('Was due:'::text)
                                                                                 ) || ' '::text
                                                                           ) || to_char
                                                                           (
                                                                                 (d_mi.due_date)::timestamp with time zone
                                                                                 ,'YYYY-MM-DD'::text
                                                                           )
                                                                     ) || '
    '::text
                                                               )
                                                               ,''::text
                                                         )
                                                   ) || ' '::text
                                             ) || _
                                             ('Importance:'::text)
                                       ) || ' '::text
                                 ) || d_mi.importance
                           ) || '
    '::text
                     ) || COALESCE
                     (
                           (
                                 (
                                       (
                                             (' '::text || _
                                                   ('Context:'::text)
                                             ) || ' '::text
                                       ) || array_to_string
                                       (d_mi.ufk_context
                                             ,','::text
                                             ,'?'::text
                                       )
                                 ) || '
    '::text
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           (
                                 (
                                       (' '::text || _
                                             ('Data:'::text)
                                       ) || ' '::text
                                 ) || d_mi.data
                           ) || '
    '::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (
                           (' '::text || _
                                 ('Provider:'::text)
                           ) || ' '::text
                     ) || d_st.short_alias
               )
               ,''::text
         )
    ) AS narrative
    ,

    (
    SELECT c_e.pk

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = d_mi.fk_patient)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS pk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        NULL::integer AS pk_health_issue
    ,
        d_mi.pk AS src_pk
    ,
        'dem.message_inbox'::text AS src_table
    ,
        d_mi.row_version
    ,
        NULL::text AS health_issue
    ,
        NULL::text AS issue_laterality
    ,
        NULL::boolean AS issue_active
    ,
        NULL::boolean AS issue_clinically_relevant
    ,
        NULL::boolean AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,

    (
    SELECT c_e.started

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = d_mi.fk_patient)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS encounter_started
    ,

    (
    SELECT c_e.last_affirmed

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = d_mi.fk_patient)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS encounter_last_affirmed
    ,
        NULL::text AS encounter_type
    ,
        NULL::text AS encounter_l10n_type

    FROM (
         (dem.message_inbox d_mi

            JOIN dem.v_inbox_item_type d_vit
              ON (
                     (d_mi.fk_inbox_item_type = d_vit.pk_type)
               )
         )

    LEFT JOIN dem.staff d_st
        ON (
               (d_mi.fk_staff = d_st.pk)
         )
    )

    WHERE (
         (d_mi.fk_patient IS NOT NULL)
       AND (d_vit.category = 'clinical'::text)
       AND (d_mi.expiry_date IS NOT NULL)
    )
    UNION

    SELECT d_mi.fk_patient AS pk_patient
    ,
        d_mi.modified_when
    ,
        d_mi.modified_when AS clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = d_mi.modified_by)
         )
         , (
               ('<'::text ||
                     (d_mi.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        NULL::text AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (
                                                                                             (
                                                                                                   (_
                                                                                                         ('Clinical reminder'::text) ||
                                                                                                      ' ('::text) || d_vit.l10n_category
                                                                                                   ) || ' - '::text
                                                                                             ) || d_vit.l10n_type
                                                                                       ) ||
                                                                               ')'::text
                                                                           ) || '
    '::text
                                                                     ) || COALESCE
                                                                     (
                                                                           (
                                                                                 (' '::text || d_mi.comment) || '
    '::text
                                                                           )
                                                                           ,''::text
                                                                     )
                                                               ) || COALESCE
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (' '::text || _
                                                                                             ('Due:'::text)
                                                                                       ) || ' '::text
                                                                                 ) || to_char
                                                                                 (
                                                                                       (d_mi.due_date)::timestamp with time zone
                                                                                       ,'YYYY-MM-DD'::text
                                                                                 )
                                                                           ) || '
    '::text
                                                                     )
                                                                     ,''::text
                                                               )
                                                         ) || COALESCE
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (' '::text || _
                                                                                       ('Expires:'::text)
                                                                                 ) || ' '::text
                                                                           ) || to_char
                                                                           (
                                                                                 (d_mi.expiry_date)::timestamp with time zone
                                                                                 ,'YYYY-MM-DD'::text
                                                                           )
                                                                     ) || '
    '::text
                                                               )
                                                               ,''::text
                                                         )
                                                   ) || ' '::text
                                             ) || _
                                             ('Importance:'::text)
                                       ) || ' '::text
                                 ) || d_mi.importance
                           ) || '
    '::text
                     ) || COALESCE
                     (
                           (
                                 (
                                       (
                                             (' '::text || _
                                                   ('Context:'::text)
                                             ) || ' '::text
                                       ) || array_to_string
                                       (d_mi.ufk_context
                                             ,','::text
                                             ,'?'::text
                                       )
                                 ) || '
    '::text
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           (
                                 (
                                       (' '::text || _
                                             ('Data:'::text)
                                       ) || ' '::text
                                 ) || d_mi.data
                           ) || '
    '::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (
                           (' '::text || _
                                 ('Provider:'::text)
                           ) || ' '::text
                     ) || d_st.short_alias
               )
               ,''::text
         )
    ) AS narrative
    ,

    (
    SELECT c_e.pk

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = d_mi.fk_patient)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS pk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        NULL::integer AS pk_health_issue
    ,
        d_mi.pk AS src_pk
    ,
        'dem.message_inbox'::text AS src_table
    ,
        d_mi.row_version
    ,
        NULL::text AS health_issue
    ,
        NULL::text AS issue_laterality
    ,
        NULL::boolean AS issue_active
    ,
        NULL::boolean AS issue_clinically_relevant
    ,
        NULL::boolean AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,

    (
    SELECT c_e.started

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = d_mi.fk_patient)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS encounter_started
    ,

    (
    SELECT c_e.last_affirmed

      FROM clin.encounter c_e

     WHERE (c_e.fk_patient = d_mi.fk_patient)

    ORDER BY c_e.started DESC
             LIMIT 1
    ) AS encounter_last_affirmed
    ,
        NULL::text AS encounter_type
    ,
        NULL::text AS encounter_l10n_type

    FROM (
         (dem.message_inbox d_mi

            JOIN dem.v_inbox_item_type d_vit
              ON (
                     (d_mi.fk_inbox_item_type = d_vit.pk_type)
               )
         )

    LEFT JOIN dem.staff d_st
        ON (
               (d_mi.fk_staff = d_st.pk)
         )
    )

    WHERE (
         (d_mi.fk_patient IS NOT NULL)
       AND (d_vit.category = 'clinical'::text)
       AND (
               (d_mi.due_date IS NOT NULL)
              OR (d_mi.expiry_date IS NOT NULL)
         )
    );

Index - Schema clin

## View: clin.v_reviewed_items

denormalization of parent table of reviewed items

clin.v_reviewed_items Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT (
    SELECT pg_class.relnamespace

      FROM pg_class

     WHERE (pg_class.oid = rr.tableoid)
    ) AS src_schema
    ,

    (
    SELECT pg_class.relname

      FROM pg_class

     WHERE (pg_class.oid = rr.tableoid)
    ) AS src_table
    ,
        rr.fk_reviewed_row AS pk_reviewed_row
    ,
        rr.is_technically_abnormal
    ,
        rr.clinically_relevant
    ,

    (
    SELECT staff.short_alias

      FROM dem.staff

     WHERE (staff.pk = rr.fk_reviewer)
    ) AS reviewer
    ,
        rr.comment
    ,
        rr.pk AS pk_review_root
    ,
        rr.fk_reviewer AS pk_reviewer

    FROM clin.review_root rr;

Index - Schema clin

## View: clin.v_subst_intake4narr_search

clin.v_subst_intake4narr_search Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_si.soap_cat
    ,

    (
         (
               (
                     (COALESCE
                           (c_si.narrative
                                 ,''::text
                           ) || COALESCE
                           (
                                 (' / '::text || c_si.comment_on_start)
                                 ,''::text
                           )
                     ) || COALESCE
                     (
                           (' / '::text || c_si.schedule)
                           ,''::text
                     )
               ) || COALESCE
               (
                     (' / '::text || c_si.aim)
                     ,''::text
               )
         ) || COALESCE
         (
               (' / '::text || c_si.discontinue_reason)
               ,''::text
         )
    ) AS narrative
    ,
        c_si.fk_encounter AS pk_encounter
    ,
        c_si.fk_episode AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        c_si.pk AS src_pk
    ,
        'clin.substance_intake'::text AS src_table

    FROM (
         (clin.substance_intake c_si

            JOIN clin.encounter c_enc
              ON (
                     (c_si.fk_encounter = c_enc.pk)
               )
         )

      JOIN clin.episode c_epi
        ON (
               (c_si.fk_episode = c_epi.pk)
         )
    );

Index - Schema clin

## View: clin.v_substance_intake_journal

clin.v_substance_intake_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_si.modified_when
    ,
        c_si.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_si.modified_by)
         )
         , (
               ('<'::text ||
                     (c_si.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_si.soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (
                                                                                             (
                                                                                                   (
                                                                                                         (
                                                                                                               (
                                                                                                                     (
                                                                                                                           (
                                                                                                                                 (
                                                                                                                                       (
            CASE
                WHEN
                                                                                                                                             (c_si.is_long_term IS TRUE) THEN
                                                                                                                                             (_
                                                                                                                                                   ('long-term'::text) || ' '::text
                                                                                                                                             )
                ELSE ''::text
            END || _
                                                                                                                                             ('substance intake'::text)
                                                                                                                                       ) || ' '::text
                                                                                                                                 ) ||
            CASE
                WHEN
                                                                                                                                 (c_si.intake_is_approved_of IS TRUE) THEN _
                                                                                                                                 ('(approved of)'::text
                                                                                                                           )
                WHEN
                                                                                                                           (c_si.intake_is_approved_of IS FALSE) THEN _
                                                                                                                           ('(not approved of)'::text
                                                                                                                     )
                ELSE _
                                                                                                                     ('(of unknown approval)'::text
                                                                                                               )
            END
                                                                                                         ) || ' '::text
                                                                                                   ) ||
            CASE
                WHEN
                                                                                                   (c_si.harmful_use_type IS NULL) THEN ''::text
                WHEN
                                                                                                   (c_si.harmful_use_type = 0) THEN _
                                                                                                   ('no harmful use'::text)
                WHEN
                                                                                                   (c_si.harmful_use_type = 1) THEN _
                                                                                                   ('harmful use'::text)
                WHEN
                                                                                                   (c_si.harmful_use_type = 2) THEN _
                                                                                                   ('addiction'::text)
                WHEN
                                                                                                   (c_si.harmful_use_type = 3) THEN _
                                                                                                   ('previous addiction'::text)
                ELSE NULL::text
            END
                                                                                             ) || ':
    '::text
                                                                                       ) || ' '::text
                                                                                 ) || r_s.description
                                                                           ) || COALESCE
                                                                           (
                                                                                 (
                                                                                       (' ['::text || r_s.atc) || '] '::text
                                                                                 )
                                                                                 ,' '::text
                                                                           )
                                                                     ) ||
                                                                     (r_d.amount)::text
                                                               ) || r_d.unit
                                                         ) || ' '::text
                                                   ) || _
                                                   (r_dp.preparation)
                                             ) || COALESCE
                                             (
                                                   (' '::text || c_si.schedule)
                                                   ,''::text
                                             )
                                       ) ||
                                    ', '::text
                                 ) ||
            CASE
                WHEN
                                 (c_si.comment_on_start = '?'::text) THEN '?'::text
                WHEN
                                 (c_si.comment_on_start IS NULL) THEN to_char
                                 (c_si.clin_when
                                       ,'YYYY-MM-DD'::text
                                 )
                ELSE
                                 (
                                       (
                                             (
                                                   ('~'::text || to_char
                                                         (c_si.clin_when
                                                               ,'YYYY-MM-DD'::text
                                                         )
                                                   ) ||
                                                ' ('::text) || c_si.comment_on_start
                                             ) ||
                                     ')'::text
                                 )
            END
                           ) || COALESCE
                           (
                                 (' -> '::text || c_si.duration)
                                 ,''::text
                           )
                     ) || '
    '::text
               ) || COALESCE
               (
                     (
                           (
                                 (
                                       (' '::text || _
                                             ('Discontinued'::text)
                                       ) || to_char
                                       (c_si.discontinued
                                             ,': YYYY-MM-DD'::text
                                       )
                                 ) || COALESCE
                                 (
                                       (
                                             (
                                                ' ('::text || c_si.discontinue_reason) ||
                                           ')'::text
                                       )
                                       ,''::text
                                 )
                           ) || '
    '::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (
                           ('
     '::text || _
                                 ('Aim'::text)
                           ) || ': '::text
                     ) || c_si.aim
               )
               ,''::text
         )
    ) || COALESCE
    (
         (
               (
                     ('
     '::text || _
                           ('Notes'::text)
                     ) || ': '::text
               ) || c_si.narrative
         )
         ,''::text
    )
    )      || COALESCE
    (
    (
         (
               ('
     '::text || _
                     ('Instructions'::text)
               ) || ': '::text
         ) || r_s.intake_instructions
    )
    ,''::text
    )
    )            || COALESCE
    (
    (
    (
         (
               (' "'::text || r_dp.description) || '"'::text
         ) || COALESCE
         (
               (
                     (' ['::text || r_dp.atc_code) || ']'::text
               )
               ,''::text
         )
    ) || COALESCE
    (
         (
               (
                     (
                           (
                              ' ('::text || r_dp.external_code_type) || ': '::text
                           ) || r_dp.external_code
                     ) ||
             ')'::text
         )
         ,''::text
    )
    )
    ,     ''::text
    )
    )                  AS narrative
    ,
        c_si.fk_encounter AS pk_encounter
    ,
        c_si.fk_episode AS pk_episode
    ,
        c_hi.pk AS pk_health_issue
    ,
        c_si.pk AS src_pk
    ,
        'clin.substance_intake'::text AS src_table
    ,
        c_si.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (                 c_ety.description) AS encounter_l10n_type

    FROM               (
    (
    (
    (
         (
               (
                     (
                           (clin.substance_intake c_si

                              JOIN ref.lnk_dose2drug r_ld2d
                                ON (
                                       (c_si.fk_drug_component = r_ld2d.pk)
                                 )
                           )

                        JOIN ref.drug_product r_dp
                          ON (
                                 (r_ld2d.fk_drug_product = r_dp.pk)
                           )
                     )

                  JOIN ref.dose r_d
                    ON (
                           (r_ld2d.fk_dose = r_d.pk)
                     )
               )

            JOIN ref.substance r_s
              ON (
                     (r_d.fk_substance = r_s.pk)
               )
         )

      JOIN clin.encounter c_enc
        ON (
               (c_si.fk_encounter = c_enc.pk)
         )
    )

    JOIN clin.encounter_type c_ety
    ON (
         (c_enc.fk_type = c_ety.pk)
    )
    )

    JOIN   clin.episode c_epi
    ON     (
    (c_si.fk_episode = c_epi.pk)
    )
    )

    LEFT JOIN    clin.health_issue c_hi
    ON           (
    (     c_epi.fk_health_issue = c_hi.pk)
    )
    )                 ;

Index - Schema clin

## View: clin.v_substance_intakes

clin.v_substance_intakes Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_si.pk AS pk_substance_intake
    ,
        c_enc.fk_patient AS pk_patient
    ,
        c_si.soap_cat
    ,
        r_dp.description AS product
    ,
        r_dp.preparation
    ,
        _
    (r_dp.preparation) AS l10n_preparation
    ,
        r_s.description AS substance
    ,
        r_d.amount
    ,
        r_d.unit
    ,
        r_d.dose_unit
    ,
        r_s.atc AS atc_substance
    ,
        r_dp.atc_code AS atc_drug
    ,
        r_dp.external_code AS external_code_product
    ,
        r_dp.external_code_type AS external_code_type_product
    ,
        ARRAY
    (
    SELECT row_to_json
         (loinc_row.*) AS row_to_json

      FROM (
          SELECT r_ll2s.loinc
               ,
                        r_ll2s.comment
               ,
                        date_part
               ('epoch'::text
                     , r_ll2s.max_age
               ) AS max_age_in_secs
               ,

               (r_ll2s.max_age)::text AS max_age_str

            FROM ref.lnk_loinc2substance r_ll2s

           WHERE (r_ll2s.fk_substance = r_s.pk)
         ) loinc_row
    ) AS loincs
    ,
            CASE
                WHEN
    (c_si.comment_on_start = '?'::text) THEN NULL::timestamp with time zone
                ELSE c_si.clin_when
            END AS started
    ,
        c_si.comment_on_start
    ,
            CASE
                WHEN
    (c_si.comment_on_start = '?'::text) THEN true
                ELSE false
            END AS start_is_unknown
    ,
            CASE
                WHEN
    (c_si.comment_on_start IS NULL) THEN false
                ELSE true
            END AS start_is_approximate
    ,
        c_si.intake_is_approved_of
    ,
        c_si.harmful_use_type
    ,
        c_enc.started AS last_checked_when
    ,
        c_si.schedule
    ,
        c_si.duration
    ,
        c_si.discontinued
    ,
        c_si.discontinue_reason
    ,
        c_si.is_long_term
    ,
        c_si.aim
    ,
        r_s.intake_instructions
    ,
        c_epi.description AS episode
    ,
        c_hi.description AS health_issue
    ,
        c_si.narrative AS notes
    ,
        r_dp.is_fake AS is_fake_product
    ,
            CASE
                WHEN
    (c_si.discontinued IS NULL) THEN true
                ELSE false
            END AS is_currently_active
    ,
            CASE
                WHEN
    (c_si.discontinued IS NOT NULL) THEN true
                WHEN
    (c_si.clin_when IS NULL) THEN
                CASE
                    WHEN
    (c_si.is_long_term IS TRUE) THEN false
                    ELSE NULL::boolean
                END
                WHEN
    (
         (c_si.clin_when > now
               ()
         ) IS TRUE
    ) THEN true
                WHEN
    (
         (
               (c_si.clin_when + c_si.duration) < now
               ()
         ) IS TRUE
    ) THEN true
                WHEN
    (
         (
               (c_si.clin_when + c_si.duration) > now
               ()
         ) IS TRUE
    ) THEN false
                ELSE NULL::boolean
            END AS seems_inactive
    ,
        r_ld2d.fk_drug_product AS pk_drug_product
    ,
        r_dp.fk_data_source AS pk_data_source
    ,
        r_ld2d.fk_dose AS pk_dose
    ,
        r_ld2d.pk AS pk_drug_component
    ,
        r_d.fk_substance AS pk_substance
    ,
        c_si.fk_encounter AS pk_encounter
    ,
        c_si.fk_episode AS pk_episode
    ,
        c_epi.fk_health_issue AS pk_health_issue
    ,
        c_si.modified_when
    ,
        c_si.modified_by
    ,
        c_si.row_version
    ,
        c_si.xmin AS xmin_substance_intake

    FROM (
         (
               (
                     (
                           (
                                 (
                                       (clin.substance_intake c_si

                                     LEFT JOIN clin.encounter c_enc
                                            ON (
                                                   (c_si.fk_encounter = c_enc.pk)
                                             )
                                       )

                               LEFT JOIN clin.episode c_epi
                                      ON (
                                             (c_si.fk_episode = c_epi.pk)
                                       )
                                 )

                         LEFT JOIN clin.health_issue c_hi
                                ON (
                                       (c_hi.pk = c_epi.fk_health_issue)
                                 )
                           )

                        JOIN ref.lnk_dose2drug r_ld2d
                          ON (
                                 (c_si.fk_drug_component = r_ld2d.pk)
                           )
                     )

                  JOIN ref.drug_product r_dp
                    ON (
                           (r_ld2d.fk_drug_product = r_dp.pk)
                     )
               )

            JOIN ref.dose r_d
              ON (
                     (r_ld2d.fk_dose = r_d.pk)
               )
         )

      JOIN ref.substance r_s
        ON (
               (r_d.fk_substance = r_s.pk)
         )
    );

Index - Schema clin

## View: clin.v_suppressed_hints

clin.v_suppressed_hints Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT (
    SELECT encounter.fk_patient

      FROM clin.encounter

     WHERE (encounter.pk = c_sh.fk_encounter)
    ) AS pk_identity
    ,
        c_sh.pk AS pk_suppressed_hint
    ,
        c_sh.fk_hint AS pk_hint
    ,
        r_vah.title
    ,
        r_vah.hint
    ,
        r_vah.recommendation
    ,
        r_vah.url
    ,
        r_vah.is_active
    ,
        r_vah.source
    ,
        r_vah.query
    ,
        r_vah.lang
    ,
        c_sh.rationale
    ,
        r_vah.popup_type
    ,
        r_vah.highlight_as_priority
    ,
        c_sh.md5_sum AS md5_suppressed
    ,
        r_vah.md5_sum AS md5_hint
    ,
        c_sh.suppressed_by
    ,
        c_sh.suppressed_when
    ,
        c_sh.fk_encounter AS pk_encounter

    FROM (clin.suppressed_hint c_sh

      JOIN ref.v_auto_hints r_vah
        ON (
               (c_sh.fk_hint = r_vah.pk_auto_hint)
         )
    );

Index - Schema clin

## View: clin.v_suppressed_hints_journal

clin.v_suppressed_hints_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_sh.modified_when
    ,
        c_sh.suppressed_when AS clin_when
    ,
        c_sh.modified_by
    ,
        'p'::text AS soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
            CASE
                WHEN
                                                                                       (r_vah.is_active IS TRUE) THEN _
                                                                                       ('Active hint'::text)
                ELSE _
                                                                                       ('Inactive hint'::text)
            END || ' #'::text
                                                                                 ) || c_sh.fk_hint
                                                                           ) || ' '::text
                                                                     ) || _
                                                                     ('suppressed by'::text)
                                                               ) || ' '::text
                                                         ) ||
                                                         (c_sh.suppressed_by)::text
                                                   ) || '
    '::text
                                             ) || COALESCE
                                             (
                                                   (
                                                         (_
                                                               ('Title: '::text) || r_vah.title
                                                         ) || '
    '::text
                                                   )
                                                   ,''::text
                                             )
                                       ) || COALESCE
                                       (
                                             (
                                                   (_
                                                         ('URL: '::text) || r_vah.url
                                                   ) || '
    '::text
                                             )
                                             ,''::text
                                       )
                                 ) || COALESCE
                                 (
                                       (
                                             (_
                                                   ('Source: '::text) || r_vah.source
                                             ) || '
    '::text
                                       )
                                       ,''::text
                                 )
                           ) || COALESCE
                           (
                                 (
                                       (_
                                             ('Rationale: '::text) || c_sh.rationale
                                       ) || '
    '::text
                                 )
                                 ,''::text
                           )
                     ) ||
            CASE
                WHEN
                     (c_sh.md5_sum <> r_vah.md5_sum) THEN
                     (_
                           ('Hint definition has been modified since suppression. Rationale for suppression may no longer apply.'::text) || '
    '::text
                     )
                ELSE ''::text
            END
               ) || COALESCE
               (
                     (
                           (_
                                 ('Hint: '::text) || r_vah.hint
                           ) || '
    '::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (_
                     ('Recommendation: '::text) || r_vah.recommendation
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_sh.fk_encounter
    ,
        NULL::integer AS pk_episode
    ,
        NULL::integer AS pk_health_issue
    ,
        c_sh.pk AS src_pk
    ,
        'clin.suppressed_hint'::text AS src_table
    ,
        c_sh.row_version
    ,
        NULL::text AS health_issue
    ,
        NULL::text AS issue_laterality
    ,
        NULL::boolean AS issue_active
    ,
        NULL::boolean AS issue_clinically_relevant
    ,
        NULL::boolean AS issue_confidential
    ,
        NULL::text AS episode
    ,
        NULL::boolean AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (clin.suppressed_hint c_sh

                  JOIN clin.encounter c_enc
                    ON (
                           (c_sh.fk_encounter = c_enc.pk)
                     )
               )

            JOIN clin.encounter_type c_ety
              ON (
                     (c_enc.fk_type = c_ety.pk)
               )
         )

      JOIN ref.v_auto_hints r_vah
        ON (
               (c_sh.fk_hint = r_vah.pk_auto_hint)
         )
    );

Index - Schema clin

## View: clin.v_test_orgs

clin.v_test_orgs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_to.pk AS pk_test_org
    ,
        d_o.description AS organization
    ,
        d_ou.description AS unit
    ,
        c_to.comment
    ,
        c_to.contact AS test_org_contact
    ,
        c_to.fk_adm_contact AS pk_adm_contact
    ,
        c_to.fk_med_contact AS pk_med_contact
    ,
        d_o.pk AS pk_org
    ,
        d_o.fk_category AS category_org
    ,
        d_ou.pk AS pk_org_unit
    ,
        d_ou.fk_category AS category_unit
    ,
        d_ou.fk_address AS pk_address_unit
    ,
        c_to.xmin AS xmin_test_org

    FROM (
         (clin.test_org c_to

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (c_to.fk_org_unit = d_ou.pk)
               )
         )

    LEFT JOIN dem.org d_o
        ON (
               (d_ou.fk_org = d_o.pk)
         )
    );

Index - Schema clin

## View: clin.v_test_panels

clin.v_test_panels Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_tp.pk AS pk_test_panel
    ,
        c_tp.description
    ,
        c_tp.comment
    ,
        c_tp.modified_when
    ,
        c_tp.modified_by
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_ll2tp.loinc) AS array_agg

            FROM clin.lnk_loinc2test_panel c_ll2tp

           WHERE (c_ll2tp.fk_test_panel = c_tp.pk)
         )
         , ARRAY[]::text[]
    ) AS loincs
    ,
        ARRAY
    (
    SELECT row_to_json
         (test_type_row.*) AS row_to_json

      FROM (
          SELECT c_ll2tp.loinc
               ,
                        c_tt.pk AS pk_test_type
               ,
                        c_tt.fk_meta_test_type AS pk_meta_test_type

            FROM (clin.lnk_loinc2test_panel c_ll2tp

                  JOIN clin.test_type c_tt
                    ON (
                           (c_ll2tp.loinc = c_tt.loinc)
                     )
               )

           WHERE (c_ll2tp.fk_test_panel = c_tp.pk)
         ) test_type_row
    ) AS test_types
    ,
        COALESCE
    (
         (
          SELECT array_agg
               (c_lc2tp.fk_generic_code) AS array_agg

            FROM clin.lnk_code2tst_pnl c_lc2tp

           WHERE (c_lc2tp.fk_item = c_tp.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    ,
        c_tp.row_version
    ,
        c_tp.xmin AS xmin_test_panel

    FROM clin.test_panel c_tp;

Index - Schema clin

## View: clin.v_test_results

denormalized view over test_results joined with (possibly unified) test type and patient/episode/encounter keys

clin.v_test_results Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT cenc.fk_patient AS pk_patient
    ,
        tr.pk AS pk_test_result
    ,
        tr.clin_when
    ,
        c_vtt.unified_abbrev
    ,
        c_vtt.unified_name
    ,
        c_vtt.unified_loinc
    ,
            CASE
                WHEN
    (COALESCE
         (btrim
               (tr.val_alpha)
               ,''::text
         ) = ''::text
    ) THEN
    (tr.val_num)::text
                ELSE
                CASE
                    WHEN
    (tr.val_num IS NULL) THEN tr.val_alpha
                    ELSE
    (
         (
               (
                     (tr.val_num)::text ||
                  ' ('::text) || tr.val_alpha
               ) ||
       ')'::text
    )
                END
            END AS unified_val
    ,
        COALESCE
    (tr.val_target_min
         , tr.val_normal_min
    ) AS unified_target_min
    ,
        COALESCE
    (tr.val_target_max
         , tr.val_normal_max
    ) AS unified_target_max
    ,
        COALESCE
    (tr.val_target_range
         , tr.val_normal_range
    ) AS unified_target_range
    ,
        tr.status
    ,
        tr.soap_cat
    ,
        tr.narrative AS comment
    ,
        tr.val_num
    ,
        tr.val_alpha
    ,
        tr.val_unit
    ,
        c_vtt.reference_unit
    ,
        tr.val_normal_min
    ,
        tr.val_normal_max
    ,
        tr.val_normal_range
    ,
        tr.val_target_min
    ,
        tr.val_target_max
    ,
        tr.val_target_range
    ,
        tr.abnormality_indicator
    ,
        tr.norm_ref_group
    ,
        tr.note_test_org
    ,
        tr.material
    ,
        tr.material_detail
    ,
        c_vtt.abbrev AS abbrev_tt
    ,
        c_vtt.name AS name_tt
    ,
        c_vtt.loinc AS loinc_tt
    ,
        c_vtt.comment_type AS comment_tt
    ,
        c_vtt.name_org AS name_test_org
    ,
        c_vtt.contact_org AS contact_test_org
    ,
        c_vtt.comment_org AS comment_test_org
    ,
        c_vtt.is_fake_meta_type
    ,
        c_vtt.abbrev_meta
    ,
        c_vtt.name_meta
    ,
        c_vtt.loinc_meta
    ,
        c_vtt.comment_meta
    ,
        epi.description AS episode
    ,
        chi.description AS health_issue
    ,

    (COALESCE
         (rtr.fk_reviewed_row
               , 0
         )
    )::boolean AS reviewed
    ,
        rtr.is_technically_abnormal
    ,
        rtr.clinically_relevant AS is_clinically_relevant
    ,
        rtr.comment AS review_comment
    ,

    (
    SELECT staff.short_alias

      FROM dem.staff

     WHERE (staff.pk = rtr.fk_reviewer)
    ) AS last_reviewer
    ,
        rtr.modified_when AS last_reviewed
    ,
        COALESCE
    (
         (rtr.fk_reviewer =
               (
                SELECT staff.pk

                  FROM dem.staff

                 WHERE (staff.db_user = "current_user"
                           ()
                     )
               )
         )
         , false
    ) AS review_by_you
    ,
        COALESCE
    (
         (tr.fk_intended_reviewer = rtr.fk_reviewer)
         , false
    ) AS review_by_responsible_reviewer
    ,

    (
    SELECT staff.short_alias

      FROM dem.staff

     WHERE (staff.pk = tr.fk_intended_reviewer)
    ) AS responsible_reviewer
    ,
        COALESCE
    (
         (tr.fk_intended_reviewer =
               (
                SELECT staff.pk

                  FROM dem.staff

                 WHERE (staff.db_user = "current_user"
                           ()
                     )
               )
         )
         , false
    ) AS you_are_responsible
    ,
            CASE
                WHEN
    (
         (
          SELECT 1

            FROM dem.staff

           WHERE (staff.db_user = tr.modified_by)
         ) IS NULL
    ) THEN
    (
         ('<'::text ||
               (tr.modified_by)::text
         ) || '>'::text
    )
                ELSE
    (
    SELECT staff.short_alias

      FROM dem.staff

     WHERE (staff.db_user = tr.modified_by)
    )
            END AS modified_by
    ,
        tr.val_grouping
    ,
        tr.source_data
    ,
        tr.modified_when
    ,
        tr.row_version
    ,
        tr.pk_item
    ,
        tr.fk_encounter AS pk_encounter
    ,
        tr.fk_episode AS pk_episode
    ,
        tr.fk_type AS pk_test_type
    ,
        tr.fk_intended_reviewer AS pk_intended_reviewer
    ,
        tr.fk_request AS pk_request
    ,
        tr.xmin AS xmin_test_result
    ,
        c_vtt.pk_test_org
    ,
        c_vtt.pk_meta_test_type
    ,
        epi.fk_health_issue AS pk_health_issue
    ,
        rtr.fk_reviewer AS pk_last_reviewer

    FROM (
         (
               (
                     (clin.test_result tr

                   LEFT JOIN clin.encounter cenc
                          ON (
                                 (tr.fk_encounter = cenc.pk)
                           )
                     )

             LEFT JOIN clin.episode epi
                    ON (
                           (tr.fk_episode = epi.pk)
                     )
               )

       LEFT JOIN clin.reviewed_test_results rtr
              ON (
                     (tr.pk = rtr.fk_reviewed_row)
               )
         )

    LEFT JOIN clin.health_issue chi
        ON (
               (epi.fk_health_issue = chi.pk)
         )
    )
    ,
        clin.v_test_types c_vtt

    WHERE (tr.fk_type = c_vtt.pk_test_type);

Index - Schema clin

## View: clin.v_test_results_journal

formatting of v_test_results for inclusion in v_emr_journal

clin.v_test_results_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_vtr.pk_patient
    ,
        c_vtr.modified_when
    ,
        c_vtr.clin_when
    ,
        c_vtr.modified_by
    ,
        c_vtr.soap_cat
    ,
        COALESCE
    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (
                                                                                             (
                                                                                                   (
                                                                                                         (
                                                                                                               (
                                                                                                                     (
                                                                                                                           (
                                                                                                                                 (
                                                                                                                                       (
                                                                                                                                             (
                                                                                                                                                   (
                                                                                                                                                         (
                                                                                                                                                               (c_vtr.unified_name ||
                                                                                                                                                                  ' ('::text) || c_vtr.unified_abbrev
                                                                                                                                                               ) || COALESCE
                                                                                                                                                               (
                                                                                                                                                                     (
                                                                                                                                                                           (' [#'::text || c_vtr.unified_loinc) || ']'::text
                                                                                                                                                                     )
                                                                                                                                                                     ,''::text
                                                                                                                                                               )
                                                                                                                                                         ) ||
                                                                                                                                               '): '::text
                                                                                                                                             ) || c_vtr.unified_val
                                                                                                                                       ) || ' '::text
                                                                                                                                 ) || COALESCE
                                                                                                                                 (c_vtr.val_unit
                                                                                                                                       ,''::text
                                                                                                                                 )
                                                                                                                           ) || ' '::text
                                                                                                                     ) || COALESCE
                                                                                                                     (
                                                                                                                           (
                                                                                                                                 (
                                                                                                                                     '('::text || c_vtr.abnormality_indicator) ||
                                                                                                                               ')'::text
                                                                                                                           )
                                                                                                                           ,''::text
                                                                                                                     )
                                                                                                               ) || '
    '::text
                                                                                                         ) || _
                                                                                                         ('Range: '::text)
                                                                                                   ) || COALESCE
                                                                                                   (
                                                                                                         (c_vtr.unified_target_min)::text
                                                                                                         ,''::text
                                                                                                   )
                                                                                             ) || ' - '::text
                                                                                       ) || COALESCE
                                                                                       (
                                                                                             (c_vtr.unified_target_max)::text
                                                                                             ,''::text
                                                                                       )
                                                                                 ) || ' / '::text
                                                                           ) || COALESCE
                                                                           (c_vtr.unified_target_range
                                                                                 ,''::text
                                                                           )
                                                                     ) || COALESCE
                                                                     (
                                                                           (
                                                                                 (
                                                                                    ' ('::text || c_vtr.norm_ref_group) ||
                                                                               ')'::text
                                                                           )
                                                                           ,''::text
                                                                     )
                                                               ) || '
    '::text
                                                         ) || COALESCE
                                                         (
                                                               (
                                                                     (_
                                                                           ('Assessment: '::text) || c_vtr.comment
                                                                     ) || '
    '::text
                                                               )
                                                               ,''::text
                                                         )
                                                   ) || COALESCE
                                                   (
                                                         (
                                                               (_
                                                                     ('Context: '::text) || c_vtr.note_test_org
                                                               ) || '
    '::text
                                                         )
                                                         ,''::text
                                                   )
                                             ) || COALESCE
                                             (
                                                   (
                                                         (_
                                                               ('Status: '::text) || c_vtr.status
                                                         ) || '
    '::text
                                                   )
                                                   ,''::text
                                             )
                                       ) || COALESCE
                                       (
                                             (
                                                   (_
                                                         ('Grouping: '::text) || c_vtr.val_grouping
                                                   ) || '
    '::text
                                             )
                                             ,''::text
                                       )
                                 ) || COALESCE
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (_
                                                                                 ('Review by '::text) || c_vtr.last_reviewer
                                                                           ) || ' @ '::text
                                                                     ) || to_char
                                                                     (c_vtr.last_reviewed
                                                                           ,'YYYY-MM-DD HH24:MI'::text
                                                                     )
                                                               ) || ': '::text
                                                         ) ||
            CASE
                WHEN c_vtr.is_technically_abnormal THEN
                                                         (_
                                                               ('abnormal'::text) ||
                                                            ', '::text
                                                         )
                ELSE ''::text
            END
                                                   ) ||
            CASE
                WHEN c_vtr.is_clinically_relevant THEN
                                                   (_
                                                         ('relevant'::text) || ' '::text
                                                   )
                ELSE ''::text
            END
                                             ) || COALESCE
                                             (
                                                   (
                                                         (
                                                             '('::text || c_vtr.review_comment) ||
                                                      ')
    '::text
                                                   )
                                                   ,'
    '::text
                                             )
                                       )
                                       ,''::text
                                 )
                           ) || _
                           ('Responsible clinician: '::text)
                     ) || c_vtr.responsible_reviewer
               ) || COALESCE
               (
                     (
                           (
                                 (_
                                       ('Source data:'::text) || '
    '::text
                                 ) || c_vtr.source_data
                           ) || '
    '::text
                     )
                     ,''::text
               )
         )
         ,'faulty clin.v_test_results_journal definition'::text
    ) AS narrative
    ,
        c_vtr.pk_encounter
    ,
        c_vtr.pk_episode
    ,
        c_vtr.pk_health_issue
    ,
        c_vtr.pk_test_result AS src_pk
    ,
        'clin.test_result'::text AS src_table
    ,
        c_vtr.row_version
    ,
        c_vtr.health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_vtr.episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (clin.v_test_results c_vtr

                        JOIN clin.encounter c_enc
                          ON (
                                 (c_vtr.pk_encounter = c_enc.pk)
                           )
                     )

                  JOIN clin.encounter_type c_ety
                    ON (
                           (c_enc.fk_type = c_ety.pk)
                     )
               )

            JOIN clin.episode c_epi
              ON (
                     (c_vtr.pk_episode = c_epi.pk)
               )
         )

    LEFT JOIN clin.health_issue c_hi
        ON (
               (c_epi.fk_health_issue = c_hi.pk)
         )
    );

Index - Schema clin

## View: clin.v_test_types

denormalizes test types with test orgs and meta types

clin.v_test_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_tt.pk AS pk_test_type
    ,
        c_tt.abbrev
    ,
        c_tt.name
    ,
        c_tt.loinc
    ,
        c_tt.reference_unit
    ,
        c_tt.comment AS comment_type
    ,
        d_ou.description AS name_org
    ,
        c_to.comment AS comment_org
    ,
        c_to.contact AS contact_org
    ,
        COALESCE
    (c_mtt.abbrev
         , c_tt.abbrev
    ) AS unified_abbrev
    ,
        COALESCE
    (c_mtt.name
         , c_tt.name
    ) AS unified_name
    ,
        COALESCE
    (c_mtt.loinc
         , c_tt.loinc
    ) AS unified_loinc
    ,

    (c_tt.fk_meta_test_type IS NULL) AS is_fake_meta_type
    ,
        c_mtt.abbrev AS abbrev_meta
    ,
        c_mtt.name AS name_meta
    ,
        c_mtt.loinc AS loinc_meta
    ,
        c_mtt.comment AS comment_meta
    ,

    (
    SELECT array_agg
         (c_vtt4tp.pk_test_panel) AS array_agg

      FROM clin.v_test_types4test_panel c_vtt4tp

     WHERE (c_vtt4tp.pk_test_type = c_tt.pk)
    ) AS pk_test_panels
    ,
        c_tt.fk_test_org AS pk_test_org
    ,
        c_tt.fk_meta_test_type AS pk_meta_test_type
    ,
        c_to.fk_org_unit AS pk_org_unit
    ,
        c_to.fk_adm_contact AS pk_adm_contact_org
    ,
        c_to.fk_med_contact AS pk_med_contact_org
    ,
        c_tt.xmin AS xmin_test_type

    FROM (
         (
               (clin.test_type c_tt

             LEFT JOIN clin.test_org c_to
                    ON (
                           (c_to.pk = c_tt.fk_test_org)
                     )
               )

       LEFT JOIN dem.org_unit d_ou
              ON (
                     (c_to.fk_org_unit = d_ou.pk)
               )
         )

    LEFT JOIN clin.meta_test_type c_mtt
        ON (
               (c_tt.fk_meta_test_type = c_mtt.pk)
         )
    );

Index - Schema clin

## View: clin.v_test_types4test_panel

Shows test types linked to test panels via their LOINC code.

clin.v_test_types4test_panel Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_tp.pk AS pk_test_panel
    ,
        c_tt.pk AS pk_test_type
    ,
        c_tp.description AS test_panel
    ,
        c_tt.name AS test_type
    ,
        c_tt.abbrev AS test_abbrev
    ,
        c_tt.loinc
    ,
        c_tp.comment AS comment_panel
    ,
        c_tt.comment AS comment_test_type
    ,
        c_tt.reference_unit
    ,
        c_tt.fk_meta_test_type AS pk_meta_test_type
    ,
        c_ll2tp.pk AS pk_lnk_loinc2test_panel

    FROM (
         (clin.test_panel c_tp

            JOIN clin.lnk_loinc2test_panel c_ll2tp
              ON (
                     (c_ll2tp.fk_test_panel = c_tp.pk)
               )
         )

      JOIN clin.test_type c_tt
        ON (
               (c_tt.loinc = c_ll2tp.loinc)
         )
    );

Index - Schema clin

## View: clin.v_vaccination_courses_in_schedule

clin.v_vaccination_courses_in_schedule Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT cvs.name AS vaccination_schedule
    ,
        cvc.is_active
    ,
        cvc.fk_recommended_by AS pk_recommended_by
    ,
        cvc.comment AS comment_course
    ,
        cvs.comment AS comment_schedule
    ,
        cvc.pk AS pk_vaccination_course
    ,
        cvc.fk_indication AS pk_indication
    ,
        cvs.pk AS pk_vaccination_schedule

    FROM clin.vaccination_course cvc
    ,
        clin.vaccination_schedule cvs
    ,
        clin.lnk_vaccination_course2schedule clvc2s

    WHERE (
         (clvc2s.fk_course = cvc.pk)
       AND (clvc2s.fk_schedule = cvs.pk)
    );

Index - Schema clin

## View: clin.v_vaccinations

Lists vaccinations for patients

clin.v_vaccinations Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_shot.pk AS pk_vaccination
    ,
        c_shot.clin_when AS date_given
    ,

    (now
         () - c_shot.clin_when
    ) AS interval_since_given
    ,
        r_dp.description AS vaccine
    ,
        ARRAY
    (
    SELECT row_to_json
         (indication_row.*) AS row_to_json

      FROM (
          SELECT _
               (
                     (r_s.atc || '-target'::text)
                     ,'en'::text
               ) AS indication
               ,
                            CASE
                                WHEN
               (_
                     (
                           (r_s.atc || '-target'::text)
                     ) =
                     (r_s.atc || '-target'::text)
               ) THEN _
               (
                     (r_s.atc || '-target'::text)
                     ,'en'::text
               )
                                ELSE _
               (
                     (r_s.atc || '-target'::text)
               )
                            END AS l10n_indication
               ,
                        r_s.atc AS atc_indication

            FROM (
                     (ref.lnk_dose2drug r_ld2d

                        JOIN ref.dose r_d
                          ON (
                                 (r_d.pk = r_ld2d.fk_dose)
                           )
                     )

                  JOIN ref.substance r_s
                    ON (
                           (r_d.fk_substance = r_s.pk)
                     )
               )

           WHERE (r_ld2d.fk_drug_product = r_dp.pk)
         ) indication_row
    ) AS indications
    ,
        c_shot.site
    ,
        c_shot.batch_no
    ,
        c_shot.reaction
    ,
        c_shot.narrative AS comment
    ,
        c_shot.soap_cat
    ,
        c_shot.modified_when
    ,
        c_shot.modified_by
    ,
        c_shot.row_version
    ,
        c_shot.fk_vaccine AS pk_vaccine
    ,
        c_shot.fk_provider AS pk_provider
    ,
        c_shot.fk_encounter AS pk_encounter
    ,
        c_shot.fk_episode AS pk_episode
    ,
        c_shot.xmin AS xmin_vaccination

    FROM (
         (
               (clin.vaccination c_shot

                  JOIN clin.encounter c_enc
                    ON (
                           (c_enc.pk = c_shot.fk_encounter)
                     )
               )

            JOIN ref.vaccine r_v
              ON (
                     (r_v.pk = c_shot.fk_vaccine)
               )
         )

      JOIN ref.drug_product r_dp
        ON (
               (r_v.fk_drug_product = r_dp.pk)
         )
    );

Index - Schema clin

## View: clin.v_vaccinations_journal

Vaccination data denormalized for the EMR journal.

clin.v_vaccinations_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_enc.fk_patient AS pk_patient
    ,
        c_vacc.modified_when
    ,
        c_vacc.clin_when
    ,
        COALESCE
    (
         (
          SELECT staff.short_alias

            FROM dem.staff

           WHERE (staff.db_user = c_vacc.modified_by)
         )
         , (
               ('<'::text ||
                     (c_vacc.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        c_vacc.soap_cat
    ,

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (_
                                                               ('Vaccination'::text) || ': '::text
                                                         ) || r_dp.description
                                                   ) || ' '::text
                                             ) || '['::text
                                       ) || c_vacc.batch_no
                                 ) || ']'::text
                           ) || COALESCE
                           (
                                 (
                                       (
                                          ' ('::text || c_vacc.site) ||
                                     ')'::text
                                 )
                                 ,''::text
                           )
                     ) || COALESCE
                     (
                           (
                                 (
                                       ('
    '::text || _
                                             ('Reaction'::text)
                                       ) || ': '::text
                                 ) || c_vacc.reaction
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           (
                                 ('
    '::text || _
                                       ('Comment'::text)
                                 ) || ': '::text
                           ) || c_vacc.narrative
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (
                           ('
    '::text || _
                                 ('Indications'::text)
                           ) || ': '::text
                     ) || array_to_string
                     (
                           (
                            SELECT array_agg
                                 (_
                                       (
                                             (r_s.atc || '-target'::text)
                                       )
                                 ) AS array_agg

                              FROM (
                                       (ref.lnk_dose2drug r_ld2d

                                          JOIN ref.dose r_d
                                            ON (
                                                   (r_d.pk = r_ld2d.fk_dose)
                                             )
                                       )

                                    JOIN ref.substance r_s
                                      ON (
                                             (r_d.fk_substance = r_s.pk)
                                       )
                                 )

                             WHERE (r_ld2d.fk_drug_product = r_dp.pk)
                           )
                           ,' / '::text
                     )
               )
               ,''::text
         )
    ) AS narrative
    ,
        c_vacc.fk_encounter AS pk_encounter
    ,
        c_vacc.fk_episode AS pk_episode
    ,

    (
    SELECT episode.fk_health_issue

      FROM clin.episode

     WHERE (episode.pk = c_vacc.fk_episode)
    ) AS pk_health_issue
    ,
        c_vacc.pk AS src_pk
    ,
        'clin.vaccination'::text AS src_table
    ,
        c_vacc.row_version
    ,
        c_hi.description AS health_issue
    ,
        c_hi.laterality AS issue_laterality
    ,
        c_hi.is_active AS issue_active
    ,
        c_hi.clinically_relevant AS issue_clinically_relevant
    ,
        c_hi.is_confidential AS issue_confidential
    ,
        c_epi.description AS episode
    ,
        c_epi.is_open AS episode_open
    ,
        c_enc.started AS encounter_started
    ,
        c_enc.last_affirmed AS encounter_last_affirmed
    ,
        c_ety.description AS encounter_type
    ,
        _
    (c_ety.description) AS encounter_l10n_type

    FROM (
         (
               (
                     (
                           (
                                 (clin.vaccination c_vacc

                                    JOIN clin.encounter c_enc
                                      ON (
                                             (c_enc.pk = c_vacc.fk_encounter)
                                       )
                                 )

                              JOIN clin.encounter_type c_ety
                                ON (
                                       (c_enc.fk_type = c_ety.pk)
                                 )
                           )

                        JOIN clin.episode c_epi
                          ON (
                                 (c_vacc.fk_episode = c_epi.pk)
                           )
                     )

             LEFT JOIN clin.health_issue c_hi
                    ON (
                           (c_epi.fk_health_issue = c_hi.pk)
                     )
               )

            JOIN ref.vaccine r_vcine
              ON (
                     (r_vcine.pk = c_vacc.fk_vaccine)
               )
         )

      JOIN ref.drug_product r_dp
        ON (
               (r_vcine.fk_drug_product = r_dp.pk)
         )
    );

Index - Schema clin

## View: clin.v_waiting_list

clin.v_waiting_list Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT c_wl.list_position
    ,
        c_wl.area AS waiting_zone
    ,
        c_wl.urgency
    ,
        d_i.title
    ,
        d_n.firstnames
    ,
        d_n.lastnames
    ,
        d_n.preferred AS preferred_name
    ,
        d_i.dob
    ,
        d_i.gender
    ,
        _
    (d_i.gender) AS l10n_gender
    ,
        d_i.comment AS comment_identity
    ,
        c_wl.registered
    ,

    (
    SELECT (now
               () - c_wl.registered
         )
    ) AS waiting_time
    ,

    (
    SELECT to_char
         (age
               (now
                     ()
                     , c_wl.registered
               )
               ,'DDD HH24:MI'::text
         ) AS to_char
    ) AS waiting_time_formatted
    ,
        c_wl.comment
    ,
        d_i.pk AS pk_identity
    ,
        d_n.id AS pk_name
    ,
        c_wl.pk AS pk_waiting_list

    FROM clin.waiting_list c_wl
    ,
        dem.identity d_i
    ,
        dem.names d_n

    WHERE (
         (c_wl.fk_patient = d_i.pk)
       AND (c_wl.fk_patient = d_n.id_identity)
       AND (d_i.deceased IS NULL)
       AND (d_n.active IS TRUE)
    );

Index - Schema clin

## Table: clin.vaccination

holds vaccinations actually given

clin.vaccination Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.encounter.pk | fk_encounter |  |
dem.staff.pk | fk_provider |  |
| pk |  | PRIMARY KEY
clin.episode.pk | fk_episode |  |
ref.vaccine.pk | fk_vaccine |  |

Table clin.vaccination Inherits clin_root_item,

clin.vaccination Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
clin_root_item_sane_soap_cat | CHECK (((soap_cat IS NULL) OR (soap_cat = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text, 'u'::text]))))
vaccination_sane_narrative | CHECK ((gm.is_null_or_non_empty_string(narrative) IS TRUE))
vaccination_sane_reaction | CHECK ((gm.is_null_or_non_empty_string(reaction) IS TRUE))
vaccination_sane_site | CHECK ((gm.is_null_or_non_empty_string(site) IS TRUE))

idx_clin_vaccination_clin_when clin_when idx_clin_vaccination_fk_encounter fk_encounter idx_clin_vaccination_fk_episode fk_episode idx_clin_vaccination_fk_provider fk_provider idx_clin_vaccination_fk_vaccine fk_vaccine

Index - Schema clin

## Table: clin.vaccination_course

holds vaccination courses defined at a techno-medical level for a single indication and will in many cases represent a part of a "recommended multi-epitope schedule", note that one organization can indeed recommend several courses for one and the same indication - which then only differ in their constraints, PostgreSQL does not currently offer the best tools to enforce such constraints

clin.vaccination_course Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

Table clin.vaccination_course Inherits audit_fields,

clin.vaccination_course Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_constraint2vacc_course

- clin.lnk_pat2vaccination_course

- clin.lnk_vaccination_course2schedule

- clin.vaccination_definition

Index - Schema clin

## Table: clin.vaccination_course_constraint

holds constraints which apply to a vaccination course

clin.vaccination_course_constraint Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| description |  | UNIQUE
| pk |  | PRIMARY KEY

Table clin.vaccination_course_constraint Inherits audit_fields,

clin.vaccination_course_constraint Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_constraint2vacc_course

Index - Schema clin

## Table: clin.vaccination_definition

defines a given vaccination event for a particular course

clin.vaccination_definition Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.vaccination_course.pk | fk_course |  | UNIQUE#1
| seq_no |  | UNIQUE#1
| id |  | PRIMARY KEY

Table clin.vaccination_definition Inherits audit_fields,

clin.vaccination_definition Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
numbered_shot_xor_booster | CHECK ((((is_booster IS TRUE) AND (seq_no IS NULL)) OR ((is_booster IS FALSE) AND (seq_no > 0))))
sensible_min_interval | CHECK ((((min_interval IS NULL) AND (seq_no = 1)) OR ((min_interval IS NOT NULL) AND (min_interval > '00:00:00'::interval) AND (is_booster IS TRUE)) OR ((min_interval IS NOT NULL) AND (min_interval > '00:00:00'::interval) AND (seq_no > 1))))
vaccination_definition_check | CHECK ((((max_age_due >= min_age_due) AND (max_age_due <= '150 years'::interval)) OR (max_age_due = '01:32:35'::interval)))
vaccination_definition_min_age_due_check | CHECK (((min_age_due >= '00:00:01'::interval) AND (min_age_due <= '150 years'::interval)))

Index - Schema clin

## Table: clin.vaccination_schedule

This table holds schedules as recommended by some authority such as a Vaccination Council. There will be numerous schedules depending on locale, constraints, age group etc. These schedules may be single or multi-epitope depending on their definition. A schedule acts as a convenient handle aggregating possibly several vaccination courses under a common name.

clin.vaccination_schedule Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| name |  | UNIQUE
| pk |  | PRIMARY KEY

Table clin.vaccination_schedule Inherits audit_fields,

clin.vaccination_schedule Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_vaccination_course2schedule

Index - Schema clin

## Table: clin.waiting_list

aggregates all the patients currently waiting for an encounter

clin.waiting_list Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| list_position |  | UNIQUE
dem.identity.pk | fk_patient |  |
| pk |  | PRIMARY KEY

Table clin.waiting_list Inherits audit_fields,

clin.waiting_list Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
non_empty_area | CHECK ((btrim(area) <> ''::text))
waiting_list_list_position_check | CHECK ((list_position > 0))

Index - Schema clin

## Function: clin._get_recommendation_for_patient_hint(text, integer)

### Returns: text

### Language: PLPGSQL

    DECLARE
    	_raw_query ALIAS FOR $1;
    	_pk_identity ALIAS FOR $2;
    	_query text;
    	_recommendation text;
    BEGIN
    	IF _raw_query IS NULL THEN
    		RETURN NULL::text;
    	END IF;
    	_query := replace(_raw_query, 'ID_ACTIVE_PATIENT', _pk_identity::text);
    	BEGIN
    		EXECUTE _query INTO STRICT _recommendation;
    	EXCEPTION
    		--WHEN insufficient_privilege THEN RAISE WARNING 'auto hint recommendation query failed: %', _query;
    		WHEN others THEN
    			RAISE WARNING 'auto hint recommendation query failed: %', _query;
    			-- only available starting with PG 9.2:
    			--GET STACKED DIAGNOSTICS
    			--	_exc_state = RETURNED_SQLSTATE,
    			--	_exc_msg = MESSAGE_TEXT,
    			--	_exc_detail = PG_EXCEPTION_DETAIL,
    			--	_exc_hint = PG_EXCEPTION_HINT,
    			--	_exc_context = PG_EXCEPTION_CONTEXT;
    			--RAISE WARNING 'SQL STATE: %', _exc_state;
    			--RAISE WARNING 'MESSAGE: %', _exc_msg;
    			--RAISE WARNING 'DETAIL: %', _exc_detail;
    			--RAISE WARNING 'HINT: %', _exc_hint;
    			--RAISE WARNING 'CONTEXT: %', _exc_context;
    			-- workaround for 9.1:
    			RAISE WARNING 'SQL STATE: %', SQLSTATE;
    			RAISE WARNING 'MESSAGE: %', SQLERRM;
    			_recommendation := 'ERROR running hint recommendation query [' || _query || ']';
    	END;
    	RETURN _recommendation;
    END;

## Function: clin.add_coded_phrase(text, text, text)

### Returns: boolean

### Language: PLPGSQL

    declare
    	_term alias for $1;
    	_code alias for $2;
    	_system alias for $3;
    	_tmp text;
    begin
    	select into _tmp 1 from clin.coded_phrase where
    		term = _term
    		and code = _code
    		and xfk_coding_system = _system;
    	if found then
    		return True;
    	end if;
    	insert into clin.coded_phrase (term, code, xfk_coding_system)
    		values (_term, _code, _system);
    	return True;
    end;

## Function: clin.f_del_booster_must_have_base_immunity()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	msg text;
    BEGIN
    	-- do not worry about booster deletes
    	if OLD.is_booster then
    		return null;
    	end if;
    	-- any non-booster rows left ?
    	perform 1 from clin.vaccination_definition where fk_course = OLD.fk_course and seq_no is not null;
    	if FOUND then
    		return null;
    	end if;
    	-- *any* rows left ?
    	perform 1 from clin.vaccination_definition where fk_course = OLD.fk_course;
    	if not FOUND then
    		-- no problem
    		return null;
    	end if;
    	-- any remaining rows can only be booster rows - which is a problem
    	msg := 'Cannot delete last non-booster vacc def [' || OLD.pk || '] from course [' || OLD.fk_course || ']. There would be only booster definitions left.';
    	raise exception '%', msg;
    	return null;
    END;

## Function: clin.f_fk_reviewer_default()

### Returns: integer

### Language: PLPGSQL

    declare
    	_pk_staff integer;
    begin
    	select pk into _pk_staff from dem.staff where db_user = current_user;
    	return _pk_staff;
    end;

## Function: clin.f_ins_booster_must_have_base_immunity()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	-- do not worry about non-booster inserts
    	if NEW.is_booster is false then
    		return NEW;
    	end if;
    	-- only insert booster def if non-booster def exists
    	perform 1 from clin.vaccination_definition where fk_course = NEW.fk_course and seq_no is not null;
    	if FOUND then
    		return NEW;
    	end if;
    	raise exception 'Cannot define booster shot for course [%]. There is no base immunization definition.', NEW.fk_course;
    	return null;
    END;

## Function: clin.f_protect_clin_root_item()

### Returns: boolean

### Language: PLPGSQL

protect from direct inserts/deletes which the inheritance system cannot handle properly

    begin
    	raise exception 'INSERT/DELETE on <clin_root_item> not allowed.';
    	return False;
    end;

## Function: clin.f_upd_booster_must_have_base_immunity()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	msg text;
    BEGIN
    	-- do not worry about non-booster updates
    	if NEW.is_booster is false then
    		return null;
    	end if;
    	-- after update to booster still non-booster def available ?
    	perform 1 from clin.vaccination_definition where fk_course = NEW.fk_course and seq_no is not null;
    	if FOUND then
    		return null;
    	end if;
    	msg := 'Cannot set vacc def [' || NEW.pk || '] to booster for course [' || NEW.fk_course || ']. There would be no base immunization definition left.';
    	raise exception '%', msg;
    	return null;
    END;

## Function: clin.get_dob(integer)

### Returns: timestamp with time zone

### Language: SQL

    		select date_trunc('day'::text, d_i.dob) + COALESCE(d_i.tob, d_i.dob::time without time zone)::interval AS dob
    		from dem.identity d_i
    		where d_i.pk = $1;

## Function: clin.get_dod(integer)

### Returns: timestamp with time zone

### Language: SQL

    select deceased from dem.identity d_i where d_i.pk = $1;

## Function: clin.get_hints_for_patient(_pk_identity integer)

### Returns: SET OF v_auto_hints

### Language: PLPGSQL

    DECLARE
    	_hint ref.v_auto_hints%rowtype;
    	_query text;
    	_suppression_exists boolean;		-- does not mean that the suppression applies
    	_md5_at_suppression text;
    	_old_rationale4suppression text;
    	_hint_currently_applies boolean;	-- regardless of whether suppressed or not
    	_hint_recommendation text;
    	_title text;
    --	_exc_state text;
    --	_exc_msg text;
    --	_exc_detail text;
    --	_exc_hint text;
    --	_exc_context text;
    BEGIN
    	-- loop over all defined hints
    	FOR _hint IN SELECT * FROM ref.v_auto_hints WHERE is_active LOOP
    		--raise NOTICE 'checking hint for patient %: %', _pk_identity, _hint.title;
    		-- is the hint suppressed ?
    		SELECT (clin.hint_suppression_exists(_pk_identity, _hint.pk_auto_hint)).*
    			INTO STRICT _suppression_exists, _md5_at_suppression, _old_rationale4suppression;
    		-- does the hint currently apply ? (regardless of whether it is suppressed)
    		_query := replace(_hint.query, 'ID_ACTIVE_PATIENT', _pk_identity::text);
    		_query := replace(_query, 'clin.v_emr_journal', 'clin._view_emr_journal_without_suppressed_hints');
    		SELECT (clin.run_hint_query(_hint.title, _query)).*
    			INTO STRICT _hint_currently_applies, _title;
    		-- error ?
    		IF _hint_currently_applies IS NULL THEN
    			--raise NOTICE ' error -> return';
    			_hint.title := _title;
    			_hint.hint := _query;
    			RETURN NEXT _hint;
    			-- process next hint
    			CONTINUE;
    		END IF;
    		-- hint does not apply
    		IF _hint_currently_applies IS FALSE THEN
    			-- does a (previously stored) suppression exist ?
    			IF _suppression_exists IS FALSE THEN
    				-- no, so skip this hint
    				--raise NOTICE ' does not apply -> skip';
    				CONTINUE;
    			END IF;
    			--raise NOTICE ' does not apply but suppression invalid -> return for invalidation';
    			-- hint suppressed but does NOT apply:
    			-- skip hint but invalidate suppression, because:
    			-- * previously the hint must have applied and the user suppressed it,
    			-- * then patient data (or hint definition) changed such that
    			--   the hint does not apply anymore (but the suppression is
    			--   still valid),
    			-- * when patient data changes again, the hint might apply again
    			-- * HOWEVER - since the suppression would still be valid - the
    			--   hint would magically get suppressed again (which is
    			--   medically unsafe) ...
    			-- after invalidation, the hint will no longer be suppressed,
    			-- however - since it does not currently apply - it will
    			-- still not be returned and shown until it applies again ...
    			--
    			-- -----------------------------------------------------------------------
    			-- UNFORTUNATELY, the following is currently not _possible_ because
    			-- we are running inside a READONLY transaction (due to inherent
    			-- security risks when running arbitrary user queries [IOW the hint
    			-- SQL] against the database) and we cannot execute a
    			-- sub-transaction as READWRITE :-/
    			--
    			--UPDATE clin.suppressed_hint
    			--SET md5_sum = 'invalidated'::text		-- will not ever match any md5 sum
    			--WHERE
    			--	fk_encounter IN (
    			--		SELECT pk FROM clin.encounter WHERE fk_patient = _pk_identity
    			--	)
    			--		AND
    			--	fk_hint = _hint.pk_auto_hint;
    			-- -----------------------------------------------------------------------
    			--
    			-- hence our our workaround is to, indeed, return the hint but
    			-- tag it with a magic rationale, by means of which the client
    			-- can detect it to be in need of invalidation:
    			_hint.title := 'HINT DOES NOT APPLY BUT NEEDS INVALIDATION OF EXISTING SUPPRESSION [' || _hint.title || '].';
    			_hint.rationale4suppression := 'magic_tag::does_not_apply::suppression_needs_invalidation';
    			RETURN NEXT _hint;
    			CONTINUE;
    		END IF;
    		--raise NOTICE ' applies';
    		-- but is there a suppression ?
    		IF _suppression_exists IS FALSE THEN
    			--raise NOTICE ' return';
    			-- no: retrieve recommendation
    			SELECT clin._get_recommendation_for_patient_hint(_hint.recommendation_query, _pk_identity) INTO STRICT _hint_recommendation;
    			_hint.recommendation := _hint_recommendation;
    			-- return hint
    			RETURN NEXT _hint;
    			CONTINUE;
    		END IF;
    		-- yes, is suppressed
    		--raise NOTICE ' is suppressed';
    		-- is the suppression still valid ?
    		-- -> yes, suppression valid
    		IF _md5_at_suppression = _hint.md5_sum THEN
    			--raise NOTICE '-> suppression valid, ignoring hint';
    			-- hint applies, suppressed, suppression valid: skip this hint
    			CONTINUE;
    		END IF;
    		-- -> no, suppression not valid
    		-- hint definition must have changed so ignore the suppression but
    		-- provide previous rationale for suppression to the user
    		_hint.rationale4suppression := _old_rationale4suppression;
    		-- retrieve recommendation
    		SELECT clin._get_recommendation_for_patient_hint(_hint.recommendation_query, _pk_identity) INTO STRICT _hint_recommendation;
    		_hint.recommendation := _hint_recommendation;
    		RETURN NEXT _hint;
    		CONTINUE;
    	END LOOP;
    	RETURN;
    END;

## Function: clin.hint_suppression_exists(_o_rationale integer, _o_md5 integer)

### Returns: record

### Language: PLPGSQL

    --DECLARE
    --	_md5_suppressed text;
    --	_old_rationale4suppression text;
    BEGIN
    	SELECT
    		md5_sum,
    		rationale
    			INTO
    		_o_md5,
    		_o_rationale
    	FROM clin.suppressed_hint WHERE
    		fk_hint = _pk_hint
    			AND
    		fk_encounter IN (
    			SELECT pk FROM clin.encounter WHERE fk_patient = _pk_identity
    		);
    	IF FOUND THEN
    		_o_exists := TRUE;
    	ELSE
    		_o_exists := FALSE;
    	END IF;
    END;

## Function: clin.move_waiting_list_entry(integer, integer)

### Returns: boolean

### Language: PLPGSQL

Move row with logical position $1 into logical position $2. If another row exists with position $2 it will be moved to position $1 in the process. Fails if there is no row with position $1.

    DECLARE
    	_wl_pos_src alias for $1;
    	_wl_pos_dest alias for $2;
    	_tmp_pos integer;
    	_curr_max_pos integer;
    BEGIN
    	if _wl_pos_src = _wl_pos_dest then
    		return true;
    	end if;
    	if _wl_pos_dest < 1 then
    		raise notice 'clin.move_waiting_list_entry(): Will not move entry [%] before start of list [%].', _wl_pos_src, _wl_pos_dest;
    		return False;
    	end if;
    	select max(list_position) into _curr_max_pos from clin.waiting_list;
    	-- do not move last entry further down
    	if _wl_pos_src = _curr_max_pos then
    		if _wl_pos_dest > _wl_pos_src then
    			raise notice 'clin.move_waiting_list_entry(): Will not move last entry [%] beyond end of list to [%].', _wl_pos_src, _wl_pos_dest;
    			return False;
    		end if;
    	end if;
    	-- does the source row exist ?
    	perform 1 from clin.waiting_list where list_position = _wl_pos_src;
    	if not found then
    		raise notice 'clin.move_waiting_list_entry(): Cannot move entry [%] to [%]. Entry does not exist.', _wl_pos_src, wl_pos_dest ;
    		return false;
    	end if;
    	-- load destination row
    	perform 1 from clin.waiting_list where list_position = _wl_pos_dest;
    	-- does not exist
    	if not found then
    		-- do not move entry beyond end of list more than necessary
    		if _wl_pos_dest > (_curr_max_pos + 1) then
    			_tmp_pos := _curr_max_pos + 1;
    		else
    			_tmp_pos := _wl_pos_dest;
    		end if;
    		-- so update row to move and be done with it
    		update clin.waiting_list
    			set list_position = _tmp_pos
    			where list_position = _wl_pos_src;
    		return true;
    	end if;
    	-- move existing row out of the way
    	select (max(list_position) + _wl_pos_dest + _wl_pos_src) into _tmp_pos from clin.waiting_list;
    	update clin.waiting_list
    		set list_position = _tmp_pos
    		where list_position = _wl_pos_dest;
    	-- move row to move
    	update clin.waiting_list
    		set list_position = _wl_pos_dest
    		where list_position = _wl_pos_src;
    	-- move back existing row
    	update clin.waiting_list
    		set list_position = _wl_pos_src
    		where list_position = _tmp_pos;
    	return true;
    END;

## Function: clin.remove_old_empty_encounters(integer)

### Returns: boolean

### Language: SQL

Remove empty encounters older than 1 week from a patient.

    select clin.remove_old_empty_encounters($1, '1 week'::interval);

## Function: clin.remove_old_empty_encounters(integer, interval)

### Returns: boolean

### Language: PLPGSQL

Remove empty encounters older than a definable minimum age from a patient.

    DECLARE
    	_pk_identity alias for $1;
    	_defined_minimum_encounter_age alias for $2;
    	_usable_minimum_encounter_age interval;
    	_no_of_encounters integer;
    BEGIN
    	-- does person exist ?
    	perform 1 from dem.identity where pk = _pk_identity;
    	if not found then
    		raise exception 'clin.remove_old_empty_encounters(person=%, min_age=%): person [%] does not exist', _pk_identity, _defined_minimum_encounter_age, _pk_identity;
    		return false;
    	end if;
    	SELECT count(1) INTO STRICT _no_of_encounters
    	FROM clin.encounter	WHERE fk_patient = _pk_identity;
    	IF _no_of_encounters < 2 THEN
    		raise notice 'clin.remove_old_empty_encounters(person=%, min_age=%): there are less than 2 encounters for this patient', _pk_identity, _defined_minimum_encounter_age;
    		return false;
    	END IF;
    	if _defined_minimum_encounter_age < '3 days'::interval then
    		_usable_minimum_encounter_age := '3 days'::interval;
    	else
    		_usable_minimum_encounter_age := _defined_minimum_encounter_age;
    	end if;
    	DELETE FROM clin.encounter WHERE
    		clin.encounter.fk_patient = _pk_identity
    			AND
    		-- is this the active encounter somewhere ?
    		(SELECT pg_try_advisory_lock('clin.encounter'::regclass::oid::int, clin.encounter.pk))
    			AND
    		age(clin.encounter.last_affirmed) > _usable_minimum_encounter_age
    			AND
    		NOT EXISTS (SELECT 1 FROM clin.clin_root_item WHERE fk_encounter = clin.encounter.pk)
    			AND
    		NOT EXISTS (SELECT 1 FROM blobs.doc_med WHERE fk_encounter = clin.encounter.pk)
    			AND
    		NOT EXISTS (SELECT 1 FROM clin.episode WHERE fk_encounter = clin.encounter.pk)
    			AND
    		NOT EXISTS (SELECT 1 FROM clin.health_issue WHERE fk_encounter = clin.encounter.pk)
    			AND
    		NOT EXISTS (SELECT 1 FROM clin.allergy_state WHERE fk_encounter = clin.encounter.pk)
    			AND
    		NOT EXISTS (SELECT 1 FROM bill.bill_item WHERE fk_encounter = clin.encounter.pk)
    			AND
    		NOT EXISTS (SELECT 1 FROM clin.external_care WHERE fk_encounter = clin.encounter.pk)
    			AND
    		NOT EXISTS (SELECT 1 FROM clin.suppressed_hint WHERE fk_encounter = clin.encounter.pk)
    	;
    	RETURN TRUE;
    END;

## Function: clin.run_hint_query(_o_title text, _o_applies text)

### Returns: record

### Language: PLPGSQL

    BEGIN
    	BEGIN
    		EXECUTE _query INTO STRICT _o_applies;
    	EXCEPTION
    		--WHEN insufficient_privilege THEN RAISE WARNING 'auto hint query failed: %', _query;
    		WHEN others THEN
    			RAISE WARNING 'auto hint query failed: %', _query;
    			-- only available starting with PG 9.2:
    			--GET STACKED DIAGNOSTICS
    			--	_exc_state = RETURNED_SQLSTATE,
    			--	_exc_msg = MESSAGE_TEXT,
    			--	_exc_detail = PG_EXCEPTION_DETAIL,
    			--	_exc_hint = PG_EXCEPTION_HINT,
    			--	_exc_context = PG_EXCEPTION_CONTEXT;
    			--RAISE WARNING 'SQL STATE: %', _exc_state;
    			--RAISE WARNING 'MESSAGE: %', _exc_msg;
    			--RAISE WARNING 'DETAIL: %', _exc_detail;
    			--RAISE WARNING 'HINT: %', _exc_hint;
    			--RAISE WARNING 'CONTEXT: %', _exc_context;
    			-- workaround for 9.1:
    			RAISE WARNING 'SQL STATE: %', SQLSTATE;
    			RAISE WARNING 'MESSAGE: %', SQLERRM;
    			_o_applies := NULL;
    			_o_title := ('ERROR checking for [' || _title || '] !')::TEXT;
    			RETURN;
    	END;
    	_o_title := _title;
    END;

## Function: clin.transfer_all_encounter_data(_pk_target_encounter integer, _pk_source_encounter integer)

### Returns: boolean

### Language: PLPGSQL

transfers all data linked to _pk_source_encounter into _pk_target_encounter

    DECLARE
    	_fk_row record;
    	_success boolean;
    BEGIN
    	-- same patient on both encounters ?
    	SELECT (
    		coalesce((select fk_patient from clin.encounter where pk = _pk_source_encounter), -1)
    			=
    		coalesce((select fk_patient from clin.encounter where pk = _pk_target_encounter), -2)
    	) INTO strict _success;
    	IF _success IS FALSE THEN
    		RAISE NOTICE 'source encounter (%) belongs to a patient different from target encounter (%), aborting', _pk_source_encounter, _pk_target_encounter;
    		RETURN FALSE;
    	END IF;
    	-- loop over foreign keys in non-clin.* tables
    	FOR _fk_row IN
    		SELECT
    			conrelid::pg_catalog.regclass
    				as referencing_table,
    			(select attname from pg_attribute where attnum = pg_c.conkey[1] and attrelid = pg_c.conrelid) as referencing_column
    		FROM
    			pg_catalog.pg_constraint pg_c
    		WHERE
    			pg_c.confrelid = 'clin.encounter'::pg_catalog.regclass
    				AND
    			pg_c.contype = 'f'
    				AND
    			position('clin.'::text in pg_c.conrelid::pg_catalog.regclass::text) = 0
    	LOOP
    		EXECUTE format (
    			'UPDATE %1$s SET %2$I = %3$L WHERE %2$I = %4$L',
    				_fk_row.referencing_table,
    				_fk_row.referencing_column,
    				_pk_target_encounter,
    				_pk_source_encounter
    		);
    	END LOOP;
    	-- update clin.clin_root_item children in one go
    	UPDATE clin.clin_root_item SET fk_encounter = _pk_target_encounter WHERE fk_encounter = _pk_source_encounter;
    	return TRUE;
    END;

## Function: clin.trf_activate_issue_on_opening_episode()

### Returns: trigger

### Language: PLPGSQL

    begin
    	if TG_OP = 'UPDATE' then
    		if OLD.is_open is TRUE then
    			return NEW;
    		end if;
    	end if;
    	update clin.health_issue
    	set is_active = TRUE
    	where
    		pk = NEW.fk_health_issue
    			AND
    		is_active is FALSE
    	;
    	return NEW;
    end;

## Function: clin.trf_announce_active_substance_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "active_substance_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_consumed_substance_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "consumed_substance_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_check_ext_care_uniq_issue_per_enc_and_unit_ins_upd()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_issue_count integer;
    BEGIN
    	SELECT COUNT(1) INTO STRICT _issue_count
    	FROM clin.external_care
    	WHERE
    		issue = NEW.issue
    			AND
    		fk_org_unit = NEW.fk_org_unit
    			AND
    		fk_encounter IN (
    			SELECT pk FROM clin.encounter WHERE fk_patient = (
    				SELECT fk_patient FROM clin.encounter WHERE pk = NEW.fk_encounter
    			)
    		)
    	;
    	IF _issue_count > 1 THEN
    		RAISE EXCEPTION '% into clin.external_care: Sanity check failed. Cannot insert issue [%] more than once for patient of encounter [%] at org unit [%].',
    			TG_OP,
    			NEW.issue,
    			NEW.fk_encounter,
    			NEW.fk_org_unit
    			USING ERRCODE = 'check_violation';
    		return NULL;
    	END IF;
    	RETURN NEW;
    END;

## Function: clin.trf_del_intake_document_deleted()

### Returns: trigger

### Language: PLPGSQL

Document the deletion of a substance intake.

    DECLARE
    	_row record;
    	_pk_episode integer;
    BEGIN
    	select
    		* into _row
    	from
    		clin.v_substance_intake_journal
    	where
    		src_pk = OLD.pk;
    	_pk_episode := _row.pk_episode;
    	-- create episode if needed
    	if _pk_episode is null then
    		select pk into _pk_episode
    		from clin.episode
    		where
    			description = _('Medication history')
    				and
    			fk_encounter in (
    				select pk from clin.encounter where fk_patient = _row.pk_patient
    			);
    		if not found then
    			insert into clin.episode (
    				description,
    				is_open,
    				fk_encounter
    			) values (
    				_('Medication history'),
    				FALSE,
    				OLD.fk_encounter
    			) returning pk into _pk_episode;
    		end if;
    	end if;
    	insert into clin.clin_narrative (
    		fk_encounter,
    		fk_episode,
    		soap_cat,
    		narrative
    	) values (
    		_row.pk_encounter,
    		_pk_episode,
    		NULL,
    		_('Deletion of') || ' ' || _row.narrative
    	);
    	return OLD;
    END;

## Function: clin.trf_del_intake_must_unlink_all_drug_components()

### Returns: trigger

### Language: PLPGSQL

If a multi-component drug intake is deleted from a patient ALL components thereof must be unlinked.

    DECLARE
    	_pk_drug_product integer;
    	_component_count integer;
    	_pk_patient integer;
    	_intake_count integer;
    	_msg text;
    BEGIN
    	-- which drug ?
    	select fk_drug_product into _pk_drug_product
    	from ref.lnk_dose2drug
    	where pk = OLD.fk_drug_component;
    	-- how many components therein ?
    	select count(1) into _component_count
    	from ref.lnk_dose2drug
    	where fk_drug_product = _pk_drug_product;
    	-- only one component anyways ?
    	if _component_count = 1 then
    		return NULL;
    	end if;
    	-- retrieve patient
    	select fk_patient into _pk_patient
    	from clin.encounter
    	where pk = OLD.fk_encounter;
    	-- how many intakes of this drug are linked to this patient
    	select count(1) into _intake_count
    	from clin.substance_intake
    	where
    		fk_drug_component in (
    			select pk from ref.lnk_dose2drug where fk_drug_product = _pk_drug_product
    		)
    			and
    		fk_encounter in (
    			select pk from clin.encounter where fk_patient = _pk_patient
    		);
    	-- intake count must be 0
    	if _intake_count = 0 then
    		return NULL;
    	end if;
    	_msg := '[clin.trf_del_intake_must_unlink_all_drug_components]: deleting a multi-component intake ['
    		|| OLD.pk || '] must unlink all components of the drug product ['
    		|| _pk_drug_product || '] '
    		|| '(unlinked component [' || OLD.fk_drug_component || '])';
    	raise exception check_violation using message = _msg;
    	return NULL;
    END;

## Function: clin.trf_ensure_one_allergy_state_per_patient()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_new_pk_patient integer;
    	_old_pk_patient integer;
    begin
    	-- find patient from encounter
    	select into _new_pk_patient fk_patient
    		from clin.encounter
    		where pk = NEW.fk_encounter;
    	if not FOUND then
    		raise exception 'Encounter % does not exist !?', NEW.fk_encounter;
    		return NEW;
    	end if;
    	-- new row
    	if TG_OP = 'INSERT' then
    		-- patient already there ?
    		perform 1 from clin.allergy_state
    		where
    			fk_encounter in (select pk from clin.encounter where fk_patient = _new_pk_patient);
    		if FOUND then
    			raise exception 'Cannot insert second allergy state for patient % via encounter %.', _new_pk_patient, NEW.fk_encounter;
    			return NEW;
    		end if;
    		return NEW;
    	end if;
    	if TG_OP = 'UPDATE' then
    		if NEW.fk_encounter = OLD.fk_encounter then
    			return NEW;
    		end if;
    		select into _old_pk_patient fk_patient
    			from clin.encounter
    			where pk = OLD.fk_encounter;
    		if _new_pk_patient = _old_pk_patient then
    			return NEW;
    		end if;
    		raise exception 'Invalid fk_encounter update (% -> %): it would change the associated patient (% -> %).', OLD.fk_encounter, NEW.fk_encounter, _old_pk_patient, _new_pk_patient;
    		return NEW;
    	end if;
    	return NEW;
    end;

## Function: clin.trf_ins_intake_prevent_duplicate_component_links()

### Returns: trigger

### Language: PLPGSQL

Prevent patient from being put on a particular component twice.

    DECLARE
    	_pk_patient integer;
    	_pk_intake integer;
    	_msg text;
    BEGIN
    	-- which patient ?
    	select fk_patient into _pk_patient
    	from clin.encounter
    	where pk = NEW.fk_encounter;
    	-- already exists ?
    	select pk into _pk_intake
    	from clin.substance_intake
    	where
    		fk_encounter in (
    			select pk from clin.encounter where fk_patient = _pk_patient
    		)
    			and
    		fk_drug_component = NEW.fk_drug_component
    	;
    	if FOUND then
    		_msg := '[clin.trf_ins_intake_prevent_duplicate_component_links]: drug component ref.lnk_dose2drug.pk=(' || NEW.fk_drug_component || ') '
    			|| 'already linked to patient=(' || _pk_patient || ') '
    			|| 'as clin.substance_intake.pk=(' || _pk_intake || ')';
    		raise exception unique_violation using message = _msg;
    	end if;
    	return NEW;
    END;

## Function: clin.trf_ins_lc2sth_fk_generic_code()

### Returns: trigger

### Language: PLPGSQL

Check foreign key integrity on insert to *.fk_generic_code -> ref.coding_system_root.pk_coding_system.

    DECLARE
    	_msg text;
    BEGIN
    	perform 1 from ref.coding_system_root where pk_coding_system = NEW.fk_generic_code;
    	if FOUND then
    		return NEW;
    	end if;
    	_msg := 'clin.trf_ins_lc2sth_fk_generic_code(): INSERT into '
    		|| TG_TABLE_SCHEMA || '.' || TG_TABLE_NAME || ': '
    		|| 'fk_generic_code=(' || NEW.fk_generic_code || ') '
    		|| 'does not exist in ref.coding_system_root.pk_coding_system';
    	raise foreign_key_violation using message = _msg;
    	return NEW;
    END;

## Function: clin.trf_ins_upd_export_item_normalize_fk_identity()

### Returns: trigger

### Language: PLPGSQL

Set .fk_identity from .fk_doc if .fk_doc is NOT NULL

    BEGIN
    	SELECT fk_patient INTO STRICT NEW.fk_identity
    	FROM clin.encounter
    	WHERE
    		pk = (
    			SELECT fk_encounter FROM blobs.doc_med WHERE pk = (
    				SELECT fk_doc FROM blobs.doc_obj WHERE pk = NEW.fk_doc_obj
    			)
    		)
    	;
    	RETURN NEW;
    END;

## Function: clin.trf_insert_intake_links_all_drug_components()

### Returns: trigger

### Language: PLPGSQL

If a patient is put on a multi-component drug they must be put on ALL components thereof.

    DECLARE
    	_component_count integer;
    	_pk_patient integer;
    	_pk_drug_product integer;
    	_pk_component integer;
    BEGIN
    	-- get the product we are linking to
    	select fk_drug_product into _pk_drug_product
    	from ref.lnk_dose2drug
    	where pk = NEW.fk_drug_component;
    	-- how many components therein ?
    	select count(1) into _component_count
    	from ref.lnk_dose2drug
    	where fk_drug_product = _pk_drug_product;
    	-- only one component ?
    	if _component_count = 1 then
    		return NEW;
    	end if;
    	-- which patient ?
    	select fk_patient into _pk_patient
    	from clin.encounter
    	where pk = NEW.fk_encounter;
    	-- INSERT all components
    	for _pk_component in
    		select pk from ref.lnk_dose2drug where fk_drug_product = _pk_drug_product
    	loop
    		-- already there ?
    		perform 1 from clin.substance_intake where
    			fk_encounter in (
    				select pk from clin.encounter where fk_patient = _pk_patient
    			)
    				and
    			fk_drug_component = _pk_component
    		;
    		if FOUND then
    			continue;
    		end if;
    		-- insert
    		insert into clin.substance_intake (
    			fk_drug_component,				-- differentiate
    			clin_when,						-- harmonize (started)
    			fk_encounter,					-- harmonize
    			fk_episode,						-- required
    			soap_cat,						-- harmonize
    			schedule,						-- harmonize
    			duration,						-- harmonize
    			intake_is_approved_of,			-- harmonize
    			is_long_term,					-- harmonize
    			discontinued,					-- harmonize
    			narrative,
    			aim,
    			discontinue_reason,
    			comment_on_start,
    			harmful_use_type
    		) values (
    			_pk_component,
    			NEW.clin_when,
    			NEW.fk_encounter,
    			NEW.fk_episode,
    			NEW.soap_cat,
    			NEW.schedule,
    			NEW.duration,
    			NEW.intake_is_approved_of,
    			NEW.is_long_term,
    			NEW.discontinued,
    			NEW.narrative,
    			NEW.aim,
    			NEW.discontinue_reason,
    			NEW.comment_on_start,
    			NEW.harmful_use_type
    		);
    	end loop;
    	return NEW;
    END;

## Function: clin.trf_invalidate_review_on_result_change()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	is_modified bool;
    BEGIN
    	is_modified := False;
    	-- change of test type
    	if NEW.fk_type != OLD.fk_type then
    		is_modified := True;
    	end if;
    	-- change of numeric value
    	if NEW.val_num != OLD.val_num then
    		is_modified := True;
    	end if;
    	-- change of alpha value
    	if NEW.val_alpha != OLD.val_alpha then
    		is_modified := True;
    	end if;
    	-- change of unit
    	if NEW.val_unit != OLD.val_unit then
    		is_modified := True;
    	end if;
    	if is_modified is True then
    		delete from clin.reviewed_test_results where fk_reviewed_row = OLD.pk;
    	end if;
    	return NEW;
    END;

## Function: clin.trf_normalize_proc_is_ongoing()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	if NEW.clin_end > clock_timestamp() then
    		NEW.is_ongoing := TRUE;
    	else
    		NEW.is_ongoing := FALSE;
    	end if;
    	return NEW;
    END;

## Function: clin.trf_notify_reviewer_of_review_change()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_patient integer;
    	_pk_type integer;
    begin
    	-- disallow change of referenced row
    	-- for cleanliness this really *should* be in another trigger
    	if NEW.fk_reviewed_row <> OLD.fk_reviewed_row then
    		raise exception 'Attaching an existing review to another test result is not allowed (fk_reviewed_row change).';
    		return NEW;
    	end if;
    	-- change of last reviewer ?
    	if NEW.fk_reviewer = OLD.fk_reviewer then
    		return NEW;
    	end if;
    	-- review change ?
    	if (NEW.is_technically_abnormal <> OLD.is_technically_abnormal) or
    	   (NEW.clinically_relevant <> OLD.clinically_relevant) then
    		-- find patient for test result
    		select pk_patient into _pk_patient
    			from clin.v_test_results
    			where pk_test_result = OLD.fk_reviewed_row;
    		-- find inbox item type
    		select pk_type into _pk_type
    			from dem.v_inbox_item_type where
    			type = 'results review change';
    		-- create it if necessary
    		if not found then
    			insert into dem.inbox_item_type (
    				fk_inbox_item_category,
    				description
    			) values (
    				(select pk from dem.inbox_item_category where description = 'clinical'),
    				'results review change'
    			);
    			select pk_type into _pk_type
    				from dem.v_inbox_item_type where
    				type = 'results review change';
    		end if;
    		-- already notified ?
    		perform 1 from dem.message_inbox where
    			fk_staff = OLD.fk_reviewer
    			and fk_inbox_item_type = _pk_type
    			and ufk_context = ARRAY[_pk_patient];
    		-- nope, so notify now
    		if not found then
    			insert into dem.message_inbox (
    				fk_staff, fk_inbox_item_type, comment, ufk_context
    			) values (
    				OLD.fk_reviewer,
    				_pk_type,
    				(select
    					_('results review changed for patient') || ' [' || vpb.lastnames || ', ' || vbp.firstnames || ']'
    					from dem.v_basic_person vbp
    					where vpb.pk_identity = _pk_patient
    				),
    				ARRAY[_pk_patient]
    			);
    		end if;
    	end if;
    	return NEW;
    end;

## Function: clin.trf_sanity_check_enc_epi_ins_upd()

### Returns: trigger

### Language: PLPGSQL

this function is used in triggers and checks whether foreign keys to clin.episode.pk and clin.encounter.pk on a single table ultimately point to the same patient

    declare
    	_fk_encounter_col text;
    	_enc_pk integer;
    	_fk_episode_col text;
    	_epi_pk integer;
    	_identity_from_encounter integer;
    	_identity_from_episode integer;
    	_cmd text;
    begin
    	_fk_encounter_col := TG_ARGV[0];
    	_fk_episode_col := TG_ARGV[1];
    	_cmd := 'select $1.' || _fk_encounter_col;
    	EXECUTE _cmd INTO STRICT _enc_pk USING NEW;
    	select fk_patient into _identity_from_encounter from clin.encounter where pk = _enc_pk;
    --	raise notice '%: % -> %', _cmd, _enc_pk, _identity_from_encounter;
    	_cmd := 'select $1.' || _fk_episode_col;
    	EXECUTE _cmd INTO STRICT _epi_pk USING NEW;
    	select fk_patient into _identity_from_episode from clin.encounter where pk = (select fk_encounter from clin.episode where pk = _epi_pk);
    --	raise notice '%: % -> %', _cmd, _epi_pk, _identity_from_episode;
    	if _identity_from_encounter <> _identity_from_episode then
    		raise exception '% into %.%: Sanity check failed. %=% -> patient=%. %=% -> patient=%.',
    			TG_OP,
    			TG_TABLE_SCHEMA,
    			TG_TABLE_NAME,
    			_fk_encounter_col,
    			_enc_pk,
    			_identity_from_encounter,
    			_fk_episode_col,
    			_epi_pk,
    			_identity_from_episode
    		;
    		return NULL;
    	end if;
    	return NEW;
    end;

## Function: clin.trf_sanity_check_enc_issue_ins_upd()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_enc_pk integer;
    	_epi_pk integer;
    	_identity_from_encounter integer;
    	_identity_from_issue integer;
    	_cmd text;
    begin
    	select fk_patient into _identity_from_encounter from clin.encounter where pk = NEW.fk_encounter;
    --	raise notice '%: % -> %', _cmd, _enc_pk, _identity_from_encounter;
    	select fk_patient into _identity_from_issue
    	from clin.encounter where pk = (
    		select fk_encounter from clin.health_issue where pk = NEW.fk_health_issue
    	);
    	IF _identity_from_encounter <> _identity_from_issue THEN
    		RAISE EXCEPTION '% into clin.external_care: Sanity check failed. fk_encounter=% -> patient=%. fk_health_issue=% -> patient=%.',
    			TG_OP,
    			NEW.fk_encounter,
    			_identity_from_encounter,
    			NEW.fk_health_issue,
    			_identity_from_issue
    			USING ERRCODE = 'check_violation'
    		;
    		return NULL;
    	END IF;
    	return NEW;
    end;

## Function: clin.trf_sanity_check_enc_vs_issue_on_epi()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_identity_from_encounter integer;
    	_identity_from_issue integer;
    begin
    	-- if issue is NULL, do not worry about mismatch
    	if NEW.fk_health_issue is NULL then
    		return NEW;
    	end if;
    	-- .fk_episode must belong to the same patient as .fk_encounter
    	select fk_patient into _identity_from_encounter from clin.encounter where pk = NEW.fk_encounter;
    	select fk_patient into _identity_from_issue     from clin.encounter where pk = (
    		select fk_encounter from clin.health_issue where pk = NEW.fk_health_issue
    	);
    	if _identity_from_encounter <> _identity_from_issue then
    		raise exception 'INSERT/UPDATE into %.%: Sanity check failed. Encounter % patient = %. Issue % patient = %.',
    			TG_TABLE_SCHEMA,
    			TG_TABLE_NAME,
    			NEW.fk_encounter,
    			_identity_from_encounter,
    			NEW.fk_health_issue,
    			_identity_from_issue
    		;
    		return NULL;
    	end if;
    	return NEW;
    end;

## Function: clin.trf_sanity_check_procedure_episode()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_hospital_stay_episode_pk integer;
    BEGIN
    	if NEW.fk_hospital_stay is null then
    		return NEW;
    	end if;
    	select into _hospital_stay_episode_pk fk_episode
    		from clin.hospital_stay
    		where pk = NEW.fk_hospital_stay;
    	if NEW.fk_episode = _hospital_stay_episode_pk then
    		return NEW;
    	end if;
    	raise exception '[clin.procedure]: INSERT/UPDATE failed: fk_episode (%) does not match fk_episode (%) behind fk_hospital_stay (%)', NEW.fk_episode, _hospital_stay_episode_pk, NEW.fk_hospital_stay;
    	return NEW;
    END;

## Function: clin.trf_sanity_check_uniq_hint_per_pat_ins_upd()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_suppression_count integer;
    BEGIN
    	-- the count of suppressions for this hint in this patient
    	SELECT COUNT(1) INTO STRICT _suppression_count
    	FROM clin.suppressed_hint
    	WHERE
    		fk_hint = NEW.fk_hint
    			AND
    		fk_encounter IN (
    			SELECT pk FROM clin.encounter WHERE fk_patient = (
    				SELECT fk_patient FROM clin.encounter WHERE pk = NEW.fk_encounter
    			)
    		)
    	;
    	IF _suppression_count > 1 THEN
    		RAISE EXCEPTION '% into clin.suppressed_hint: Sanity check failed. Hint [%] suppressed more than once for patient of encounter [%].',
    			TG_OP,
    			NEW.pk,
    			NEW.fk_encounter
    			USING ERRCODE = 'check_violation';
    		return NULL;
    	END IF;
    	return NEW;
    END;

## Function: clin.trf_sync_allergic_state_on_allergies_modified()

### Returns: trigger

### Language: PLPGSQL

trigger function to sync the allergy state on insert/delete

    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;

## Function: clin.trf_undiscontinue_unsets_reason()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_identity_from_encounter integer;
    	_identity_from_issue integer;
    begin
    	if NEW.discontinued is NULL then
    		NEW.discontinue_reason := NULL;
    	end if;
    	return NEW;
    end;

## Function: clin.trf_unique_indication_in_schedule()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_msg text;
    BEGIN
    	-- is the indication already linked ?
    	perform 1 from clin.v_vaccination_courses_in_schedule where
    		pk_vaccination_schedule = NEW.fk_schedule and
    		pk_indication = (select fk_indication from clin.vaccination_course where pk=NEW.fk_course);
    	if FOUND then
    		_msg := 'Cannot link course [' || NEW.fk_course || '] into schedule [' || NEW.fk_schedule || ']. The indication is already linked.';
    		raise exception '%', _msg;
    		return null;
    	end if;
    	return null;
    END;

## Function: clin.trf_upd_intake_must_link_all_drug_components()

### Returns: trigger

### Language: PLPGSQL

If a patient is put on a different multi-component drug ALL components thereof must be updated.

    DECLARE
    	_intake_count integer;
    	_component_count integer;
    	_pk_patient integer;
    	_pk_drug_product integer;
    	_msg text;
    BEGIN
    	select fk_patient into _pk_patient
    	from clin.encounter
    	where pk = NEW.fk_encounter;
    	-- get the drug product we were linking to
    	select fk_drug_product into _pk_drug_product
    	from ref.lnk_dose2drug
    	where pk = OLD.fk_drug_component;
    	-- How many substance intake links for this drug have we got ?
    	select count(1) into _intake_count
    	from clin.substance_intake
    	where
    		fk_drug_component in (
    			select pk from ref.lnk_dose2drug where fk_drug_product = _pk_drug_product
    		)
    			and
    		fk_encounter in (
    			select pk from clin.encounter where fk_patient = _pk_patient
    		);
    	-- unlinking completely would be fine but else:
    	if _intake_count != 0 then
    		-- How many components *are* there in the drug in question ?
    		select count(1) into _component_count
    		from ref.lnk_dose2drug
    		where fk_drug_product = _pk_drug_product;
    		-- substance intake link count and number of components must match
    		if _component_count != _intake_count then
    			_msg := '[clin.trf_upd_intake_must_link_all_drug_components]: re-linking drug product must unlink all components of old drug product [' || _pk_drug_product || '] '
    				|| '(component [' || OLD.fk_drug_component || ' -> ' || NEW.fk_drug_component || '])';
    			raise exception check_violation using message = _msg;
    		end if;
    	end if;
    	-- check the NEW drug product
    	-- get the drug product we are linking to
    	select fk_drug_product into _pk_drug_product
    	from ref.lnk_dose2drug
    	where fk_substance = NEW.fk_drug_component;
    	-- How many substance intake links for this drug have we got ?
    	select count(1) into _intake_count
    	from clin.substance_intake
    	where
    		fk_drug_component in (
    			select pk from ref.lnk_dose2drug where fk_drug_product = _pk_drug_product
    		)
    			and
    		fk_encounter in (
    			select pk from clin.encounter where fk_patient = _pk_patient
    		);
    	-- linking all is fine but else:
    	if _intake_count != 0 then
    		-- How many components *are* there in the drug in question ?
    		select count(1) into _component_count
    		from ref.lnk_dose2drug
    		where fk_drug_product = _pk_drug_product;
    		-- substance intake link count and number of components must match
    		if _component_count != _intake_count then
    			_msg := '[clin.trf_upd_intake_must_link_all_drug_components]: re-linking drug product must link all components of new drug product [' || _pk_drug_product || '] '
    				|| '(component [' || OLD.fk_drug_component || ' -> ' || NEW.fk_drug_component || '])';
    			raise exception check_violation using message = _msg;
    		end if;
    	end if;
    	return NEW;
    END;

## Function: clin.trf_upd_intake_prevent_duplicate_component_links()

### Returns: trigger

### Language: PLPGSQL

Prevent patient from being put on a particular component twice.

    DECLARE
    	_pk_patient integer;
    	_intake_count integer;
    	_msg text;
    BEGIN
    	-- which patient ?
    	select fk_patient into _pk_patient
    	from clin.encounter
    	where pk = NEW.fk_encounter;
    	-- already exists ?
    	select count(1) into strict _intake_count
    	from clin.substance_intake
    	where
    		fk_encounter in (
    			select pk from clin.encounter where fk_patient = _pk_patient
    		)
    			and
    		fk_drug_component = NEW.fk_drug_component
    	;
    	if _intake_count > 1 then
    		_msg := '[clin.trf_upd_intake_prevent_duplicate_component_links]: drug component ref.lnk_dose2drug.pk=(' || NEW.fk_drug_component || ') '
    			|| 'already linked to patient=(' || _pk_patient || ') as clin.substance_intake';
    		raise exception unique_violation using message = _msg;
    	end if;
    	return NEW;
    END;

## Function: clin.trf_upd_intake_updates_all_drug_components()

### Returns: trigger

### Language: PLPGSQL

If a drug component substance intake is updated all sibling components must receive some values thereof.

    DECLARE
    	_pk_drug_product integer;
    	_component_count integer;
    	_pk_patient integer;
    BEGIN
    	-- which drug ?
    	select fk_drug_product into _pk_drug_product
    	from ref.lnk_dose2drug
    	where pk = NEW.fk_drug_component;
    	-- how many components therein ?
    	select count(1) into _component_count
    	from ref.lnk_dose2drug
    	where fk_drug_product = _pk_drug_product;
    	-- only one component ?
    	if _component_count = 1 then
    		return NEW;
    	end if;
    	-- which patient ?
    	select fk_patient into _pk_patient
    	from clin.encounter
    	where pk = NEW.fk_encounter;
    	-- update all substance instake fields shared by drug components ...
    	update clin.substance_intake set
    		clin_when = NEW.clin_when,				-- started
    		fk_encounter = NEW.fk_encounter,
    		soap_cat = NEW.soap_cat,
    		schedule = NEW.schedule,
    		duration = NEW.duration,
    		intake_is_approved_of = NEW.intake_is_approved_of,
    		is_long_term = NEW.is_long_term,
    		discontinued = NEW.discontinued,
    		discontinue_reason = NEW.discontinue_reason,
    		comment_on_start = NEW.comment_on_start,
    		harmful_use_type = NEW.harmful_use_type
    	where
    		-- ... which belong to this drug ...
    		fk_drug_component in (
    			select pk from ref.lnk_dose2drug where fk_drug_product = _pk_drug_product
    		)
    			AND
    		-- ... but are not THIS component ...
    		fk_drug_component != NEW.fk_drug_component
    			AND
    		-- ... this patient ...
    		fk_encounter in (
    			select pk from clin.encounter where fk_patient = _pk_patient
    		)
    			AND
    		-- ... are different in value (this will stop recursion as soon as all are equal)
    		(
    			clin_when is distinct from NEW.clin_when
    				OR
    			fk_encounter is distinct from NEW.fk_encounter
    				OR
    			soap_cat is distinct from NEW.soap_cat
    				OR
    			schedule is distinct from NEW.schedule
    				OR
    			duration is distinct from NEW.duration
    				OR
    			intake_is_approved_of is distinct from NEW.intake_is_approved_of
    				OR
    			is_long_term is distinct from NEW.is_long_term
    				OR
    			discontinued is distinct from NEW.discontinued
    				OR
    			discontinue_reason is distinct from NEW.discontinue_reason
    				OR
    			comment_on_start is distinct from NEW.comment_on_start
    				OR
    			harmful_use_type is distinct from NEW.harmful_use_type
    		)
    	;
    	return NEW;
    END;

## Function: clin.trf_upd_lc2sth_fk_generic_code()

### Returns: trigger

### Language: PLPGSQL

Check foreign key integrity on update of *.fk_generic_code -> ref.coding_system_root.pk_coding_system.

    DECLARE
    	_msg text;
    BEGIN
    	perform 1 from ref.coding_system_root where pk_coding_system = NEW.fk_generic_code;
    	if FOUND then
    		return NEW;
    	end if;
    	_msg := 'clin.trf_upd_lc2sth_fk_generic_code(): UPDATE of '
    		|| TG_TABLE_SCHEMA || '.' || TG_TABLE_NAME || ': '
    		|| 'fk_generic_code=(' || NEW.fk_generic_code || ') '
    		|| 'does not exist in ref.coding_system_root.pk_coding_system, '
    		|| 'old fk_generic_code=(' || OLD.fk_generic_code || ')';
    	raise foreign_key_violation using message = _msg;
    	return OLD;
    END;

# Schema de_de

## Table: de_de.beh_fall_typ

Art des Behandlungsfalls (MuVo/Impfung/...)

de_de.beh_fall_typ Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| code |  | UNIQUE
| kurzform |  | UNIQUE
| pk |  | PRIMARY KEY
| name |  | UNIQUE

Table de_de.beh_fall_typ Inherits audit_fields,

de_de.beh_fall_typ Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema de_de

## Table: de_de.kvk

Speichert die Daten einer bestimmten KVK. Wir trennen die KVK-Daten von den Daten ueber Person, Wohnort, Kassenzugehoerigkeit, Mitgliedsstatus und Abrechnungsfaellen. Diese Daten werden jedoch a) als Vorgaben fuer die eigentlichen Personendaten und b) als gueltig fuer abrechnungstechnische Belange angesehen.

de_de.kvk Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.identity.pk | fk_patient |  |
| pk |  | PRIMARY KEY

Index - Schema de_de

## Table: de_de.lab_test_gnr

specific for Germany, GNR = GebuehrenordnungsNummeR = billing item, build index before lab import and drop afterwards, check against this table when importing, build table during import

de_de.lab_test_gnr Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.test_type.pk | id_test |  |
| id |  | PRIMARY KEY

Table de_de.lab_test_gnr Inherits audit_fields,

de_de.lab_test_gnr Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema de_de

## Table: de_de.payment_method

de_de.payment_method Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| description |  | UNIQUE

Tables referencing this one via Foreign Key Constraints:

- de_de.prax_geb_paid

Index - Schema de_de

## Table: de_de.prax_geb_paid

de_de.prax_geb_paid Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
de_de.payment_method.pk | paid_with |  |

Table de_de.prax_geb_paid Inherits audit_fields,

de_de.prax_geb_paid Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema de_de

## Table: de_de.zuzahlungsbefreiung

de_de.zuzahlungsbefreiung Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| id |  | PRIMARY KEY
dem.identity.pk | id_patient |  |

Index - Schema de_de

# Schema dem

## Table: dem.address

an address aka a location, void of attached meaning such as type of address

dem.address Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| number |  | UNIQUE#1
dem.street.id | id_street |  | UNIQUE#1
| addendum |  | UNIQUE#1
| aux_street |  | UNIQUE#1
| subunit |  | UNIQUE#1
| id |  | PRIMARY KEY

Table dem.address Inherits audit_fields,

dem.address Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- dem.lnk_identity2comm

- dem.lnk_person_org_address

- dem.org_unit

idx_dem_address_id_street id_street

Index - Schema dem

## Table: dem.address_type

dem.address_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| id |  | PRIMARY KEY
| name |  | UNIQUE

Tables referencing this one via Foreign Key Constraints:

- dem.lnk_person_org_address

Index - Schema dem

## Table: dem.country

countries coded per ISO 3166-1

dem.country Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| code |  | UNIQUE
| id |  | PRIMARY KEY
| name |  | UNIQUE

dem.country Constraints
Name | Constraint
--- | ---
no_linebreaks | CHECK ((("position"(((COALESCE(code, ''::bpchar))::text || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"(((COALESCE(code, ''::bpchar))::text || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"(((COALESCE(code, ''::bpchar))::text || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"(((COALESCE(code, ''::bpchar))::text || COALESCE(name, ''::text)), ''::text) = 0)))

Tables referencing this one via Foreign Key Constraints:

- dem.region

Index - Schema dem

## Table: dem.enum_comm_types

dem.enum_comm_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| description |  | UNIQUE

Tables referencing this one via Foreign Key Constraints:

- dem.lnk_identity2comm

- dem.lnk_org_unit2comm

Index - Schema dem

## Table: dem.enum_ext_id_types

a list of all bureaucratic IDs/serial numbers/3rd party primary keys, etc.

dem.enum_ext_id_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| issuer |  | UNIQUE#1
| name |  | UNIQUE#1
| pk |  | PRIMARY KEY

Tables referencing this one via Foreign Key Constraints:

- dem.lnk_identity2ext_id

- dem.lnk_org_unit2ext_id

Index - Schema dem

## Table: dem.gender_label

This table stores the genders known to GNUmed. FIXME: cross-check with CDA:administrative-gender-code

dem.gender_label Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| label |  | UNIQUE
| pk |  | PRIMARY KEY
| tag |  | UNIQUE

Table dem.gender_label Inherits audit_fields,

dem.gender_label Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
gender_label_tag_check | CHECK ((tag = ANY (ARRAY['m'::text, 'f'::text, 'h'::text, 'tm'::text, 'tf'::text])))

Tables referencing this one via Foreign Key Constraints:

- dem.identity

Index - Schema dem

## Table: dem.identity

represents the unique identity of a person

dem.identity Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.marital_status.pk | fk_marital_status |  |
dem.gender_label.tag | gender |  |
dem.staff.pk | fk_primary_provider |  |
dem.identity.pk | fk_emergency_contact |  |
| pk |  | PRIMARY KEY

Table dem.identity Inherits audit_fields,

dem.identity Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
dem_identity_sane_dob | CHECK (((dob IS NULL) OR (dob <= now())))
dem_identity_sane_dod | CHECK (((deceased IS NULL) OR (dob IS NULL) OR (deceased >= dob)))
identity_title_check | CHECK ((btrim(COALESCE(title, 'NULL'::text)) <> ''::text))
sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
sane_emergency_contact | CHECK ((gm.is_null_or_non_empty_string(emergency_contact) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- au.referral

- bill.bill

- clin.lab_request

- clin.patient

- clin.test_org

- clin.waiting_list

- de_de.kvk

- de_de.zuzahlungsbefreiung

- dem.identity

- dem.identity_tag

- dem.lnk_identity2comm

- dem.lnk_identity2ext_id

- dem.lnk_job2person

- dem.lnk_person2relative

- dem.lnk_person_org_address

- dem.message_inbox

- dem.names

- dem.staff

idx_identity_dob_ymd dem.date_trunc_utc('day'::text, dob)

Index - Schema dem

## Table: dem.identity_tag

tags attached to this identity

dem.identity_tag Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.tag_image.pk | fk_tag |  | UNIQUE#1
| pk |  | PRIMARY KEY
dem.identity.pk | fk_identity |  | UNIQUE#1

Table dem.identity_tag Inherits audit_fields,

dem.identity_tag Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
dem_identity_tag_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))

Index - Schema dem

## Table: dem.inbox_item_category

Holds the various categories of messages that can show up in the provider inbox.

dem.inbox_item_category Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| description |  | UNIQUE

Table dem.inbox_item_category Inherits audit_fields,

dem.inbox_item_category Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
inbox_item_category_description_check | CHECK ((btrim(COALESCE(description, 'xxxDEFAULTxxx'::text)) <> ''::text))

Tables referencing this one via Foreign Key Constraints:

- dem.inbox_item_type

Index - Schema dem

## Table: dem.inbox_item_type

Holds the various types of messages that can show up in the provider inbox.

dem.inbox_item_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.inbox_item_category.pk | fk_inbox_item_category |  | UNIQUE#1
| description |  | UNIQUE#1
| pk |  | PRIMARY KEY

Table dem.inbox_item_type Inherits audit_fields,

dem.inbox_item_type Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
inbox_item_type_description_check | CHECK ((btrim(COALESCE(description, 'xxxDEFAULTxxx'::text)) <> ''::text))

Tables referencing this one via Foreign Key Constraints:

- dem.message_inbox

Index - Schema dem

## Table: dem.lnk_identity2comm

dem.lnk_identity2comm Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.address.id | fk_address |  |
dem.identity.pk | fk_identity |  | UNIQUE#1
| pk |  | PRIMARY KEY
| url |  | UNIQUE#1
dem.enum_comm_types.pk | fk_type |  |

dem.lnk_identity2comm Constraints
Name | Constraint
--- | ---
d_l_i2comm_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
lnk_identity2comm_url_check | CHECK ((btrim(url) <> ''::text))

Index - Schema dem

## Table: dem.lnk_identity2ext_id

link external IDs to GnuMed identities

dem.lnk_identity2ext_id Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| external_id |  | UNIQUE#1
| id |  | PRIMARY KEY
dem.identity.pk | id_identity |  | UNIQUE#1
dem.enum_ext_id_types.pk | fk_origin |  | UNIQUE#1

Table dem.lnk_identity2ext_id Inherits audit_fields,

dem.lnk_identity2ext_id Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema dem

## Table: dem.lnk_job2person

linking (possibly several) jobs to a person

dem.lnk_job2person Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.identity.pk | fk_identity |  | UNIQUE#1
| pk |  | PRIMARY KEY
dem.occupation.id | fk_occupation |  | UNIQUE#1

Table dem.lnk_job2person Inherits audit_fields,

dem.lnk_job2person Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema dem

## Table: dem.lnk_org_unit2comm

Comm channels per org unit.

dem.lnk_org_unit2comm Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.enum_comm_types.pk | fk_type |  | UNIQUE#1
| url |  | UNIQUE#1
| pk |  | PRIMARY KEY
dem.org_unit.pk | fk_org_unit |  | UNIQUE#1

Table dem.lnk_org_unit2comm Inherits audit_fields,

dem.lnk_org_unit2comm Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
dem_lnk_unit2comm_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
lnk_org_unit2comm_sane_url | CHECK ((gm.is_null_or_blank_string(url) IS FALSE))

Index - Schema dem

## Table: dem.lnk_org_unit2ext_id

External IDs per org unit.

dem.lnk_org_unit2ext_id Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.org_unit.pk | fk_org_unit |  | UNIQUE#1
| pk |  | PRIMARY KEY
dem.enum_ext_id_types.pk | fk_type |  | UNIQUE#1
| external_id |  | UNIQUE#1

Table dem.lnk_org_unit2ext_id Inherits audit_fields,

dem.lnk_org_unit2ext_id Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
lnk_org_unit2ext_id_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
lnk_org_unit2ext_id_sane_id | CHECK ((gm.is_null_or_blank_string(external_id) IS FALSE))

Index - Schema dem

## View: dem.lnk_person2address

dem.lnk_person2address Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT lnk_person_org_address.id_identity
    ,
        lnk_person_org_address.id_address
    ,
        lnk_person_org_address.id_type

    FROM dem.lnk_person_org_address;

Index - Schema dem

## Table: dem.lnk_person2relative

biological and social relationships between an identity and other identities

dem.lnk_person2relative Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.identity.pk | id_relative |  |
dem.relation_types.id | id_relation_type |  |
dem.identity.pk | id_identity |  |
| id |  | PRIMARY KEY

Table dem.lnk_person2relative Inherits audit_fields,

dem.lnk_person2relative Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

idx_lnk_pers2rel id_identity, id_relation_type

Index - Schema dem

## Table: dem.lnk_person_org_address

a many-to-many pivot table describing the relationship between an organisation, a person, their work address and their occupation at that location. For patients id_org is NULL

dem.lnk_person_org_address Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| id_org |  | UNIQUE#2
| id |  | PRIMARY KEY
dem.address.id | id_address |  | UNIQUE#1 UNIQUE#2
dem.address_type.id | id_type |  |
dem.identity.pk | id_identity |  | UNIQUE#1

Tables referencing this one via Foreign Key Constraints:

- bill.bill

Index - Schema dem

## Table: dem.marital_status

dem.marital_status Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| name |  | UNIQUE
| pk |  | PRIMARY KEY

Tables referencing this one via Foreign Key Constraints:

- dem.identity

Index - Schema dem

## Table: dem.message_inbox

messages in GNUmed relating to a patient, a provider, and a context

dem.message_inbox Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.identity.pk | fk_patient |  |
| pk |  | PRIMARY KEY
dem.staff.pk | fk_staff |  |
dem.inbox_item_type.pk | fk_inbox_item_type |  |

Table dem.message_inbox Inherits audit_fields,

dem.message_inbox Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
dem_inbox_sane_expiry_date | CHECK (((expiry_date IS NULL) OR (due_date IS NULL) OR (expiry_date > due_date)))
message_must_have_recipient | CHECK ((((fk_staff IS NULL) AND (fk_patient IS NULL)) IS FALSE))
provider_inbox_comment_check | CHECK ((btrim(COALESCE(comment, 'xxxDEFAULTxxx'::text)) <> ''::text))
provider_inbox_importance_check | CHECK (((importance = '-1'::integer) OR (importance = 0) OR (importance = 1)))

idx_msg_inbox_fk_patient fk_patient idx_msg_inbox_fk_staff fk_staff

Index - Schema dem

## Table: dem.name_gender_map

maps (first) names to their most frequently locally assigned gender, this table is updated nightly by a cron script, names whose gender distribution is between 70/30 and 30/70 are ignored for ambiguity reasons, names with "ambigous" gender are also ignored

dem.name_gender_map Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| name |  | UNIQUE
| id |  | PRIMARY KEY

dem.name_gender_map Constraints
Name | Constraint
--- | ---
name_gender_map_gender_check | CHECK ((gender = ANY (ARRAY['m'::bpchar, 'f'::bpchar])))

Index - Schema dem

## Table: dem.names

all the names an identity is known under; As opposed to the versioning of all other tables, changed names should not be moved into the audit trail tables. Search functionality must be available at any time for all names a person ever had.

dem.names Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.identity.pk | id_identity |  | UNIQUE#1
| lastnames |  | UNIQUE#1
| firstnames |  | UNIQUE#1
| id |  | PRIMARY KEY

idx_names_firstnames firstnames idx_names_last_first lastnames, firstnames

Index - Schema dem

## Table: dem.occupation

collects occupation names

dem.occupation Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| id |  | PRIMARY KEY

Table dem.occupation Inherits audit_fields,

dem.occupation Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
occupation_name_check | CHECK ((btrim(name) <> ''::text))

Tables referencing this one via Foreign Key Constraints:

- dem.lnk_job2person

Index - Schema dem

## Table: dem.org

Organizations at a conceptual level.

dem.org Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.data_source.pk | fk_data_source |  |
| pk |  | PRIMARY KEY
| description |  | UNIQUE
dem.org_category.pk | fk_category |  |

Table dem.org Inherits audit_fields,

dem.org Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
org_sane_description | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- dem.org_unit

idx_dem_org_fk_category fk_category

Index - Schema dem

## Table: dem.org_category

dem.org_category Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

Tables referencing this one via Foreign Key Constraints:

- dem.org

- dem.org_unit

Index - Schema dem

## Table: dem.org_unit

Actual branches/departments/offices/... of organizations.

dem.org_unit Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.org_category.pk | fk_category |  |
dem.org.pk | fk_org |  | UNIQUE#1
dem.address.id | fk_address |  |
| description |  | UNIQUE#1
| pk |  | PRIMARY KEY

Table dem.org_unit Inherits audit_fields,

dem.org_unit Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
org_unit_sane_description | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- blobs.doc_med

- clin.encounter

- clin.external_care

- clin.hospital_stay

- clin.procedure

- clin.test_org

- dem.lnk_org_unit2comm

- dem.lnk_org_unit2ext_id

idx_dem_org_unit_fk_address fk_address idx_dem_org_unit_fk_category fk_category

Index - Schema dem

## Table: dem.praxis_branch

Defines one branch of a praxis (which itself is a dem.org)

dem.praxis_branch Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| fk_org_unit |  | UNIQUE

Table dem.praxis_branch Inherits audit_fields,

dem.praxis_branch Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Index - Schema dem

## Table: dem.region

region codes (country specific); Richard agreed we should require pre-existence, allow user to mail details for adding a state to developers

dem.region Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| code |  | UNIQUE#1
| pk |  | PRIMARY KEY
dem.country.code | country |  | UNIQUE#1

Table dem.region Inherits audit_fields,

dem.region Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
no_linebreaks | CHECK ((("position"(((COALESCE(code, ''::text) || (COALESCE(country, ''::bpchar))::text) || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"(((COALESCE(code, ''::text) || (COALESCE(country, ''::bpchar))::text) || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"(((COALESCE(code, ''::text) || (COALESCE(country, ''::bpchar))::text) || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"(((COALESCE(code, ''::text) || (COALESCE(country, ''::bpchar))::text) || COALESCE(name, ''::text)), ''::text) = 0)))

Tables referencing this one via Foreign Key Constraints:

- dem.urb

idx_dem_state_country_code country idx_state_names name

Index - Schema dem

## Table: dem.relation_types

types of biological/social relationships between identities

dem.relation_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.relation_types.id | inverse |  |
| id |  | PRIMARY KEY

Table dem.relation_types Inherits audit_fields,

dem.relation_types Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- dem.lnk_person2relative

- dem.relation_types

Index - Schema dem

## Table: dem.staff

one-to-one mapping of database user accounts (db_user) to staff identities (fk_identity)

dem.staff Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.identity.pk | fk_identity |  |
| db_user |  | UNIQUE
| short_alias |  | UNIQUE
| pk |  | PRIMARY KEY

Table dem.staff Inherits audit_fields,

dem.staff Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- bill.bill_item

- blobs.doc_obj

- clin.incoming_data_unmatched

- clin.review_root

- clin.reviewed_test_results

- clin.test_result

- clin.vaccination

- dem.identity

- dem.message_inbox

- ref.keyword_expansion

Index - Schema dem

## Table: dem.street

street names, specific for distinct "urbs"

dem.street Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
dem.urb.id | id_urb |  | UNIQUE#1
| id |  | PRIMARY KEY
| postcode |  | UNIQUE#1
| name |  | UNIQUE#1

Table dem.street Inherits audit_fields,

dem.street Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
no_linebreaks | CHECK ((("position"(((COALESCE(postcode, ''::text) || COALESCE(suburb, ''::text)) || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"(((COALESCE(postcode, ''::text) || COALESCE(suburb, ''::text)) || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"(((COALESCE(postcode, ''::text) || COALESCE(suburb, ''::text)) || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"(((COALESCE(postcode, ''::text) || COALESCE(suburb, ''::text)) || COALESCE(name, ''::text)), ''::text) = 0)))

Tables referencing this one via Foreign Key Constraints:

- dem.address

idx_dem_street_id_urb id_urb idx_street_names name idx_street_zips postcode

Index - Schema dem

## Table: dem.urb

cities, towns, dwellings ..., eg. "official" places of residence

dem.urb Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| postcode |  | UNIQUE#1
| name |  | UNIQUE#1
| id |  | PRIMARY KEY
dem.region.pk | fk_region |  | UNIQUE#1

Table dem.urb Inherits audit_fields,

dem.urb Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
no_linebreaks | CHECK ((("position"((COALESCE(postcode, ''::text) || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"((COALESCE(postcode, ''::text) || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"((COALESCE(postcode, ''::text) || COALESCE(name, ''::text)), ' '::text) = 0) AND ("position"((COALESCE(postcode, ''::text) || COALESCE(name, ''::text)), ''::text) = 0)))

Tables referencing this one via Foreign Key Constraints:

- dem.street

idx_dem_urb_id_state fk_region idx_urb_names name idx_urb_zips postcode

Index - Schema dem

## View: dem.v_active_persons

This view denormalizes non-deleted persons with their active name.

dem.v_active_persons Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_vp.pk_identity
    ,
        d_vp.title
    ,
        d_vp.firstnames
    ,
        d_vp.preferred
    ,
        d_vp.lastnames
    ,
        d_vp.gender
    ,
        d_vp.l10n_gender
    ,
        d_vp.dob_only
    ,
        d_vp.dob
    ,
        d_vp.tob
    ,
        d_vp.deceased
    ,
        d_vp.marital_status
    ,
        d_vp.l10n_marital_status
    ,
        d_vp.emergency_contact
    ,
        d_vp.comment
    ,
        d_vp.is_deleted
    ,
        d_vp.pk_marital_status
    ,
        d_vp.pk_active_name
    ,
        d_vp.pk_emergency_contact
    ,
        d_vp.pk_primary_provider
    ,
        d_vp.xmin_identity
    ,
        d_vp.dob_is_estimated

    FROM dem.v_all_persons d_vp

    WHERE (d_vp.is_deleted IS FALSE);

Index - Schema dem

## View: dem.v_address

fully denormalizes data about addresses as entities in themselves

dem.v_address Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_adr.id AS pk_address
    ,
        d_str.name AS street
    ,
        COALESCE
    (d_str.postcode
         , d_u.postcode
    ) AS postcode
    ,
        d_adr.aux_street AS notes_street
    ,
        d_adr.number
    ,
        d_adr.subunit
    ,
        d_adr.addendum AS notes_subunit
    ,
        d_adr.lat_lon AS lat_lon_address
    ,
        d_str.postcode AS postcode_street
    ,
        d_str.lat_lon AS lat_lon_street
    ,
        d_str.suburb
    ,
        d_u.name AS urb
    ,
        d_u.postcode AS postcode_urb
    ,
        d_u.lat_lon AS lat_lon_urb
    ,
        d_r.code AS code_region
    ,
        d_r.name AS region
    ,
        _
    (d_r.name) AS l10n_region
    ,
        d_r.country AS code_country
    ,
        d_c.name AS country
    ,
        _
    (d_c.name) AS l10n_country
    ,
        d_c.deprecated AS country_deprecated
    ,
        d_adr.id_street AS pk_street
    ,
        d_u.id AS pk_urb
    ,
        d_r.pk AS pk_region
    ,
        d_adr.xmin AS xmin_address

    FROM (
         (
               (
                     (dem.address d_adr

                   LEFT JOIN dem.street d_str
                          ON (
                                 (d_adr.id_street = d_str.id)
                           )
                     )

             LEFT JOIN dem.urb d_u
                    ON (
                           (d_str.id_urb = d_u.id)
                     )
               )

       LEFT JOIN dem.region d_r
              ON (
                     (d_u.fk_region = d_r.pk)
               )
         )

    LEFT JOIN dem.country d_c
        ON (
               (d_c.code = d_r.country)
         )
    );

Index - Schema dem

## View: dem.v_all_persons

This view denormalizes persons with their active name.

dem.v_all_persons Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_i.pk AS pk_identity
    ,
        d_i.title
    ,
        d_n.firstnames
    ,
        d_n.preferred
    ,
        d_n.lastnames
    ,
        d_i.gender
    ,
        _
    (d_i.gender) AS l10n_gender
    ,
        d_i.dob AS dob_only
    ,

    (date_trunc
         ('day'::text
               , d_i.dob
         ) +
         (COALESCE
               (d_i.tob
                     , (d_i.dob)::time without time zone
               )
         )::interval
    ) AS dob
    ,
        d_i.tob
    ,
        d_i.deceased
    ,
        COALESCE
    (d_ms.name
         ,'unknown'::text
    ) AS marital_status
    ,
        _
    (COALESCE
         (d_ms.name
               ,'unknown'::text
         )
    ) AS l10n_marital_status
    ,
        d_i.emergency_contact
    ,
        d_i.comment
    ,
        d_i.deleted AS is_deleted
    ,
        d_i.fk_marital_status AS pk_marital_status
    ,
        d_n.id AS pk_active_name
    ,
        d_i.fk_emergency_contact AS pk_emergency_contact
    ,
        d_i.fk_primary_provider AS pk_primary_provider
    ,
        d_i.xmin AS xmin_identity
    ,
        d_i.dob_is_estimated

    FROM (
         (dem.identity d_i

            JOIN dem.names d_n
              ON (
                     (
                           (d_n.id_identity = d_i.pk)
                         AND (d_n.active IS TRUE)
                     )
               )
         )

    LEFT JOIN dem.marital_status d_ms
        ON (
               (d_i.fk_marital_status = d_ms.pk)
         )
    );

Index - Schema dem

## View: dem.v_basic_address

dem.v_basic_address Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_adr.id
    ,
        d_r.country AS country_code
    ,
        d_r.code AS region_code
    ,
        d_r.name AS region
    ,
        d_c.name AS country
    ,
        COALESCE
    (d_str.postcode
         , d_u.postcode
    ) AS postcode
    ,
        d_u.name AS urb
    ,
        d_adr.number
    ,
        d_str.name AS street
    ,
        d_adr.addendum
    ,
        COALESCE
    (d_adr.lat_lon
         , d_str.lat_lon
         , d_u.lat_lon
    ) AS lat_lon

    FROM dem.address d_adr
    ,
        dem.region d_r
    ,
        dem.country d_c
    ,
        dem.urb d_u
    ,
        dem.street d_str

    WHERE (
         (d_r.country = d_c.code)
       AND (d_adr.id_street = d_str.id)
       AND (d_str.id_urb = d_u.id)
       AND (d_u.fk_region = d_r.pk)
    );

Index - Schema dem

## View: dem.v_deleted_persons

This view denormalizes "deleted" persons with their active name.

dem.v_deleted_persons Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_vp.pk_identity
    ,
        d_vp.title
    ,
        d_vp.firstnames
    ,
        d_vp.preferred
    ,
        d_vp.lastnames
    ,
        d_vp.gender
    ,
        d_vp.l10n_gender
    ,
        d_vp.dob_only
    ,
        d_vp.dob
    ,
        d_vp.tob
    ,
        d_vp.deceased
    ,
        d_vp.marital_status
    ,
        d_vp.l10n_marital_status
    ,
        d_vp.emergency_contact
    ,
        d_vp.comment
    ,
        d_vp.is_deleted
    ,
        d_vp.pk_marital_status
    ,
        d_vp.pk_active_name
    ,
        d_vp.pk_emergency_contact
    ,
        d_vp.pk_primary_provider
    ,
        d_vp.xmin_identity
    ,
        d_vp.dob_is_estimated

    FROM dem.v_all_persons d_vp

    WHERE (d_vp.is_deleted IS TRUE);

Index - Schema dem

## View: dem.v_external_ids4identity

dem.v_external_ids4identity Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT li2ei.id_identity AS pk_identity
    ,
        li2ei.id AS pk_id
    ,
        eit.name
    ,
        li2ei.external_id AS value
    ,
        eit.issuer
    ,
        li2ei.comment
    ,
        li2ei.fk_origin AS pk_type

    FROM dem.lnk_identity2ext_id li2ei
    ,
        dem.enum_ext_id_types eit

    WHERE (li2ei.fk_origin = eit.pk);

Index - Schema dem

## View: dem.v_external_ids4org_unit

dem.v_external_ids4org_unit Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_lou2ei.fk_org_unit AS pk_org_unit
    ,
        d_lou2ei.pk AS pk_id
    ,
        d_eit.name
    ,
        d_lou2ei.external_id AS value
    ,
        d_eit.issuer
    ,
        d_lou2ei.comment
    ,
        d_lou2ei.fk_type AS pk_type

    FROM (dem.lnk_org_unit2ext_id d_lou2ei

      JOIN dem.enum_ext_id_types d_eit
        ON (
               (d_lou2ei.fk_type = d_eit.pk)
         )
    );

Index - Schema dem

## View: dem.v_gender_labels

dem.v_gender_labels Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT gl.tag
    ,
        _
    (gl.tag) AS l10n_tag
    ,
        gl.label
    ,
        _
    (gl.label) AS l10n_label
    ,
        gl.comment
    ,
        gl.sort_weight
    ,
        gl.pk AS pk_gender_label

    FROM dem.gender_label gl;

Index - Schema dem

## View: dem.v_identity_tags

dem.v_identity_tags Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT dit.fk_identity AS pk_identity
    ,
        rti.description
    ,
        _
    (rti.description) AS l10n_description
    ,
        dit.comment
    ,
        rti.filename
    ,
        octet_length
    (COALESCE
         (rti.image
               ,'\x'::bytea
         )
    ) AS image_size
    ,
        dit.pk AS pk_identity_tag
    ,
        rti.pk AS pk_tag_image
    ,
        dit.xmin AS xmin_identity_tag

    FROM (dem.identity_tag dit

    LEFT JOIN ref.tag_image rti
        ON (
               (dit.fk_tag = rti.pk)
         )
    );

Index - Schema dem

## View: dem.v_inbox_item_type

dem.v_inbox_item_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT it.description AS type
    ,
        _
    (it.description) AS l10n_type
    ,
        ic.description AS category
    ,
        _
    (ic.description) AS l10n_category
    ,
        it.is_user AS is_user_type
    ,
        ic.is_user AS is_user_category
    ,
        it.pk AS pk_type
    ,
        it.fk_inbox_item_category AS pk_category

    FROM dem.inbox_item_type it
    ,
        dem.inbox_item_category ic

    WHERE (it.fk_inbox_item_category = ic.pk);

Index - Schema dem

## View: dem.v_message_inbox

Denormalized messages for the providers and/or patients. Using UNION makes sure we get the right level of uniqueness.

dem.v_message_inbox Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT all_msgs.received_when
    ,
        all_msgs.modified_by
    ,
        all_msgs.provider
    ,
        all_msgs.importance
    ,
        all_msgs.category
    ,
        all_msgs.l10n_category
    ,
        all_msgs.type
    ,
        all_msgs.l10n_type
    ,
        all_msgs.comment
    ,
        all_msgs.pk_context
    ,
        all_msgs.data
    ,
        all_msgs.pk_inbox_message
    ,
        all_msgs.pk_staff
    ,
        all_msgs.pk_category
    ,
        all_msgs.pk_type
    ,
        all_msgs.pk_patient
    ,
        all_msgs.is_virtual
    ,
        all_msgs.due_date
    ,
        all_msgs.expiry_date
    ,
        all_msgs.is_overdue
    ,
        all_msgs.is_expired
    ,
        all_msgs.interval_due
    ,
        all_msgs.xmin_message_inbox
    ,
        d_n.lastnames
    ,
        d_n.firstnames
    ,
        d_n.preferred AS preferred_name
    ,
        d_n.comment AS comment_name
    ,
        d_i.gender
    ,
        _
    (d_i.gender) AS l10n_gender
    ,

    (date_trunc
         ('day'::text
               , d_i.dob
         ) +
         (COALESCE
               (d_i.tob
                     , (d_i.dob)::time without time zone
               )
         )::interval
    ) AS dob
    ,
        d_i.deceased
    ,
        d_i.title
    ,
        d_i.comment AS comment_identity

    FROM (
         (
               (
                SELECT mi.modified_when AS received_when
                     ,
                COALESCE
                     (
                           (
                            SELECT staff.short_alias

                              FROM dem.staff

                             WHERE (staff.db_user = mi.modified_by)
                           )
                           , (
                                 ('<'::text ||
                                       (mi.modified_by)::text
                                 ) || '>'::text
                           )
                     ) AS modified_by
                     ,

                     (
                      SELECT staff.short_alias

                        FROM dem.staff

                       WHERE (staff.pk = mi.fk_staff)
                     ) AS provider
                     ,
                mi.importance
                     ,
                vit.category
                     ,
                vit.l10n_category
                     ,
                vit.type
                     ,
                vit.l10n_type
                     ,
                mi.comment
                     ,
                mi.ufk_context AS pk_context
                     ,
                mi.data
                     ,
                mi.pk AS pk_inbox_message
                     ,
                mi.fk_staff AS pk_staff
                     ,
                vit.pk_category
                     ,
                mi.fk_inbox_item_type AS pk_type
                     ,
                mi.fk_patient AS pk_patient
                     ,
                false AS is_virtual
                     ,
                mi.due_date
                     ,
                mi.expiry_date
                     ,
                    CASE
                        WHEN
                     (mi.due_date IS NULL) THEN false
                        WHEN
                     (mi.due_date > now
                           ()
                     ) THEN false
                        WHEN
                     (mi.expiry_date IS NULL) THEN true
                        WHEN
                     (mi.expiry_date < now
                           ()
                     ) THEN false
                        ELSE true
                    END AS is_overdue
                     ,
                    CASE
                        WHEN
                     (mi.expiry_date IS NULL) THEN false
                        WHEN
                     (mi.expiry_date > now
                           ()
                     ) THEN false
                        ELSE true
                    END AS is_expired
                     ,
                    CASE
                        WHEN
                     (mi.due_date IS NULL) THEN NULL::interval
                        WHEN
                     (mi.due_date > now
                           ()
                     ) THEN
                     (
                           (mi.due_date)::timestamp with time zone - now
                           ()
                     )
                        ELSE
                     (now
                           () -
                           (mi.due_date)::timestamp with time zone
                     )
                    END AS interval_due
                     ,
                gm.xid2int
                     (mi.xmin) AS xmin_message_inbox

                  FROM dem.message_inbox mi
                     ,
                dem.v_inbox_item_type vit

                 WHERE (mi.fk_inbox_item_type = vit.pk_type)

             UNION ALL

                SELECT v_unreviewed_docs_inbox.received_when
                     ,
                v_unreviewed_docs_inbox.modified_by
                     ,
                v_unreviewed_docs_inbox.provider
                     ,
                v_unreviewed_docs_inbox.importance
                     ,
                v_unreviewed_docs_inbox.category
                     ,
                v_unreviewed_docs_inbox.l10n_category
                     ,
                v_unreviewed_docs_inbox.type
                     ,
                v_unreviewed_docs_inbox.l10n_type
                     ,
                v_unreviewed_docs_inbox.comment
                     ,
                v_unreviewed_docs_inbox.pk_context
                     ,
                v_unreviewed_docs_inbox.data
                     ,
                v_unreviewed_docs_inbox.pk_inbox_message
                     ,
                v_unreviewed_docs_inbox.pk_staff
                     ,
                v_unreviewed_docs_inbox.pk_category
                     ,
                v_unreviewed_docs_inbox.pk_type
                     ,
                v_unreviewed_docs_inbox.pk_patient
                     ,
                v_unreviewed_docs_inbox.is_virtual
                     ,
                v_unreviewed_docs_inbox.due_date
                     ,
                v_unreviewed_docs_inbox.expiry_date
                     ,
                v_unreviewed_docs_inbox.is_overdue
                     ,
                v_unreviewed_docs_inbox.is_expired
                     ,
                v_unreviewed_docs_inbox.interval_due
                     ,
                v_unreviewed_docs_inbox.xmin_message_inbox

                  FROM blobs.v_unreviewed_docs_inbox

             UNION ALL (

                      SELECT now
                           () AS received_when
                           ,
                        vtr.modified_by
                           ,

                           (
                            SELECT staff.short_alias

                              FROM dem.staff

                             WHERE (staff.pk = vtr.pk_intended_reviewer)
                           ) AS provider
                           ,
                        1 AS importance
                           ,
                        'clinical'::text AS category
                           ,
                        _
                           ('clinical'::text) AS l10n_category
                           ,
                        'review results'::text AS type
                           ,
                        _
                           ('review results'::text) AS l10n_type
                           ,

                           (
                            SELECT (
                                       (
                                             (
                                                   (
                                                         (_
                                                               ('unreviewed (abnormal) results for patient'::text
                                                         ) || ' ['::text
                                                   ) || dn.lastnames
                                             ) ||
                                          ', '::text
                                       ) || dn.firstnames
                                 ) || ']'::text
                           )

                        FROM dem.names dn

                       WHERE (
                                 (dn.id_identity = vtr.pk_patient)
                               AND (dn.active IS TRUE)
                           )
                     ) AS comment
                     ,
                        NULL::integer[] AS pk_context
                     ,
                        NULL::text AS data
                     ,
                        NULL::integer AS pk_inbox_message
                     ,
                        vtr.pk_intended_reviewer AS pk_staff
                     ,

                     (
                      SELECT v_inbox_item_type.pk_category

                        FROM dem.v_inbox_item_type

                       WHERE (v_inbox_item_type.type = 'review results'::text)
                     ) AS pk_category
                     ,

                     (
                      SELECT v_inbox_item_type.pk_type

                        FROM dem.v_inbox_item_type

                       WHERE (v_inbox_item_type.type = 'review results'::text)
                     ) AS pk_type
                     ,
                        vtr.pk_patient
                     ,
                        true AS is_virtual
                     ,

                     (now
                           () - '01:00:00'::interval
                     ) AS due_date
                     ,
                        NULL::timestamp with time zone AS expiry_date
                     ,
                        true AS is_overdue
                     ,
                        false AS is_expired
                     ,
                        '01:00:00'::interval AS interval_due
                     ,
                        NULL::integer AS xmin_message_inbox

                  FROM clin.v_test_results vtr

                 WHERE (
                           (vtr.reviewed IS FALSE)
                         AND (
                                 (vtr.is_technically_abnormal IS TRUE)
                                OR (
                                       (vtr.is_technically_abnormal IS NULL)
                                     AND (vtr.abnormality_indicator IS NOT NULL)
                                 )
                           )
                     )

                 UNION

                SELECT now
                     () AS received_when
                     ,
                        vtr.modified_by
                     ,

                     (
                      SELECT staff.short_alias

                        FROM dem.staff

                       WHERE (staff.pk = vtr.pk_intended_reviewer)
                     ) AS provider
                     ,
                        0 AS importance
                     ,
                        'clinical'::text AS category
                     ,
                        _
                     ('clinical'::text) AS l10n_category
                     ,
                        'review results'::text AS type
                     ,
                        _
                     ('review results'::text) AS l10n_type
                     ,

                     (
                      SELECT (
                                 (
                                       (
                                             (
                                                   (_
                                                         ('unreviewed (normal) results for patient'::text
                                                   ) || ' ['::text
                                             ) || dn.lastnames
                                       ) ||
                                    ', '::text
                                 ) || dn.firstnames
                           ) || ']'::text
                     )

                  FROM dem.names dn

                 WHERE (
                           (dn.id_identity = vtr.pk_patient)
                         AND (dn.active IS TRUE)
                     )
               ) AS comment
               ,
                        NULL::integer[] AS pk_context
               ,
                        NULL::text AS data
               ,
                        NULL::integer AS pk_inbox_message
               ,
                        vtr.pk_intended_reviewer AS pk_staff
               ,

               (
                SELECT v_inbox_item_type.pk_category

                  FROM dem.v_inbox_item_type

                 WHERE (v_inbox_item_type.type = 'review results'::text)
               ) AS pk_category
               ,

               (
                SELECT v_inbox_item_type.pk_type

                  FROM dem.v_inbox_item_type

                 WHERE (v_inbox_item_type.type = 'review results'::text)
               ) AS pk_type
               ,
                        vtr.pk_patient
               ,
                        true AS is_virtual
               ,

               (now
                     () - '01:00:00'::interval
               ) AS due_date
               ,
                        NULL::timestamp with time zone AS expiry_date
               ,
                        true AS is_overdue
               ,
                        false AS is_expired
               ,
                        '01:00:00'::interval AS interval_due
               ,
                        NULL::integer AS xmin_message_inbox

            FROM clin.v_test_results vtr

           WHERE (
                     (vtr.reviewed IS FALSE)
                   AND (
                           (vtr.is_technically_abnormal IS FALSE)
                          OR (
                                 (vtr.is_technically_abnormal IS NULL)
                               AND (vtr.abnormality_indicator IS NULL)
                           )
                     )
               )

         )
    ) all_msgs

    LEFT JOIN dem.identity d_i
    ON (
         (all_msgs.pk_patient = d_i.pk)
    )
    )

    LEFT JOIN dem.names d_n
    ON     (
    (d_i.pk = d_n.id_identity)
    )
    )

    WHERE        (d_n.active IS DISTINCT
    FROM   false
    )           ;

Index - Schema dem

## View: dem.v_org_unit_comms

denormalizes org units to communication channels

dem.v_org_unit_comms Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_lo2c.fk_org_unit AS pk_org_unit
    ,
        ect.description AS comm_type
    ,
        _
    (ect.description) AS l10n_comm_type
    ,
        d_lo2c.url
    ,
        d_lo2c.comment
    ,
        d_lo2c.is_confidential
    ,
        d_lo2c.pk AS pk_lnk_org_unit2comm
    ,
        d_lo2c.fk_type AS pk_type
    ,
        d_lo2c.xmin AS xmin_lnk_org_unit2comm

    FROM (dem.lnk_org_unit2comm d_lo2c

      JOIN dem.enum_comm_types ect
        ON (
               (d_lo2c.fk_type = ect.pk)
         )
    );

Index - Schema dem

## View: dem.v_org_units

dem.v_org_units Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_ou.pk AS pk_org_unit
    ,
        d_o.description AS organization
    ,
        d_ou.description AS unit
    ,
        d_oc_o.description AS organization_category
    ,
        _
    (d_oc_o.description) AS l10n_organization_category
    ,
        d_oc_u.description AS unit_category
    ,
        _
    (d_oc_u.description) AS l10n_unit_category
    ,

    (EXISTS
         (
          SELECT 1

            FROM dem.praxis_branch d_pb

           WHERE (d_pb.fk_org_unit = d_ou.pk)
         )
    ) AS is_praxis_branch
    ,
        d_o.pk AS pk_org
    ,
        d_o.fk_category AS pk_category_org
    ,
        d_ou.fk_category AS pk_category_unit
    ,
        d_ou.fk_address AS pk_address
    ,
        d_ou.xmin AS xmin_org_unit

    FROM (
         (
               (dem.org_unit d_ou

                  JOIN dem.org d_o
                    ON (
                           (d_o.pk = d_ou.fk_org)
                     )
               )

       LEFT JOIN dem.org_category d_oc_u
              ON (
                     (d_ou.fk_category = d_oc_u.pk)
               )
         )

    LEFT JOIN dem.org_category d_oc_o
        ON (
               (d_o.fk_category = d_oc_o.pk)
         )
    );

Index - Schema dem

## View: dem.v_org_units_no_praxis_check

dem.v_org_units_no_praxis_check Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_ou.pk AS pk_org_unit
    ,
        d_o.description AS organization
    ,
        d_ou.description AS unit
    ,
        d_oc_o.description AS organization_category
    ,
        _
    (d_oc_o.description) AS l10n_organization_category
    ,
        d_oc_u.description AS unit_category
    ,
        _
    (d_oc_u.description) AS l10n_unit_category
    ,
        d_o.pk AS pk_org
    ,
        d_o.fk_category AS pk_category_org
    ,
        d_ou.fk_category AS pk_category_unit
    ,
        d_ou.fk_address AS pk_address
    ,
        d_ou.xmin AS xmin_org_unit

    FROM (
         (
               (dem.org_unit d_ou

                  JOIN dem.org d_o
                    ON (
                           (d_o.pk = d_ou.fk_org)
                     )
               )

       LEFT JOIN dem.org_category d_oc_u
              ON (
                     (d_ou.fk_category = d_oc_u.pk)
               )
         )

    LEFT JOIN dem.org_category d_oc_o
        ON (
               (d_o.fk_category = d_oc_o.pk)
         )
    );

Index - Schema dem

## View: dem.v_orgs

dem.v_orgs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_o.pk AS pk_org
    ,
        d_o.description AS organization
    ,
        d_oc.description AS category
    ,
        _
    (d_oc.description) AS l10n_category
    ,

    (EXISTS
         (
          SELECT 1

            FROM dem.praxis_branch d_pb

           WHERE (d_pb.fk_org_unit IN
                     (
                      SELECT d_ou.pk

                        FROM dem.org_unit d_ou

                       WHERE (d_ou.fk_org = d_o.pk)
                     )
               )
         )
    ) AS is_praxis
    ,
        d_o.fk_category AS pk_category_org
    ,
        d_o.xmin AS xmin_org

    FROM (dem.org d_o

    LEFT JOIN dem.org_category d_oc
        ON (
               (d_o.fk_category = d_oc.pk)
         )
    );

Index - Schema dem

## View: dem.v_pat_addresses

denormalized addresses per person

dem.v_pat_addresses Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_vp.pk_identity
    ,
        d_va.pk_address
    ,
        d_at.name AS address_type
    ,
        _
    (d_at.name) AS l10n_address_type
    ,
        d_vp.title
    ,
        d_vp.firstnames
    ,
        d_vp.lastnames
    ,
        d_vp.dob
    ,
        d_vp.gender
    ,
        d_vp.l10n_gender
    ,
        d_vp.preferred
    ,
        d_va.street
    ,
        d_va.postcode
    ,
        d_va.notes_street
    ,
        d_va.number
    ,
        d_va.subunit
    ,
        d_va.notes_subunit
    ,
        d_va.lat_lon_address
    ,
        d_va.postcode_street
    ,
        d_va.lat_lon_street
    ,
        d_va.suburb
    ,
        d_va.urb
    ,
        d_va.postcode_urb
    ,
        d_va.lat_lon_urb
    ,
        d_va.code_region
    ,
        d_va.region
    ,
        d_va.l10n_region
    ,
        d_va.code_country
    ,
        d_va.country
    ,
        d_va.l10n_country
    ,
        d_va.country_deprecated
    ,
        d_va.pk_street
    ,
        d_va.pk_urb
    ,
        d_va.pk_region
    ,
        d_lpoa.id AS pk_lnk_person_org_address
    ,
        d_lpoa.id_type AS pk_address_type
    ,
        d_lpoa.xmin AS xmin_lnk_person_org_address

    FROM (
         (
               (dem.lnk_person_org_address d_lpoa

                  JOIN dem.v_address d_va
                    ON (
                           (d_lpoa.id_address = d_va.pk_address)
                     )
               )

            JOIN dem.address_type d_at
              ON (
                     (d_lpoa.id_type = d_at.id)
               )
         )

      JOIN dem.v_all_persons d_vp
        ON (
               (d_lpoa.id_identity = d_vp.pk_identity)
         )
    );

Index - Schema dem

## View: dem.v_person_comms

denormalizes persons to communications channels

dem.v_person_comms Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT li2c.fk_identity AS pk_identity
    ,
        ect.description AS comm_type
    ,
        _
    (ect.description) AS l10n_comm_type
    ,
        li2c.url
    ,
        li2c.is_confidential
    ,
        li2c.comment
    ,
        li2c.pk AS pk_lnk_identity2comm
    ,
        li2c.fk_address AS pk_address
    ,
        li2c.fk_type AS pk_type
    ,
        li2c.xmin AS xmin_lnk_identity2comm

    FROM dem.lnk_identity2comm li2c
    ,
        dem.enum_comm_types ect

    WHERE (li2c.fk_type = ect.pk);

Index - Schema dem

## View: dem.v_person_jobs

denormalizes the jobs a person has

dem.v_person_jobs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT lj2p.fk_identity AS pk_identity
    ,
        o.name AS occupation
    ,
        _
    (o.name) AS l10n_occupation
    ,
        lj2p.activities
    ,
        lj2p.modified_when
    ,
        lj2p.fk_occupation AS pk_occupation
    ,
        lj2p.pk AS pk_lnk_job2person
    ,
        lj2p.xmin AS xmin_lnk_job2person

    FROM (dem.lnk_job2person lj2p

      JOIN dem.occupation o
        ON (
               (lj2p.fk_occupation = o.id)
         )
    );

Index - Schema dem

## View: dem.v_person_names

dem.v_person_names Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_i.pk AS pk_identity
    ,
        d_n.active AS active_name
    ,
        d_i.title
    ,
        d_n.firstnames
    ,
        d_n.lastnames
    ,
        d_n.preferred
    ,
        d_n.comment
    ,
        d_i.comment AS comment_identity
    ,
        d_i.gender
    ,
        d_i.dob
    ,
        d_i.tob
    ,
        d_i.deceased AS dod
    ,
        d_i.deleted AS identity_deleted
    ,

    (d_i.deceased IS NOT NULL) AS deceased
    ,
        d_n.id AS pk_name
    ,
        d_n.xmin AS xmin_name

    FROM (dem.names d_n

      JOIN dem.identity d_i
        ON (
               (d_n.id_identity = d_i.pk)
         )
    )

    WHERE (d_i.pk = d_n.id_identity);

Index - Schema dem

## View: dem.v_persons

This view denormalizes persons with their active name.

dem.v_persons Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT i.pk AS pk_identity
    ,
        i.title
    ,
        n.firstnames
    ,
        n.preferred
    ,
        n.lastnames
    ,
        i.gender
    ,
        _
    (i.gender) AS l10n_gender
    ,
        i.dob AS dob_only
    ,

    (date_trunc
         ('day'::text
               , i.dob
         ) +
         (COALESCE
               (i.tob
                     , (i.dob)::time without time zone
               )
         )::interval
    ) AS dob
    ,
        i.tob
    ,
        i.deceased
    ,
            CASE
                WHEN
    (i.fk_marital_status IS NULL) THEN 'unknown'::text
                ELSE
    (
    SELECT ms.name

      FROM dem.marital_status ms
         ,
                    dem.identity i1

     WHERE (
               (ms.pk = i.fk_marital_status)
             AND (i1.pk = i.pk)
         )
    )
            END AS marital_status
    ,
            CASE
                WHEN
    (i.fk_marital_status IS NULL) THEN _
    ('unknown'::text)
                ELSE
    (
    SELECT _
         (ms1.name) AS _

      FROM dem.marital_status ms1
         ,
                    dem.identity i1

     WHERE (
               (ms1.pk = i.fk_marital_status)
             AND (i1.pk = i.pk)
         )
    )
            END AS l10n_marital_status
    ,
        i.emergency_contact
    ,
        i.comment
    ,
        i.deleted AS is_deleted
    ,
        i.fk_marital_status AS pk_marital_status
    ,
        n.id AS pk_active_name
    ,
        i.fk_emergency_contact AS pk_emergency_contact
    ,
        i.fk_primary_provider AS pk_primary_provider
    ,
        i.xmin AS xmin_identity
    ,
        i.dob_is_estimated

    FROM dem.identity i
    ,
        dem.names n

    WHERE (
         (n.active IS TRUE)
       AND (n.id_identity = i.pk)
    );

Index - Schema dem

## View: dem.v_praxis_branches

Denormalized praxis branches with their praxis.

dem.v_praxis_branches Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT branches_w_orgs.pk_praxis_branch
    ,
        branches_w_orgs.branch
    ,
        branches_w_orgs.pk_org_unit
    ,
        branches_w_orgs.pk_category_unit
    ,
        branches_w_orgs.pk_address
    ,
        branches_w_orgs.pk_org
    ,
        branches_w_orgs.xmin_praxis_branch
    ,
        branches_w_orgs.xmin_org_unit
    ,
        branches_w_orgs.praxis
    ,
        branches_w_orgs.pk_category_org
    ,
        d_ocat.description AS organization_category
    ,
        _
    (d_ocat.description) AS l10n_organization_category
    ,
        d_ucat.description AS unit_category
    ,
        _
    (d_ucat.description) AS l10n_unit_category

    FROM (
         (
               (
                SELECT branches_w_units.pk_praxis_branch
                     ,
                branches_w_units.branch
                     ,
                branches_w_units.pk_org_unit
                     ,
                branches_w_units.pk_category_unit
                     ,
                branches_w_units.pk_address
                     ,
                branches_w_units.pk_org
                     ,
                branches_w_units.xmin_praxis_branch
                     ,
                branches_w_units.xmin_org_unit
                     ,
                d_o.description AS praxis
                     ,
                d_o.fk_category AS pk_category_org

                  FROM (
                           (
                            SELECT d_pb.pk AS pk_praxis_branch
                                 ,
                        d_ou.description AS branch
                                 ,
                        d_pb.fk_org_unit AS pk_org_unit
                                 ,
                        d_ou.fk_category AS pk_category_unit
                                 ,
                        d_ou.fk_address AS pk_address
                                 ,
                        d_ou.fk_org AS pk_org
                                 ,
                        d_pb.xmin AS xmin_praxis_branch
                                 ,
                        d_ou.xmin AS xmin_org_unit

                              FROM (dem.praxis_branch d_pb

                                    JOIN dem.org_unit d_ou
                                      ON (
                                             (d_pb.fk_org_unit = d_ou.pk)
                                       )
                                 )
                           ) branches_w_units

                        JOIN dem.org d_o
                          ON (
                                 (d_o.pk = branches_w_units.pk_org)
                           )
                     )
               ) branches_w_orgs

       LEFT JOIN dem.org_category d_ucat
              ON (
                     (branches_w_orgs.pk_category_unit = d_ucat.pk)
               )
         )

    LEFT JOIN dem.org_category d_ocat
        ON (
               (branches_w_orgs.pk_category_org = d_ocat.pk)
         )
    );

Index - Schema dem

## View: dem.v_region

denormalizes region information

dem.v_region Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_r.pk AS pk_region
    ,
        d_r.code AS code_region
    ,
        d_r.name AS region
    ,
        _
    (d_r.name) AS l10n_region
    ,
        d_r.country AS code_country
    ,
        c.name AS country
    ,
        _
    (c.name) AS l10n_country
    ,
        c.deprecated AS country_deprecated
    ,
        d_r.xmin AS xmin_region

    FROM (dem.region d_r

    LEFT JOIN dem.country c
        ON (
               (d_r.country = c.code)
         )
    );

Index - Schema dem

## View: dem.v_staff

Denormalized staff data.

dem.v_staff Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_vp.pk_identity
    ,
        d_s.pk AS pk_staff
    ,
        d_vp.title
    ,
        d_vp.firstnames
    ,
        d_vp.lastnames
    ,
        d_s.short_alias
    ,
            CASE
                WHEN
    (
    SELECT (EXISTS
               (
                SELECT 1

                  FROM pg_group

                 WHERE (
                           (pg_group.groname = 'gm-doctors'::name)
                         AND (
                                 (
                                  SELECT pg_user.usesysid

                                    FROM pg_user

                                   WHERE (pg_user.usename = d_s.db_user)
                                 ) = ANY
                                 (pg_group.grolist)
                           )
                     )
               )
         ) AS "exists"
    ) THEN 'full clinical access'::text
                WHEN
    (
    SELECT (EXISTS
               (
                SELECT 1

                  FROM pg_group

                 WHERE (
                           (pg_group.groname = 'gm-nurses'::name)
                         AND (
                                 (
                                  SELECT pg_user.usesysid

                                    FROM pg_user

                                   WHERE (pg_user.usename = d_s.db_user)
                                 ) = ANY
                                 (pg_group.grolist)
                           )
                     )
               )
         ) AS "exists"
    ) THEN 'limited clinical access'::text
                WHEN
    (
    SELECT (EXISTS
               (
                SELECT 1

                  FROM pg_group

                 WHERE (
                           (pg_group.groname = 'gm-staff'::name)
                         AND (
                                 (
                                  SELECT pg_user.usesysid

                                    FROM pg_user

                                   WHERE (pg_user.usename = d_s.db_user)
                                 ) = ANY
                                 (pg_group.grolist)
                           )
                     )
               )
         ) AS "exists"
    ) THEN 'non-clinical access'::text
                WHEN
    (
    SELECT (EXISTS
               (
                SELECT 1

                  FROM pg_group

                 WHERE (
                           (pg_group.groname = 'gm-public'::name)
                         AND (
                                 (
                                  SELECT pg_user.usesysid

                                    FROM pg_user

                                   WHERE (pg_user.usename = d_s.db_user)
                                 ) = ANY
                                 (pg_group.grolist)
                           )
                     )
               )
         ) AS "exists"
    ) THEN 'public access'::text
                ELSE NULL::text
            END AS role
    ,
        d_vp.dob
    ,
        d_vp.gender
    ,
        d_s.db_user
    ,
        d_s.comment
    ,
        d_s.is_active
    ,
        d_vp.is_deleted AS person_is_deleted
    ,

    (
    SELECT (
               (
                SELECT (EXISTS
                           (
                            SELECT 1

                              FROM pg_group

                             WHERE (
                                       (
                                             (
                                              SELECT pg_user.usesysid

                                                FROM pg_user

                                               WHERE (pg_user.usename = d_s.db_user)
                                             ) = ANY
                                             (pg_group.grolist)
                                       )
                                     AND (pg_group.groname = current_database
                                             ()
                                       )
                                 )
                           )
                     ) AS "exists"
               )
             AND (
                SELECT (EXISTS
                           (
                            SELECT 1

                              FROM pg_group

                             WHERE (
                                       (
                                             (
                                              SELECT pg_user.usesysid

                                                FROM pg_user

                                               WHERE (pg_user.usename = d_s.db_user)
                                             ) = ANY
                                             (pg_group.grolist)
                                       )
                                     AND (pg_group.groname = 'gm-logins'::name)
                                 )
                           )
                     ) AS "exists"
               )
         )
    ) AS can_login
    ,
        d_s.xmin AS xmin_staff

    FROM (dem.staff d_s

      JOIN dem.v_all_persons d_vp
        ON (
               (d_s.fk_identity = d_vp.pk_identity)
         )
    );

Index - Schema dem

## View: dem.v_street

denormalizes street data

dem.v_street Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_st.id AS pk_street
    ,
        d_st.name AS street
    ,
        COALESCE
    (d_st.postcode
         , d_vu.postcode_urb
    ) AS postcode
    ,
        d_st.postcode AS postcode_street
    ,
        d_st.lat_lon AS lat_lon_street
    ,
        d_st.suburb
    ,
        d_vu.urb
    ,
        d_vu.postcode_urb
    ,
        d_vu.lat_lon_urb
    ,
        d_vu.code_region
    ,
        d_vu.region
    ,
        d_vu.l10n_region
    ,
        d_vu.code_country
    ,
        d_vu.country
    ,
        d_vu.l10n_country
    ,
        d_vu.country_deprecated
    ,
        d_st.id_urb AS pk_urb
    ,
        d_vu.pk_region
    ,
        d_st.xmin AS xmin_street

    FROM (dem.street d_st

    LEFT JOIN dem.v_urb d_vu
        ON (
               (d_st.id_urb = d_vu.pk_urb)
         )
    );

Index - Schema dem

## View: dem.v_uniq_zipped_urbs

convenience view that selects urbs which: - have a zip code - are not referenced in table "street" with that zip code

dem.v_uniq_zipped_urbs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_u.postcode
    ,
        d_u.name
    ,
        d_r.name AS region
    ,
        d_r.code AS code_region
    ,
        d_c.name AS country
    ,
        _
    (d_c.name) AS l10n_country
    ,
        d_r.country AS code_country

    FROM dem.urb d_u
    ,
        dem.region d_r
    ,
        dem.country d_c

    WHERE (
         (d_u.postcode IS NOT NULL)
       AND (NOT
               (EXISTS
                     (
                      SELECT 1

                        FROM dem.v_zip2street d_vz2str

                       WHERE (
                                 (d_vz2str.postcode = d_u.postcode)
                               AND (d_vz2str.urb = d_u.name)
                           )
                     )
               )
         )
       AND (d_u.fk_region = d_r.pk)
       AND (d_r.country = d_c.code)
    );

Index - Schema dem

## View: dem.v_urb

denormalizes urb data

dem.v_urb Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_u.id AS pk_urb
    ,
        d_u.name AS urb
    ,
        d_u.postcode AS postcode_urb
    ,
        d_u.lat_lon AS lat_lon_urb
    ,
        d_vr.code_region
    ,
        d_vr.region
    ,
        d_vr.l10n_region
    ,
        d_vr.code_country
    ,
        d_vr.country
    ,
        d_vr.l10n_country
    ,
        d_vr.country_deprecated
    ,
        d_u.fk_region AS pk_region
    ,
        d_u.xmin AS xmin_urb

    FROM (dem.urb d_u

    LEFT JOIN dem.v_region d_vr
        ON (
               (d_vr.pk_region = d_u.fk_region)
         )
    );

Index - Schema dem

## View: dem.v_zip2data

aggregates nearly all known data per zip code

dem.v_zip2data Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_vz2s.postcode AS zip
    ,
        d_vz2s.street
    ,
        d_vz2s.suburb
    ,
        d_vz2s.urb
    ,
        d_vz2s.region
    ,
        d_vz2s.code_region
    ,
        d_vz2s.country
    ,
        d_vz2s.l10n_country
    ,
        d_vz2s.code_country

    FROM dem.v_zip2street d_vz2s

    UNION

    SELECT d_vuzu.postcode AS zip
    ,
        NULL::text AS street
    ,
        NULL::text AS suburb
    ,
        d_vuzu.name AS urb
    ,
        d_vuzu.region
    ,
        d_vuzu.code_region
    ,
        d_vuzu.country
    ,
        d_vuzu.l10n_country
    ,
        d_vuzu.code_country

    FROM dem.v_uniq_zipped_urbs d_vuzu;

Index - Schema dem

## View: dem.v_zip2street

list known data for streets that have a zip code

dem.v_zip2street Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT COALESCE
    (d_str.postcode
         , d_u.postcode
    ) AS postcode
    ,
        d_str.name AS street
    ,
        d_str.suburb
    ,
        d_r.name AS region
    ,
        d_r.code AS code_region
    ,
        d_u.name AS urb
    ,
        d_c.name AS country
    ,
        _
    (d_c.name) AS l10n_country
    ,
        d_r.country AS code_country

    FROM dem.street d_str
    ,
        dem.urb d_u
    ,
        dem.region d_r
    ,
        dem.country d_c

    WHERE (
         (d_str.postcode IS NOT NULL)
       AND (d_str.id_urb = d_u.id)
       AND (d_u.fk_region = d_r.pk)
       AND (d_r.country = d_c.code)
    );

Index - Schema dem

## View: dem.v_zip2urb

list known data for urbs that have a zip code

dem.v_zip2urb Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT d_u.postcode
    ,
        d_u.name AS urb
    ,
        d_r.name AS region
    ,
        d_r.code AS code_region
    ,
        _
    (d_c.name) AS country
    ,
        d_r.country AS code_country

    FROM dem.urb d_u
    ,
        dem.region d_r
    ,
        dem.country d_c

    WHERE (
         (d_u.postcode IS NOT NULL)
       AND (d_u.fk_region = d_r.pk)
       AND (d_r.country = d_c.code)
    );

Index - Schema dem

## Function: dem.add_external_id_type(text, text)

### Returns: integer

### Language: PLPGSQL

Add an external ID type if it does not exist yet. This implementation is prone to concurrency issues.

    declare
    	_name alias for $1;
    	_issuer alias for $2;
    	_pk int;
    begin
    	select pk into _pk from dem.enum_ext_id_types where name = _name and issuer = _issuer;
    	if FOUND then
    		return _pk;
    	end if;
    	insert into dem.enum_ext_id_types(name, issuer) values (_name, _issuer);
    	select currval(pg_get_serial_sequence('dem.enum_ext_id_types', 'pk')) into _pk;
    	return _pk;
    end;

## Function: dem.add_name(integer, text, text, boolean)

### Returns: integer

### Language: PLPGSQL

    DECLARE
    	_id_identity alias for $1;
    	_first alias for $2;
    	_last alias for $3;
    	_active alias for $4;
    	_id integer;
    BEGIN
        -- deactivate all the existing names if this name is to become active
    	if _active then
    		update dem.names set active = false where id_identity = _id_identity;
    	end if;
    	-- name already there for this identity ?
    	select into _id id from dem.names where id_identity = _id_identity and firstnames = _first and lastnames = _last;
    	if FOUND then
    		update dem.names set active = _active where id = _id;
    		return _id;
    	end if;
    	-- no, insert new name
    	insert into dem.names (id_identity, firstnames, lastnames, active) values (_id_identity, _first, _last, _active);
    	if FOUND then
    		return currval('dem.names_id_seq');
    	end if;
    	return NULL;
    END;

## Function: dem.address_exists(text, text, text, text, text, text, text)

### Returns: integer

### Language: PLPGSQL

This function checks whether a given address exists in the database and returns the primary key if found. It takes the following parameters: country code, region code, urb (location), postcode, street, number, subunit (can be NULL)

    DECLARE
    	_code_country alias for $1;
    	_code_region alias for $2;
    	_urb alias for $3;
    	_postcode alias for $4;
    	_street alias for $5;
    	_number alias for $6;
    	_subunit alias for $7;
    	__subunit text;
    	_pk_address integer;
    	msg text;
    BEGIN
    	if (_code_country || _code_region || _urb || _postcode || _street || _number) is NULL then
    		msg := '[dem.address_exists]: insufficient or invalid address definition: '
    			|| 'country code <' || coalesce(_code_country, 'NULL') || '>, '
    			|| 'region code <' || coalesce(_code_region, 'NULL') || '>, '
    			|| 'urb <' || coalesce(_urb, 'NULL') || '>, '
    			|| 'zip <' || coalesce(_postcode, 'NULL') || '>, '
    			|| 'street <' || coalesce(_street, 'NULL') || '>, '
    			|| 'number <' || coalesce(_number, 'NULL') || '>'
    		;
    		raise exception '%', msg;
    	end if;
    	__subunit := nullif(trim(_subunit), '');
    	if __subunit is null then
    		select
    			pk_address into _pk_address
    		from
    			dem.v_address
    		where
    			code_country = trim(_code_country)
    				and
    			code_region = trim(_code_region)
    				and
    			urb = trim(_urb)
    				and
    			postcode = trim(_postcode)
    				and
    			street = trim(_street)
    				and
    			number = trim(_number)
    				and
    			subunit is null;
    	else
    		select
    			pk_address into _pk_address
    		from
    			dem.v_address
    		where
    			code_country = trim(_code_country)
    				and
    			code_region = trim(_code_region)
    				and
    			urb = trim(_urb)
    				and
    			postcode = trim(_postcode)
    				and
    			street = trim(_street)
    				and
    			number = trim(_number)
    				and
    			subunit = __subunit;
    	end if;
    	return _pk_address;
    END;

## Function: dem.assert_unique_named_identity()

### Returns: trigger

### Language: PLPGSQL

Ensures unique(identity.dob, names.firstnames, names.lastnames, identity.comment)

    DECLARE
    	_identity_row record;
    	_names_row record;
    	_other_identities integer[];
    BEGIN
    	-- working on dem.identity
    	if TG_TABLE_NAME = 'identity' then
    		_identity_row := NEW;
    		select * into _names_row from dem.names where id_identity = NEW.pk;
    	-- working on dem.names
    	else
    		select * into _identity_row from dem.identity where pk = NEW.id_identity;
    		_names_row := NEW;
    	end if;
    	-- there cannot be any combination of identical
    	-- (dob, firstname, lastname, identity.comment)
    	-- so, look for clashing rows
    	SELECT array_agg(pk_identity) INTO _other_identities FROM
    		dem.v_person_names d_vpn
    			join dem.identity d_i on (d_i.pk = d_vpn.pk_identity)
    	WHERE
    		-- same firstname
    		d_vpn.firstnames = _names_row.firstnames
    			AND
    		-- same lastname
    		d_vpn.lastnames = _names_row.lastnames
    			AND
    		-- same gender
    		d_i.gender is not distinct from _identity_row.gender
    			AND
    		-- same dob (day)
    		date_trunc('day', d_i.dob) is not distinct from date_trunc('day', _identity_row.dob)
    			AND
    		-- same discriminator
    		d_i.comment is not distinct from _identity_row.comment
    			AND
    		-- but not the currently updated or inserted row
    		d_i.pk != _identity_row.pk
    	;
    	if coalesce(array_length(_other_identities, 1), 0) > 0 then
    		RAISE EXCEPTION
    			'[dem.assert_unique_named_identity] % on %.%: More than one person with (firstnames=%), (lastnames=%), (dob=%), (comment=%): % & %',
    				TG_OP,
    				TG_TABLE_SCHEMA,
    				TG_TABLE_NAME,
    				_names_row.firstnames,
    				_names_row.lastnames,
    				_identity_row.dob,
    				_identity_row.comment,
    				_identity_row.pk,
    				_other_identities
    			USING ERRCODE = 'unique_violation'
    		;
    		RETURN NULL;
    	end if;
    	return NEW;
    END;

## Function: dem.create_address(text, text, text, text, text, text, text)

### Returns: integer

### Language: PLPGSQL

This function creates an address. It first checks whether the address already exists. It takes the following parameters: number, street, postcode, urb (location), region code, country code, subunit (can be NULL) If the country or the region do not exist in the database, the function fails.

    DECLARE
    	_number ALIAS FOR $1;
    	_street ALIAS FOR $2;
    	_postcode ALIAS FOR $3;
    	_urb ALIAS FOR $4;
    	_region_code ALIAS FOR $5;
    	_country_code ALIAS FOR $6;
    	_subunit alias for $7;
    	_street_id integer;
    	_pk_address integer;
    	__subunit text;
    	msg text;
    BEGIN
    	select into _pk_address dem.address_exists (
    		_country_code,
    		_region_code,
    		_urb,
    		_postcode,
    		_street,
    		_number,
    		_subunit
    	);
    	if _pk_address is not null then
    		return _pk_address;
    	end if;
    	-- this either creates dem.street and possible dem.urb rows or
    	-- or else it fails (because region and/or country do not exist)
    	select into _street_id dem.create_street(_street, _postcode, _urb, _region_code, _country_code);
    	-- create address
    	__subunit := nullif(trim(_subunit), '');
    	insert into dem.address (
    		number,
    		id_street,
    		subunit
    	) values (
    		_number,
    		_street_id,
    		__subunit
    	)
    	returning id
    	into _pk_address;
    	return _pk_address;
    END;

## Function: dem.create_comm_type(text)

### Returns: integer

### Language: PLPGSQL

    DECLARE
    	_description alias for $1;
    	_pk_type integer;
    BEGIN
    	select pk into _pk_type from dem.enum_comm_types where _(description) = _description;
    	if FOUND then
    		return _pk_type;
    	end if;
    	select pk into _pk_type from dem.enum_comm_types where description = _description;
    	if FOUND then
    		return _pk_type;
    	end if;
    	insert into dem.enum_comm_types(description) values (_description);
    	select currval(pg_get_serial_sequence('dem.enum_comm_types', 'pk')) into _pk_type;
    	return _pk_type;
    END;

## Function: dem.create_occupation(text)

### Returns: integer

### Language: PLPGSQL

    DECLARE
    	_job alias for $1;
    	_id integer;
    BEGIN
    	select into _id id from dem.occupation where name = _job;
    	if FOUND then
    		return _id;
    	end if;
    	insert into dem.occupation (name) values (_job);
    	return currval('dem.occupation_id_seq');
    END;

## Function: dem.create_street(text, text, text, text, text)

### Returns: integer

### Language: PLPGSQL

This function takes a parameters the name of the street, the postal code, the name of the urb, the postcode of the urb, the code of the state and the code of the country. If the country or the state does not exists in the tables, the function fails. At first, both the urb and street are tried to be retrieved according to the supplied information. If the fields do not match exactly an existing row, a new urb is created or a new street is created and returned.

    DECLARE
    	_street ALIAS FOR $1;
    	_postcode ALIAS FOR $2;
    	_urb ALIAS FOR $3;
    	_state_code ALIAS FOR $4;
    	_country_code ALIAS FOR $5;
    	_urb_id integer;
    	_street_id integer;
    	msg text;
    BEGIN
    	-- create/get urb
    	SELECT INTO _urb_id dem.create_urb(_urb, _postcode, _state_code, _country_code);
    	-- create/get and return street
    	SELECT INTO _street_id s.id from dem.street s WHERE s.name ILIKE _street AND s.id_urb = _urb_id AND postcode ILIKE _postcode;
    	IF FOUND THEN
    		RETURN _street_id;
    	END IF;
    	INSERT INTO dem.street (name, postcode, id_urb) VALUES (_street, _postcode, _urb_id);
    	RETURN currval('dem.street_id_seq');
    END;

## Function: dem.create_urb(text, text, text, text)

### Returns: integer

### Language: PLPGSQL

This function takes a parameters the name of the urb,\n the postcode of the urb, the name of the region and the\n name of the country.\n If the country or the region does not exists in the tables,\n the function fails.\n At first, the urb is tried to be retrieved according to the\n supplied information. If the fields do not match exactly an\n existing row, a new urb is created and returned.

    DECLARE
    	_urb ALIAS FOR $1;
    	_urb_postcode ALIAS FOR $2;
    	_region_code ALIAS FOR $3;
    	_country_code ALIAS FOR $4;
     	_region_pk integer;
    	_urb_id integer;
    	msg text;
    BEGIN
     	-- get region
     	SELECT INTO _region_pk d_r.pk from dem.region d_r WHERE d_r.code = _region_code and d_r.country = _country_code;
     	IF NOT FOUND THEN
    		msg := 'combination of region + country not registered ['
    			||   'country:' || coalesce(_country_code, 'NULL')
    			||  ', region:' || coalesce(_region_code, 'NULL')
    			||     ', urb:' || coalesce(_urb, 'NULL')
    			|| ', urb_zip:' || coalesce(_urb_postcode, 'NULL')
    			|| ']';
    		RAISE EXCEPTION '=> %', msg;
     	END IF;
    	-- get/create and return urb
    	SELECT INTO _urb_id u.id from dem.urb u WHERE u.name ILIKE _urb AND u.fk_region = _region_pk;
    	IF FOUND THEN
    		RETURN _urb_id;
    	END IF;
    	INSERT INTO dem.urb (name, postcode, fk_region) VALUES (_urb, _urb_postcode, _region_pk);
    	RETURN currval('dem.urb_id_seq');
    END;

## Function: dem.date_trunc_utc(text, timestamp with time zone)

### Returns: timestamp without time zone

### Language: SQL

date_trunc() is not immutable because it depends on the timezone setting, hence need to use this in index creation, but also need to use it in queries which want to use that index, so make it generally available as a function

    select date_trunc($1, $2 at time zone 'UTC');

## Function: dem.dob_is_in_range(timestamp with time zone, interval, interval)

### Returns: boolean

### Language: SQL

    select
    	($1 - (extract(year from $1) * '1 year'::interval)) -
    	(now() - (extract(year from now()) * '1 year'::interval))
    	between (-1 * $2) and $3

## Function: dem.f_always_active_name()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	if NEW.active = false then
    		raise exception 'Cannot delete/disable active name. Another name must be activated first.';
    		return OLD;
    	end if;
    	return NEW;
    END;

## Function: dem.f_delete_names()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    BEGIN
    	DELETE from dem.names WHERE id_identity=OLD.id;
    	RETURN OLD;
    END;

## Function: dem.f_uniq_active_name()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    --	tmp text;
    BEGIN
    --	tmp := 'identity:' || NEW.id_identity || ',id:' || NEW.id || ',name:' || NEW.firstnames || ' ' || NEW.lastnames;
    --	raise notice 'uniq_active_name: [%]', tmp;
    	if NEW.active = true then
    		update dem.names set active = false
    		where
    			id_identity = NEW.id_identity
    				and
    			active = true;
    	end if;
    	return NEW;
    END;

## Function: dem.gm_upd_default_regions()

### Returns: boolean

### Language: PLPGSQL

    declare
    	_region_code text;
    	_region_name text;
    	_country_row record;
    begin
    	_region_code := '??';
    	_region_name := 'state/territory/province/region not available';
    	-- add default region to countries needing one
    	for _country_row in
    		select distinct code from dem.country
    		where code not in (
    			select country from dem.region where code = _region_code
    		)
    	loop
    		raise notice 'adding default region for [%]', _country_row.code;
    		execute 'insert into dem.region (code, country, name) values ('
    				|| quote_literal(_region_code) || ', '
    				|| quote_literal(_country_row.code) || ', '
    				|| quote_literal(_region_name) || ');';
    	end loop;
    	return true;
    end;

## Function: dem.remove_person(integer)

### Returns: boolean

### Language: PLPGSQL

Fully remove a person from the system - except everything is still in the audit tables ;-)

    DECLARE
    	_pk_identity alias for $1;
    BEGIN
    	-- does person exist ?
    	perform 1 from dem.identity where pk = _pk_identity;
    	if not FOUND then
    		raise notice 'dem.remove_person(): dem.identity.pk=(%) does not exist, not removing', _pk_identity;
    		return false;
    	end if;
    	-- we cannot just get the child tables of clin.clin_root_item and
    	-- delete from them since they are inter-dependent and may require
    	-- a particular order of deletion, so let us do that explicitely:
    	DELETE FROM clin.clin_hx_family WHERE fk_encounter IN (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.vaccination WHERE fk_encounter IN (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.allergy WHERE fk_encounter IN (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.allergy_state WHERE fk_encounter IN (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.clin_diag WHERE fk_narrative IN (
    		SELECT pk FROM clin.clin_narrative WHERE fk_encounter IN (
    			select pk from clin.encounter where fk_patient = _pk_identity
    		)
    	);
    	DELETE FROM clin.test_result WHERE fk_encounter IN (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.lab_request WHERE fk_encounter in (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.substance_intake WHERE fk_encounter IN (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.procedure WHERE fk_encounter IN (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.clin_narrative WHERE fk_encounter IN (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM blobs.doc_med WHERE fk_encounter IN (
    		select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	-- now that we have deleted all the clinical data let us
    	-- delete the EMR structural items as well:
    	DELETE FROM clin.episode WHERE fk_encounter IN (
    	    select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.health_issue WHERE fk_encounter IN (
    	    select pk from clin.encounter where fk_patient = _pk_identity
    	);
    	DELETE FROM clin.encounter WHERE fk_patient = _pk_identity;
    	-- delete demographics details:
    	DELETE FROM dem.identity_tag where fk_identity = _pk_identity;
    	DELETE FROM dem.names WHERE id_identity = _pk_identity;
    	-- eventually delete the identity itself which does
    	-- not go down without some twisting of arms:
    	ALTER TABLE dem.identity disable rule r_del_identity;
    	DELETE FROM dem.identity WHERE pk = _pk_identity;
    	ALTER TABLE dem.identity enable rule r_del_identity;
    	return true;
    END;

## Function: dem.set_nickname(integer, text)

### Returns: integer

### Language: PLPGSQL

Setting the nickname only makes sense for the currently active name. However, we also want to keep track of previous nicknames. Hence we would set the nickname right in the active name if it is NULL. It it contains a previous nickname (eg IS NOT NULL) we will inactivate the currently active name and copy it into a new active name but with the nickname set to the new one. Unsetting works the same (IOW *setting* to NULL).

    DECLARE
    	_id_identity alias for $1;
    	_nick alias for $2;
    	_names_row record;
    	msg text;
    BEGIN
    	-- 0.1: Just always set the nickname inside the active name
    	-- post 0.1: openEHR-like (name: pk, fk_identity, name, fk_type, comment, is_legal, is_active ...)
    	-- does name exist ?
    	select into _names_row * from dem.names where id_identity = _id_identity and active = true;
    	if not found then
    		msg := 'Cannot set nickname [' || _nick || ']. No active <names> row with id_identity [' || _id_identity || '] found.';
    		raise exception '%', msg;
    	end if;
    	update dem.names set preferred = _nick where id = _names_row.id;
    	return _names_row.id;
    END;

## Function: dem.trf_normalize_time_in_dob()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	if NEW.dob is NULL then
    		return NEW;
    	end if;
    	NEW.dob = date_trunc('day', NEW.dob) + '11 hours 11 minutes 11 seconds 111 milliseconds'::interval;
    	return NEW;
    END;

## Function: dem.trf_null_empty_title()

### Returns: trigger

### Language: PLPGSQL

    begin
    	if (NEW.title is null) then
    		return NEW;
    	end if;
    	if trim(NEW.title) <> '' then
    		return NEW;
    	end if;
    	NEW.title := NULL;
    	return NEW;
    end;

## Function: dem.trf_prevent_deletion_of_in_use_staff()

### Returns: trigger

### Language: PLPGSQL

this function is used to prevent DELETEs of staff members which had been used to store data

    BEGIN
    	-- does any audited table contain the dem.staff.db_user we are about to delete ?
    	PERFORM 1 FROM audit.audit_fields WHERE modified_by = OLD.db_user LIMIT 1;
    	IF FOUND THEN
    		RAISE EXCEPTION
    			'DELETE from dem.staff: Sanity check failed. User <%> is referenced from <.modified_by> of at least one audited table.', OLD.db_user
    			USING ERRCODE = 'foreign_key_violation'
    		;
    		RETURN NULL;
    	END IF;
    	-- does any audit table contain the dem.staff.db_user we are about to delete ?
    	PERFORM 1 FROM audit.audit_trail WHERE orig_by = OLD.db_user OR audit_by = OLD.db_user LIMIT 1;
    	IF FOUND THEN
    		RAISE EXCEPTION
    			'DELETE from dem.staff: Sanity check failed. User <%> is referenced from <.orig_by> or <.audit_by> of at least one audit table.', OLD.db_user
    			USING ERRCODE = 'foreign_key_violation'
    		;
    		RETURN NULL;
    	END IF;
    	RETURN OLD;
    END;

## Function: dem.trf_prevent_multiple_praxi()

### Returns: trigger

### Language: PLPGSQL

Prevent praxis branches to be defined for more than one dem.org.

    DECLARE
    	_branch_count integer;
    	_pk_org_existing integer;
    	_pk_org_prospective integer;
    	_msg text;
    BEGIN
    	select count(1) into _branch_count from dem.praxis_branch;
    	if TG_OP = 'INSERT' then
    		-- first branch ever
    		if _branch_count = 0 then
    			return NEW;
    		end if;
    	end if;
    	if TG_OP = 'UPDATE' then
    		-- only one branch (which is being updated)
    		if _branch_count = 1 then
    			return NEW;
    		end if;
    	end if;
    	-- now we have either got an INSERT with at least
    	-- one praxis_branch already existing or we are
    	-- UPDATEing one of several existing branches
    	SELECT fk_org INTO _pk_org_existing FROM dem.org_unit
    	WHERE pk = (SELECT fk_org_unit FROM dem.praxis_branch LIMIT 1);
    	SELECT fk_org INTO _pk_org_prospective
    	FROM dem.org_unit WHERE pk = NEW.fk_org_unit;
    	if _pk_org_prospective = _pk_org_existing then
    		return NEW;
    	end if;
    	_msg := '[dem.trf_prevent_multiple_praxi] '
    			|| TG_OP || ': '
    			|| 'Existing praxis branches (dem.praxis_branch.fk_org->dem.org_unit.pk->dem.org_unit.fk_org) belong to an org with dem.org.pk='
    			|| _pk_org_existing
    			|| '. Cannot link praxis branch (dem.praxis_branch.fk_org=dem.org_unit.pk='
    			|| NEW.fk_org_unit
    			||') to a different org (dem.org.pk='
    			|| _pk_org_prospective
    			||'). There can only be one praxis (=dem.org) per database.';
    	raise exception unique_violation using message = _msg;
    	return NULL;
    END;

## Function: dem.trf_protect_active_name_of_person()

### Returns: trigger

### Language: PLPGSQL

A person must have at least one, active, name record.

    DECLARE
    	_name_count integer;
    	_msg text;
    BEGIN
    	-- how many names are there for the identity at the end of the Tx ?
    	select count(1) into _name_count
    	from dem.names
    	where
    		id_identity = OLD.id_identity
    			and
    		active is true
    	;
    	-- less than one name ?
    	if _name_count < 1 then
    		_msg := 'person ' || OLD.id_identity || ' must have at least one, active, name entry';
    		raise exception check_violation using message = _msg;
    		return OLD;
    	end if;
    	return OLD;
    END;

# Schema gm

## Table: gm.access_log

This logs access to the database and to records. Needed for HIPAA compliance among other things.

gm.access_log Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

Table gm.access_log Inherits audit_fields,

gm.access_log Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
non_empty_user_action | CHECK ((gm.is_null_or_blank_string(user_action) IS FALSE))

Index - Schema gm

## Table: gm.notifying_tables

All tables that want to send standard notifications must be recorded in this table. Notification triggers will be generated automatically for all tables recorded here.

gm.notifying_tables Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

Index - Schema gm

## Table: gm.schema_revision

this table holds the revisions of all SQL scripts ever inserted into this database, the values are preferably provided by CVS tags in the scripts themselves, see above for a convenient way to do that

gm.schema_revision Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| version |  | UNIQUE#1
| filename |  | UNIQUE#1
| pk |  | PRIMARY KEY

Index - Schema gm

## Function: gm.account_is_dbowner_or_staff(_account name)

### Returns: boolean

### Language: PLPGSQL

    DECLARE
    	_is_owner boolean;
    BEGIN
    	-- is _account member of current db group ?
    --	PERFORM 1 FROM pg_auth_members
    --	WHERE
    --		roleid = (SELECT oid FROM pg_roles WHERE rolname = current_database())
    --			AND
    --		member = (SELECT oid FROM pg_roles WHERE rolname = _account)
    --	;
    --	IF FOUND THEN
    --		-- should catch people on staff, gm-dbo, and postgres
    --		RETURN TRUE;
    --	END IF;
    	-- postgres
    	IF _account = 'postgres' THEN
    		RETURN TRUE;
    	END IF;
    	-- on staff list
    	PERFORM 1 FROM dem.staff WHERE db_user = _account;
    	IF FOUND THEN
    		RETURN TRUE;
    	END IF;
    	-- owner
    	SELECT pg_catalog.pg_get_userbyid(datdba) = _account INTO STRICT _is_owner FROM pg_catalog.pg_database WHERE datname = current_database();
    	IF _is_owner IS TRUE THEN
    		RETURN TRUE;
    	END IF;
    	RETURN FALSE;
    END;

## Function: gm.add_missing_array_bits()

### Returns: boolean

### Language: PLPGSQL

Add array aggregate and array unnesting to PostgreSQL versions lacking this functionality (IOW < 8.4).

    DECLARE
    BEGIN
    	-- array_agg
    	perform 1 from pg_catalog.pg_aggregate where aggfnoid::oid = (select oid from pg_catalog.pg_proc where proname = 'array_agg'::name limit 1);
    	if FOUND then
    		raise NOTICE '[gm.add_missing_array_bits]: aggregate <array_agg> already exists';
    	else
    		raise NOTICE '[gm.add_missing_array_bits]: aggregate <array_agg> does not exist (probably PostgreSQL <8.4), creating';
    		CREATE AGGREGATE array_agg(anyelement) (
    			SFUNC = array_append,
    			STYPE = anyarray,
    			INITCOND = '{}'
    		);
    		comment on aggregate array_agg(anyelement) is
    			'Missing on PG 8.3, needed for vaccination handling starting with conversion from gnumed_v13 to gnumed_v14.';
    	end if;
    	-- unnest()
    	perform 1 from pg_catalog.pg_proc where
    		proname = 'array_unnest'::name
    			and
    		pronamespace = (select oid from pg_namespace where nspname = 'gm'::name)
    	;
    	if FOUND then
    		raise NOTICE '[gm.add_missing_array_bits]: function "gm.array_unnest()" already exists';
    	else
    		raise NOTICE '[gm.add_missing_array_bits]: function "gm.array_unnest()" does not exist, creating';
    		CREATE OR REPLACE FUNCTION gm.array_unnest(anyarray)
    			RETURNS SETOF anyelement
    			AS '
    		SELECT $1[i] FROM
    			generate_series (
    				array_lower($1,1),
    				array_upper($1,1)
    			) i
    		;'
    			LANGUAGE 'sql'
    			IMMUTABLE
    		;
    		comment on function gm.array_unnest(anyarray) is
    			'Missing on PG 8.3, needed for vaccination handling starting with conversion from gnumed_v13 to gnumed_v14.';
    	end if;
    	perform 1 from pg_catalog.pg_proc where
    		proname = 'unnest'::name
    			and
    		pronamespace = (select oid from pg_namespace where nspname = 'pg_catalog'::name)
    	;
    	if FOUND then
    		raise NOTICE '[gm.add_missing_array_bits]: function "pg_catalog.unnest()" exists';
    		-- also exists in public ?
    		perform 1 from pg_catalog.pg_proc where
    			proname = 'unnest'::name
    				and
    			pronamespace = (select oid from pg_namespace where nspname = 'public'::name)
    		;
    		if FOUND then
    			raise NOTICE '[gm.add_missing_array_bits]: function "unnest()" also exists in schema "public", removing';
    			drop function public.unnest(anyarray) cascade;
    		end if;
    	else
    		raise NOTICE '[gm.add_missing_array_bits]: function "pg_catalog.unnest()" does not exist (probably PostgreSQL <8.4)';
    		-- exists in public ?
    		perform 1 from pg_catalog.pg_proc where
    			proname = 'unnest'::name
    				and
    			pronamespace = (select oid from pg_namespace where nspname = 'public'::name)
    		;
    		if FOUND then
    			raise NOTICE '[gm.add_missing_array_bits]: function "public.unnest()" already exists';
    		else
    			raise NOTICE '[gm.add_missing_array_bits]: function "public.unnest()" does not exist either, creating';
    			CREATE OR REPLACE FUNCTION public.unnest(anyarray)
    				RETURNS SETOF anyelement
    				AS 'SELECT gm.array_unnest($1);'
    				LANGUAGE 'sql'
    				IMMUTABLE
    			;
    			comment on function public.unnest(anyarray) is
    				'Missing on PG 8.3, needed for vaccination handling starting with conversion from gnumed_v13 to gnumed_v14.';
    		end if;
    	end if;
    	return TRUE;
    END;

## Function: gm.add_table_for_notifies(name, name)

### Returns: boolean

### Language: SQL

Mark given table for notification trigger generator. Parameters are: (schema, table). Defaults signal to table name.

    select gm.register_notifying_table($1, $2);

## Function: gm.add_user_to_permission_group(name, name)

### Returns: boolean

### Language: PLPGSQL

Only gm-dbo is GRANTed EXECUTE on this function. This way users need to know the gm-dbo (GNUmed admin) password to execute it.

    DECLARE
    	_username alias for $1;
    	_target_group alias for $2;
    	_valid_groups name[];
    	_group name;
    	_query text;
    BEGIN
    	-- verify user
    	perform 1 from pg_user where usename = _username;
    	if not FOUND then
    		raise warning '[gm.add_user_to_permission_group]: user [%] does not exist', _username;
    		return False;
    	end if;
    	-- verify logical group validity
    	-- no "gm-nurse", "gm-admin" just yet
    	_valid_groups := ARRAY[quote_ident('gm-public'), quote_ident('gm-staff'), quote_ident('gm-doctors')];
    	if quote_ident(_target_group) <> all(_valid_groups) then
    		raise warning '[gm.add_user_to_permission_group]: invalid group [%]', _target_group;
    		return False;
    	end if;
    	-- verify group existance
    	perform 1 from pg_group where groname = _target_group;
    	if not FOUND then
    		raise warning '[gm.add_user_to_permission_group]: group [%] does not exist', _target_group;
    		return False;
    	end if;
    	-- drop user from all groups
    	--FOREACH _group IN ARRAY _valid_groups LOOP
    	FOR _group IN SELECT unnest(_valid_groups) LOOP
    		_query := 'alter group ' || _group || ' drop user ' || quote_ident(_username) || ';';
    		execute _query;
    	END LOOP;
    	-- add user to desired group
    	_query := 'alter group ' || quote_ident(_target_group) || ' add user ' || quote_ident(_username) || ';';
    	execute _query;
    	return True;
    END;

## Function: gm.array_unnest(anyarray)

### Returns: SET OF anyelement

### Language: SQL

Missing on PG 8.3, needed for vaccination handling starting with conversion from gnumed_v13 to gnumed_v14.

    		SELECT $1[i] FROM
    			generate_series (
    				array_lower($1,1),
    				array_upper($1,1)
    			) i
    		;

## Function: gm.concat_table_structure()

### Returns: text

### Language: PLPGSQL

    declare
    	_struct text;
    begin
    	select into _struct gm.concat_table_structure_v19_and_up();
    	return _struct;
    end;

## Function: gm.concat_table_structure(integer)

### Returns: text

### Language: PLPGSQL

    declare
    	_db_ver alias for $1;
    	_struct text;
    begin
    	if _db_ver < 6 then
    		select into _struct gm.concat_table_structure_v1();
    		return _struct;
    	end if;
    	if _db_ver < 8 then
    		select into _struct gm.concat_table_structure_v2();
    		return _struct;
    	end if;
    	if _db_ver < 16 then
    		select into _struct gm.concat_table_structure_v3();
    		return _struct;
    	end if;
    	if _db_ver < 17 then
    		select into _struct gm.concat_table_structure_v16_and_up();
    		return _struct;
    	end if;
    	if _db_ver < 18 then
    		select into _struct gm.concat_table_structure_v17_and_up();
    		return _struct;
    	end if;
    	if _db_ver < 19 then
    		select into _struct gm.concat_table_structure_v18_and_up();
    		return _struct;
    	end if;
    	select into _struct gm.concat_table_structure_v19_and_up();
    	return _struct;
    end;

## Function: gm.concat_table_structure_v1()

### Returns: text

### Language: PLPGSQL

copy of gm_concat_table_structure() until gnumed_v5, works on public, dem, clin, blobs

    declare
    	_row record;
    	_total text;
    begin
    	_total := '';
    	-- schema.table.column.data_type
    	for _row in
    		select * from information_schema.columns cols
    			where cols.table_name in (
    				select tabs.table_name from information_schema.tables tabs where
    					-- those which hold clinical data
    					tabs.table_schema in ('public', 'dem', 'clin', 'blobs') and
    					tabs.table_type = 'BASE TABLE'
    				)
    			order by
    				md5(cols.table_schema || cols.table_name || cols.column_name || cols.data_type)
    	loop
    		_total := _total
    			|| _row.table_schema || '.'
    			|| _row.table_name || '.'
    			|| _row.column_name || '::'
    			|| _row.udt_name || '
    ';
    	end loop;
    	return _total;
    end;

## Function: gm.concat_table_structure_v16_and_up()

### Returns: text

### Language: PLPGSQL

new concat_table_structure() starting with gnumed_v16, works on dem, clin, blobs, cfg, ref, i18n, sorts properly by bytea

    declare
    	_row record;
    	_total text;
    begin
    	_total := '';
    	-- schema.table.column.data_type
    	for _row in
    		select *
    		from information_schema.columns cols
    		where
    			cols.table_name in (
    				select tabs.table_name from information_schema.tables tabs where
    					-- those which hold clinical data
    					tabs.table_schema in ('dem', 'clin', 'blobs', 'cfg', 'ref', 'i18n')
    						and
    					tabs.table_type = 'BASE TABLE'
    			) and
    			cols.table_schema in ('dem', 'clin', 'blobs', 'cfg', 'ref', 'i18n')
    		order by
    			decode(md5(cols.table_schema || cols.table_name || cols.column_name || cols.data_type), 'hex')
    	loop
    		_total := _total
    			|| _row.table_schema || '.'
    			|| _row.table_name || '.'
    			|| _row.column_name || '::'
    			|| _row.udt_name || E'
    ';
    	end loop;
    	return _total;
    end;

## Function: gm.concat_table_structure_v17_and_up()

### Returns: text

### Language: PLPGSQL

new concat_table_structure() starting with gnumed_v17, works on dem, clin, blobs, cfg, ref, i18n, bill, sorts properly by bytea

    declare
    	_row record;
    	_total text;
    begin
    	_total := '';
    	-- schema.table.column.data_type
    	for _row in
    		select *
    		from information_schema.columns cols
    		where
    			cols.table_name in (
    				select tabs.table_name from information_schema.tables tabs where
    					tabs.table_schema in ('dem', 'clin', 'blobs', 'cfg', 'ref', 'i18n', 'bill')
    						and
    					tabs.table_type = 'BASE TABLE'
    			) and
    			cols.table_schema in ('dem', 'clin', 'blobs', 'cfg', 'ref', 'i18n', 'bill')
    		order by
    			decode(md5(cols.table_schema || cols.table_name || cols.column_name || cols.data_type), 'hex')
    	loop
    		_total := _total
    			|| _row.table_schema || '.'
    			|| _row.table_name || '.'
    			|| _row.column_name || '::'
    			|| _row.udt_name || E'
    ';
    	end loop;
    	return _total;
    end;

## Function: gm.concat_table_structure_v18_and_up()

### Returns: text

### Language: PLPGSQL

new concat_table_structure() starting with gnumed_v18, works on dem, clin, blobs, cfg, ref, i18n, bill, includes primary keys, sorts properly by bytea

    declare
    	_table_desc record;
    	_pk_desc record;
    	_column_desc record;
    	_total text;
    begin
    	_total := '';
    	-- find relevant tables
    	for _table_desc in
    		select * from information_schema.tables tabs where
    			tabs.table_schema in ('dem', 'clin', 'blobs', 'cfg', 'ref', 'i18n', 'bill')
    				and
    			tabs.table_type = 'BASE TABLE'
    		order by
    			decode(md5(tabs.table_schema || tabs.table_name), 'hex')
    	-- loop over tables
    	loop
    		-- where are we at ?
    		_total := _total || 'TABLE:' || _table_desc.table_schema || '.' || _table_desc.table_name || E'
    ';
    		-- find PKs of that table
    		for _pk_desc in
    			select * from (
    				select
    					pg_class.oid::regclass || '.' || pg_attribute.attname || '::' || format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS primary_key_column
    				from
    					pg_index, pg_class, pg_attribute
    				where
    					--pg_class.oid = 'TABLENAME'::regclass
    					pg_class.oid = (_table_desc.table_schema || '.' || _table_desc.table_name)::regclass
    						AND
    					indrelid = pg_class.oid
    						AND
    					pg_attribute.attrelid = pg_class.oid
    						AND
    					pg_attribute.attnum = any(pg_index.indkey)
    						AND
    					indisprimary
    				) AS PKs
    			order by
    				decode(md5(PKs.primary_key_column), 'hex')
    		-- and loop over those PK columns
    		loop
    			_total := _total || 'PK:' || _pk_desc.primary_key_column	|| E'
    ';
    		end loop;
    		-- find columns of that table
    		for _column_desc in
    			select *
    			from information_schema.columns cols
    			where
    				cols.table_name = _table_desc.table_name
    					and
    				cols.table_schema = _table_desc.table_schema
    			order by
    				decode(md5(cols.column_name || cols.data_type), 'hex')
    		-- and loop over those columns
    		loop
    			-- add columns in the format "schema.table.column::data_type"
    			_total := _total || 'COL:'
    				|| _column_desc.table_schema || '.'
    				|| _column_desc.table_name || '.'
    				|| _column_desc.column_name || '::'
    				|| _column_desc.udt_name || E'
    ';
    		end loop;
    	end loop;
    	return _total;
    end;

## Function: gm.concat_table_structure_v19_and_up()

### Returns: text

### Language: PLPGSQL

new concat_table_structure() starting with gnumed_v19, works on dem, clin, blobs, cfg, ref, i18n, bill, includes primary keys and constraints, sorts properly by bytea

    declare
    	_table_desc record;
    	_pk_desc record;
    	_column_desc record;
    	_constraint_def record;
    	_total text;
    begin
    	_total := '';
    	-- find relevant tables
    	for _table_desc in
    		select * from information_schema.tables tabs where
    			tabs.table_schema in ('dem', 'clin', 'blobs', 'cfg', 'ref', 'i18n', 'bill')
    				and
    			tabs.table_type = 'BASE TABLE'
    		order by
    			decode(md5(tabs.table_schema || tabs.table_name), 'hex')
    	-- loop over tables
    	loop
    		-- where are we at ?
    		_total := _total || 'TABLE:' || _table_desc.table_schema || '.' || _table_desc.table_name || E'\n';
    		-- find PKs of that table
    		for _pk_desc in
    			select * from (
    				select
    					pg_class.oid::regclass || '.' || pg_attribute.attname || '::' || format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS primary_key_column
    				from
    					pg_index, pg_class, pg_attribute
    				where
    					--pg_class.oid = 'TABLENAME'::regclass
    					pg_class.oid = (_table_desc.table_schema || '.' || _table_desc.table_name)::regclass
    						AND
    					indrelid = pg_class.oid
    						AND
    					pg_attribute.attrelid = pg_class.oid
    						AND
    					pg_attribute.attnum = any(pg_index.indkey)
    						AND
    					indisprimary
    				) AS PKs
    			order by
    				decode(md5(PKs.primary_key_column), 'hex')
    		-- and loop over those PK columns
    		loop
    			_total := _total || 'PK:' || _pk_desc.primary_key_column	|| E'\n';
    		end loop;
    		-- find columns of that table
    		for _column_desc in
    			select *
    			from information_schema.columns cols
    			where
    				cols.table_name = _table_desc.table_name
    					and
    				cols.table_schema = _table_desc.table_schema
    			order by
    				decode(md5(cols.column_name || cols.data_type), 'hex')
    		-- and loop over those columns
    		loop
    			-- add columns in the format "schema.table.column::data_type"
    			_total := _total || 'COL:'
    				|| _column_desc.table_schema || '.'
    				|| _column_desc.table_name || '.'
    				|| _column_desc.column_name || '::'
    				|| _column_desc.udt_name || E'\n';
    		end loop;
    		-- find and loop over CONSTRAINTs of that table
    		for _constraint_def in
    			select * from
    				(select
    					tbl.contype,
    					'CONSTRAINT:type='
    						|| tbl.contype || ':'
    						|| replace(pg_catalog.pg_get_constraintdef(tbl.oid, true), ' ', '_')
    						|| '::active='
    						|| tbl.convalidated
    					 as condef
    				from pg_catalog.pg_constraint tbl
    				where
    					tbl.conrelid = (_table_desc.table_schema || '.' || _table_desc.table_name)::regclass
    					-- include FKs only because we may have to add/remove
    					-- other (say, check) constraints in a minor release
    					-- for valid reasons which we do not want to affect
    					-- the hash, if however we need to modify a foreign
    					-- key that would, indeed, warrant a hash change
    						AND
    					tbl.contype = 'f'
    				) as CONSTRAINTs
    			order by
    				CONSTRAINTs.contype,
    				decode(md5(CONSTRAINTs.condef), 'hex')
    		loop
    			_total := _total || _constraint_def.condef || E'\n';
    		end loop;
    	end loop;		-- over tables
    	return _total;
    end;

## Function: gm.concat_table_structure_v2()

### Returns: text

### Language: PLPGSQL

new concat_table_structure() starting with gnumed_v6, works on dem, clin, blobs, cfg, ref, i18n

    declare
    	_row record;
    	_total text;
    begin
    	_total := '';
    	-- schema.table.column.data_type
    	for _row in
    		select * from information_schema.columns cols
    			where cols.table_name in (
    				select tabs.table_name from information_schema.tables tabs where
    					-- those which hold clinical data
    					tabs.table_schema in ('dem', 'clin', 'blobs', 'cfg', 'ref', 'i18n') and
    					tabs.table_type = 'BASE TABLE'
    				)
    			order by
    				md5(cols.table_schema || cols.table_name || cols.column_name || cols.data_type)
    	loop
    		_total := _total
    			|| _row.table_schema || '.'
    			|| _row.table_name || '.'
    			|| _row.column_name || '::'
    			|| _row.udt_name || '
    ';
    	end loop;
    	return _total;
    end;

## Function: gm.concat_table_structure_v3()

### Returns: text

### Language: PLPGSQL

new concat_table_structure() starting with gnumed_v8, works on dem, clin, blobs, cfg, ref, i18n, sorts properly by bytea

    declare
    	_row record;
    	_total text;
    begin
    	_total := '';
    	-- schema.table.column.data_type
    	for _row in
    		select * from information_schema.columns cols
    			where cols.table_name in (
    				select tabs.table_name from information_schema.tables tabs where
    					-- those which hold clinical data
    					tabs.table_schema in ('dem', 'clin', 'blobs', 'cfg', 'ref', 'i18n') and
    					tabs.table_type = 'BASE TABLE'
    				)
    			order by
    				decode(md5(cols.table_schema || cols.table_name || cols.column_name || cols.data_type), 'hex')
    	loop
    		_total := _total
    			|| _row.table_schema || '.'
    			|| _row.table_name || '.'
    			|| _row.column_name || '::'
    			|| _row.udt_name || '
    ';
    	end loop;
    	return _total;
    end;

## Function: gm.create_all_enc_epi_sanity_check_triggers()

### Returns: boolean

### Language: PLPGSQL

(Re)create sanity check triggers for all tables which have both fk_encounter and fk_episode.

    DECLARE
    	_schema name;
    	_table name;
    	_qualified_table2check name;
    	_fk_encounter_col name;
    	_fk_episode_col name;
    	_total_success boolean;
    BEGIN
    	raise notice 'gm.create_all_enc_epi_sanity_check_triggers()';
    	_total_success := True;
    	-- loop over tables with encounter AND episode FKs
    	-- (assumes there is only one of each)
    	for _schema, _table in
    		select
    			(select pg_n.nspname from pg_catalog.pg_namespace pg_n where pg_n.oid = pg_c.relnamespace),
    			pg_c.relname
    		from pg_class pg_c
    		where pg_c.oid in (
    			select distinct fk_tbl.conrelid
    			from pg_catalog.pg_constraint fk_tbl
    			where
    				exists (
    					select 1 from pg_catalog.pg_constraint fk_tbl1
    					where
    						fk_tbl1.contype = 'f'
    							and
    						fk_tbl1.conrelid = fk_tbl.conrelid
    							and
    						fk_tbl1.confrelid = 'clin.encounter'::regclass
    							and
    						fk_tbl1.confkey[1] = (
    							select attnum from pg_catalog.pg_attribute col_tbl
    							where
    								col_tbl.attname = 'pk'
    									AND
    								col_tbl.attrelid = 'clin.encounter'::regclass
    						)
    				)
    					and
    				exists (
    					select 1 from pg_catalog.pg_constraint fk_tbl2
    					where
    						fk_tbl2.contype = 'f'
    							and
    						fk_tbl2.conrelid = fk_tbl.conrelid
    							and
    						fk_tbl2.confrelid = 'clin.episode'::regclass
    							and
    						fk_tbl2.confkey[1] = (
    							select attnum from pg_catalog.pg_attribute col_tbl
    							where
    								col_tbl.attname = 'pk'
    									AND
    								col_tbl.attrelid = 'clin.episode'::regclass
    						)
    				)
    		)
    	loop
    		_qualified_table2check := _schema || '.' || _table;
    		raise notice 'gm.create_all_enc_epi_sanity_check_triggers(): processing %', _qualified_table2check;
    		-- find encounter FK column name
    		select col_tbl.attname into _fk_encounter_col
    		from pg_catalog.pg_attribute col_tbl
    		where
    			col_tbl.attrelid = _qualified_table2check::regclass
    				and
    			col_tbl.attnum = (
    				select fk_tbl.conkey[1]
    				from pg_catalog.pg_constraint fk_tbl
    				where
    					fk_tbl.contype = 'f'
    						and
    					fk_tbl.conrelid = _qualified_table2check::regclass
    						and
    					fk_tbl.confrelid = 'clin.encounter'::regclass
    						and
    					fk_tbl.confkey[1] = (
    						select col_tbl1.attnum
    						from pg_catalog.pg_attribute col_tbl1
    						where
    							col_tbl1.attname = 'pk'
    								AND
    							col_tbl1.attrelid = 'clin.encounter'::regclass
    					)
    				)
    			;
    		-- find episode FK column name
    		select col_tbl.attname into _fk_episode_col
    		from pg_catalog.pg_attribute col_tbl
    		where
    			col_tbl.attrelid = _qualified_table2check::regclass
    				and
    			col_tbl.attnum = (
    				select fk_tbl.conkey[1]
    				from pg_catalog.pg_constraint fk_tbl
    				where
    					fk_tbl.contype = 'f'
    						and
    					fk_tbl.conrelid = _qualified_table2check::regclass
    						and
    					fk_tbl.confrelid = 'clin.episode'::regclass
    						and
    					fk_tbl.confkey[1] = (
    						select col_tbl1.attnum
    						from pg_catalog.pg_attribute col_tbl1
    						where
    							col_tbl1.attname = 'pk'
    								AND
    							col_tbl1.attrelid = 'clin.episode'::regclass
    					)
    				)
    			;
    		-- now create the trigger
    		BEGIN
    			PERFORM gm.create_enc_epi_sanity_check_trigger(_schema, _table, _fk_encounter_col, _fk_episode_col);
    		EXCEPTION
    			WHEN undefined_table OR invalid_foreign_key THEN
    				raise warning 'gm.create_all_enc_epi_sanity_check_triggers(): error processing <%.%>, skipping', _schema, _table;
    				_total_success := False;
    		END;
    	end loop;
    	return _total_success;
    END;

## Function: gm.create_all_table_mod_triggers(_drop_old_triggers boolean)

### Returns: boolean

### Language: PLPGSQL

(Re)create all table mod triggers for all registered tables.

    DECLARE
    	_notify_table record;
    	_cmd text;
    	_total_success boolean;
    BEGIN
    	_total_success := True;
    	-- loop over registered tables
    	for _notify_table in select * from gm.notifying_tables loop
    		BEGIN
    			PERFORM gm.create_table_mod_triggers(_notify_table.schema_name, _notify_table.table_name);
    		EXCEPTION
    			WHEN undefined_table OR undefined_column THEN
    				raise warning 'gm.create_all_table_mod_triggers(): error processing <%.%>, skipping', _notify_table.schema_name, _notify_table.table_name;
    				_total_success := False;
    		END;
    	end loop;
    	return _total_success;
    END;

## Function: gm.create_enc_epi_sanity_check_trigger(_fk_episode_col name, _fk_encounter_col name, _table_name name, _schema_name name)

### Returns: boolean

### Language: PLPGSQL

This function can be run on any table in order to add enccounter <-> episode sanity check triggers to that table.

    DECLARE
    	_qualified_table2check text;
    	_msg text;
    	_cmd text;
    BEGIN
    	_qualified_table2check := _schema_name || '.' || _table_name;
    	raise notice 'gm.create_enc_epi_sanity_check_trigger(): % (.% vs .%)', _qualified_table2check, _fk_encounter_col, _fk_episode_col;
    	-- verify table exists
    	if not exists(select 1 from information_schema.tables where table_schema = _schema_name and table_name = _table_name) then
    		raise warning 'gm.create_enc_epi_sanity_check_trigger(): table <%> does not exist', _qualified_table2check;
    		raise exception undefined_table;
    		return false;
    	end if;
    	-- verify that it points to clin.encounter.pk
    	if not exists (
    		select 1
    		from
    			pg_catalog.pg_constraint fk_tbl
    		where
    			fk_tbl.contype = 'f'
    				AND
    			fk_tbl.confrelid = 'clin.encounter'::regclass
    				AND
    			fk_tbl.conrelid = _qualified_table2check::regclass
    				AND
    			fk_tbl.confkey[1] = (
    				select attnum from pg_catalog.pg_attribute col_tbl
    				where
    					col_tbl.attname = 'pk'
    						AND
    					col_tbl.attrelid = 'clin.encounter'::regclass
    			)
    				AND
    			fk_tbl.conkey[1] = (
    				select attnum from pg_catalog.pg_attribute col_tbl
    				where
    					col_tbl.attname = _fk_encounter_col
    						AND
    					col_tbl.attrelid = _qualified_table2check::regclass
    			)
    	) then
    		raise exception
    			'gm.create_enc_epi_sanity_check_trigger(): <%.%> does not point to clin.encounter.pk', _qualified_table2check, _fk_encounter_col
    			USING ERRCODE = 'invalid_foreign_key'
    		;
    		return false;
    	end if;
    	-- verify that it points to clin.episode.pk
    	if not exists (
    		select 1
    		from
    			pg_catalog.pg_constraint fk_tbl
    		where
    			fk_tbl.contype = 'f'
    				AND
    			fk_tbl.confrelid = 'clin.episode'::regclass
    				AND
    			fk_tbl.conrelid = _qualified_table2check::regclass
    				AND
    			fk_tbl.confkey[1] = (
    				select attnum from pg_catalog.pg_attribute col_tbl
    				where
    					col_tbl.attname = 'pk'
    						AND
    					col_tbl.attrelid = 'clin.episode'::regclass
    			)
    				AND
    			fk_tbl.conkey[1] = (
    				select attnum from pg_catalog.pg_attribute col_tbl
    				where
    					col_tbl.attname = _fk_episode_col
    						AND
    					col_tbl.attrelid = _qualified_table2check::regclass
    			)
    	) then
    		raise exception
    			'gm.create_enc_epi_sanity_check_trigger(): <%.%> does not point to clin.episode.pk', _qualified_table2check, _fk_episode_col
    			USING ERRCODE = 'invalid_foreign_key'
    		;
    		return false;
    	end if;
    	-- re-create trigger
    	_cmd := 'drop trigger if exists tr_sanity_check_enc_epi_ins_upd on ' || _qualified_table2check || ' cascade';
    	execute _cmd;
    	_cmd := 'create trigger tr_sanity_check_enc_epi_ins_upd ';
    	_cmd := _cmd || 'before insert or update ';
    	_cmd := _cmd || 'on ' || _qualified_table2check || ' ';
    	_cmd := _cmd || 'for each row when (NEW.fk_episode is not null) ';
    	_cmd := _cmd || 'execute procedure clin.trf_sanity_check_enc_epi_ins_upd(''' || _fk_encounter_col || ''', ''' || _fk_episode_col || ''')';
    	execute _cmd;
    	return True;
    END;

## Function: gm.create_generic_combi_vaccine(text, text[], text, boolean)

### Returns: boolean

### Language: PLPGSQL

    DECLARE
    	_name alias for $1;
    	_indications alias for $2;
    	_atc alias for $3;
    	_is_live alias for $4;
    	_generic_name text;
    	_pk_brand integer;
    	_pk_vaccine integer;
    	_indication text;
    BEGIN
    	_generic_name := _name || ' - generic vaccine';
    	raise notice 're-creating [%] (%)', _generic_name, array_to_string(_indications, '-');
    	-- retrieve or create ref.branded_drug entry for indication
    	select pk into _pk_brand from ref.branded_drug
    	where
    		is_fake is true
    			and
    		description = _generic_name;
    	if FOUND is false then
    		insert into ref.branded_drug (
    			description,
    			preparation,
    			is_fake,
    			atc_code
    		) values (
    			_generic_name,
    			'vaccine',		-- this is rather arbitrary
    			True,
    			coalesce(_atc, 'J07')
    		)
    		returning pk
    		into _pk_brand;
    	end if;
    	-- retrieve or create clin.vaccine entry for generic brand
    	select pk into _pk_vaccine from clin.vaccine
    	where fk_brand = _pk_brand;
    	if FOUND is false then
    		insert into clin.vaccine (
    			is_live,
    			fk_brand
    		) values (
    			_is_live,
    			_pk_brand
    		)
    		returning pk
    		into _pk_vaccine;
    	end if;
    	-- link indications to vaccine
    	delete from clin.lnk_vaccine2inds
    	where
    		fk_vaccine = _pk_vaccine;
    	for _indication in select unnest(_indications) loop
    		insert into clin.lnk_vaccine2inds (
    			fk_vaccine,
    			fk_indication
    		) values (
    			_pk_vaccine,
    			(select id from clin.vacc_indication where description = _indication)
    		);
    	end loop;
    	return true;
    END;

## Function: gm.create_table_mod_triggers(_table_name name, _schema_name name)

### Returns: boolean

### Language: PLPGSQL

This function can be run on any table in order to add notification triggers to that table.

    DECLARE
    	_qualified_table text;
    	_msg text;
    	_payload text;
    	_PK_col_name text;
    	_pk_accessor_SQL text;
    	_accessor_col text;
    	_col_candidate text;
    	_identity_accessor_SQL text;
    	_cmd text;
    BEGIN
    	_qualified_table := _schema_name || '.' || _table_name;
    	raise notice 'gm.create_table_mod_triggers(): %', _qualified_table;
    	-- verify table exists
    	if not exists(select 1 from information_schema.tables where table_schema = _schema_name and table_name = _table_name) then
    		raise warning 'gm.create_table_mod_triggers(): table <%> does not exist', _qualified_table;
    		raise exception undefined_table;
    		return false;
    	end if;
    	-- find PK column
    	select
    		pg_attribute.attname into _PK_col_name
    	from
    		pg_index, pg_class, pg_attribute
    	where
    		pg_class.oid = _qualified_table::regclass
    			AND
    		indrelid = pg_class.oid
    			AND
    		pg_attribute.attrelid = pg_class.oid
    			AND
    		pg_attribute.attnum = any(pg_index.indkey)
    			AND
    		indisprimary;
    	if _PK_col_name is NULL then
    		raise warning 'gm.create_table_mod_triggers(): table <%> lacks a primary key', _qualified_table;
    		raise exception undefined_column;
    		return false;
    	end if;
    	_pk_accessor_SQL := 'select $1.' || _PK_col_name;
    	-- find identity accessor
    	-- special case
    	if _qualified_table = 'dem.identity' then
    		_identity_accessor_SQL := 'select $1.pk';
    	else
    		-- look for columns by which to retrieve affected person
    		_accessor_col := NULL;
    		foreach _col_candidate in array array['fk_identity', 'fk_patient', 'id_identity', 'fk_encounter'] loop
    			if exists (
    				select 1 from pg_class, pg_attribute where
    				pg_class.oid = _qualified_table::regclass
    					AND
    				pg_attribute.attname = _col_candidate
    					AND
    				pg_attribute.attrelid = pg_class.oid
    			) then
    				_accessor_col := _col_candidate;
    				exit;
    			end if;
    		end loop;
    		if _accessor_col = 'fk_encounter' then					-- retrieve identity PK via fk_encounter
    			_identity_accessor_SQL := 'select fk_patient from clin.encounter where pk = $1.fk_encounter limit 1';
    		elsif _accessor_col = 'fk_identity' then					-- retrieve identity PK via fk_identity
    			_identity_accessor_SQL := 'select $1.fk_identity';
    		elsif _accessor_col = 'fk_patient' then					-- retrieve identity PK via fk_patient
    			_identity_accessor_SQL := 'select $1.fk_patient';
    		elsif _accessor_col = 'id_identity' then					-- retrieve identity PK via id_identity
    			_identity_accessor_SQL := 'select $1.id_identity';
    		else
    			_identity_accessor_SQL := '<NULL>';
    		end if;
    	end if;
    	-- drop triggers should they exist
    	-- new-name announcement triggers
    	_cmd := 'drop trigger if exists zzz_tr_announce_' || _schema_name || '_' || _table_name || '_ins_upd on ' || _qualified_table || ' cascade;';
    	execute _cmd;
    	_cmd := 'drop trigger if exists zzz_tr_announce_' || _schema_name || '_' || _table_name || '_del on ' || _qualified_table || ' cascade;';
    	execute _cmd;
    	-- re-create triggers
    	-- 1) INSERT/UPDATE
    	_payload := 'table=' || _qualified_table || '::PK name=' || _PK_col_name;
    	_cmd := 'create constraint trigger zzz_tr_announce_' || _schema_name || '_' || _table_name || '_ins_upd';
    	_cmd := _cmd || ' after insert or update';
    	_cmd := _cmd || ' on ' || _qualified_table;
    	-- needed so a SELECT inside, say, _identity_accessor_SQL running
    	-- concurrently to a "lengthy" TX does not create a serialization
    	-- failure by being a rw-dependancy pivot
    	_cmd := _cmd || ' deferrable initially deferred';
    	_cmd := _cmd || ' for each row';
    	_cmd := _cmd || ' execute procedure gm.trf_announce_table_ins_upd(''' || _payload || ''', ''' || _pk_accessor_SQL || ''', ''' || _identity_accessor_SQL || ''');';
    	execute _cmd;
    	-- 2) DELETE
    	_payload := 'operation=DELETE::' || _payload;
    	_cmd := 'create constraint trigger zzz_tr_announce_' || _schema_name || '_' || _table_name || '_del';
    	_cmd := _cmd || ' after delete';
    	_cmd := _cmd || ' on ' || _qualified_table;
    	-- needed so a SELECT inside, say, _identity_accessor_SQL running
    	-- concurrently to a "lengthy" TX does not create a serialization
    	-- failure by being a rw-dependancy pivot
    	_cmd := _cmd || ' deferrable initially deferred';
    	_cmd := _cmd || ' for each row';
    	_cmd := _cmd || ' execute procedure gm.trf_announce_table_del(''' || _payload || ''', ''' || _pk_accessor_SQL || ''', ''' || _identity_accessor_SQL || ''');';
    	execute _cmd;
    	return True;
    END;

## Function: gm.create_user(name, text)

### Returns: boolean

### Language: PLPGSQL

To create users one needs to have CREATEROLE rights. Only gm-dbo is GRANTed EXECUTE. This way users need to know the gm-dbo (GNUmed admin) password to execute the function. Newly created users belong to group "gm-public" by default.

    DECLARE
    	_username alias for $1;
    	_password alias for $2;
    	_database text;
    	_query text;
    BEGIN
    	perform 1 from pg_user where usename = _username;
    	if not FOUND then
    		_query := 'create user ' || quote_ident(_username)
    					|| ' with password ' || quote_literal(_password)
    					|| ';';
    		execute _query;
    		perform 1 from pg_user where usename = _username;
    		if not FOUND then
    			raise exception 'cannot create user [%]', _username;
    			return false;
    		end if;
    	end if;
    	_query := 'alter group "gm-logins" add user ' || quote_ident(_username) || ';';
    	execute _query;
    	_query := 'alter group "gm-public" add user ' || quote_ident(_username) || ';';
    	execute _query;
    	-- satisfy "database = samerole" in pg_hba.conf
    	select into _database current_database();
    	_query := 'alter group ' || quote_ident(_database) || ' add user ' || quote_ident(_username) || ';';
    	execute _query;
    	return true;
    END;

## Function: gm.disable_user(name)

### Returns: boolean

### Language: PLPGSQL

To disable users one needs to have CREATEROLE rights. Only gm-dbo is GRANTed EXECUTE. This way users need to know the gm-dbo (GNUmed admin) password to execute the function.

    DECLARE
    	_username alias for $1;
    	_query text;
    BEGIN
    	perform 1 from pg_user where usename = _username;
    	if not FOUND then
    		return true;
    	end if;
    	_query := 'alter group "gm-logins" drop user ' || quote_ident(_username) || ';';
    	execute _query;
    	return true;
    END;

## Function: gm.drop_user(name)

### Returns: boolean

### Language: PLPGSQL

To drop users one needs to have CREATEROLE rights. Only gm-dbo is GRANTed EXECUTE. This way users need to know the gm-dbo (GNUmed admin) password to execute the function.

    DECLARE
    	_username alias for $1;
    	_query text;
    BEGIN
    	perform 1 from pg_user where usename = _username;
    	if not FOUND then
    		return true;
    	end if;
    	_query := 'drop user ' || quote_ident(_username) || ';';
    	execute _query;
    	perform 1 from pg_user where usename = _username;
    	if FOUND then
    		return false;
    	end if;
    	return true;
    END;

## Function: gm.get_users()

### Returns: text[]

### Language: SQL

    select gm.get_users(current_database());

## Function: gm.get_users(name)

### Returns: text[]

### Language: PLPGSQL

Convenience function listing all PostgreSQL accounts (roles) needed for a consistent dump of the database.

    DECLARE
    	_db alias for $1;
    	_gm_users text[];
    	_user text;
    BEGIN
    	-- GNUmed group roles
    	_gm_users := ARRAY['gm-logins', 'gm-public', 'gm-doctors', 'gm-staff', _db];
    	-- add roles being *members* of groups gm-logins, gm-public, _db
    	FOR _user in
    		select distinct rolname from pg_roles where oid in (
    			select member from pg_auth_members where roleid in (
    				select oid from pg_roles where rolname in ('gm-logins', 'gm-public', _db)
    			)
    		)
    	LOOP
    		continue when _user = 'postgres';
    		continue when _user = any(_gm_users);
    		_gm_users := _gm_users || _user;
    	END LOOP;
    	-- add roles mentioned in any *.modified_by fields
    	FOR _user in select distinct modified_by from audit.audit_fields LOOP
    		continue when _user = 'postgres';
    		continue when _user = any(_gm_users);
    		_gm_users := _gm_users || _user;
    	END LOOP;
    	-- add roles mentioned in dem.staff.db_user
    	FOR _user in select distinct db_user from dem.staff LOOP
    		continue when _user = 'postgres';
    		continue when _user = any(_gm_users);
    		_gm_users := _gm_users || _user;
    	END LOOP;
    	return _gm_users;
    END;

## Function: gm.is_null_or_blank_string(text)

### Returns: boolean

### Language: SQL

input is either NULL or empty string -> True; input is not NULL and not empty -> FALSE

    select (coalesce(trim($1), '') = '');

## Function: gm.is_null_or_non_empty_string(text)

### Returns: boolean

### Language: SQL

    select (coalesce(trim($1), 'NULL') != '');

## Function: gm.lo_chunked_md5(oid, integer)

### Returns: text

### Language: PLPGSQL

Function to create a chunked md5 sum on arbitrarily large LARGE OBJECTs.

    DECLARE
    	lo_id alias for $1;
    	chunk_size alias for $2;
    	_lo_fd integer;
    	_lo_size integer;
    	_chunk_count integer;
    	_remainder integer;
    	_md5_concat text;
    	INV_READ constant integer := x'40000'::integer;
    	SEEK_SET constant integer := 0;
    	SEEK_END constant integer := 2;
    BEGIN
    	-- check for existence of lo_id ?
    	_lo_fd := lo_open(lo_id, INV_READ);
    	-- get size
    	_lo_size := lo_lseek(_lo_fd, 0, SEEK_END);
    	PERFORM lo_close(_lo_fd);						-- move further down if loread() proves faster
    	-- calculate chunks and remainder
    	_chunk_count := _lo_size / chunk_size;
    	_remainder := _lo_size % chunk_size;
    	-- loop over chunks
    	_md5_concat := '';
    	FOR _chunk_id in 1.._chunk_count LOOP
    		_md5_concat := _md5_concat || md5(lo_get(lo_id, (_chunk_id - 1) * chunk_size, chunk_size));
    		-- using loread() may be faster (as it directly accesses the
    		-- existing lo_fd and thusly does not need to re-open the LO
    		-- each round)
    	END LOOP;
    	-- add remainder
    	_md5_concat := _md5_concat || md5(lo_get(lo_id, _chunk_count * chunk_size, _remainder));
    	return md5(_md5_concat);
    END;

## Function: gm.log_access2emr(text)

### Returns: void

### Language: PLPGSQL

This logs access to a patient EMR.

    DECLARE
    	_action alias for $1;
    BEGIN
    	if gm.is_null_or_blank_string(_action) then
    		raise exception 'gm.log_access2emr(): action detail cannot be NULL or empty';
    	end if;
    	insert into gm.access_log (user_action) values ('EMR access: ' || _action);
    	return;
    END;

## Function: gm.log_other_access(text)

### Returns: void

### Language: SQL

This logs access to the database.

    insert into gm.access_log (user_action) values ($1);

## Function: gm.log_script_insertion(text, text)

### Returns: text

### Language: PLPGSQL

    declare
    	_filename alias for $1;
    	_version alias for $2;
    	_hash text;
    begin
    	delete from gm.schema_revision where filename = _filename;
    	insert into gm.schema_revision (filename, version) values (
    		_filename,
    		_version
    	);
    	perform gm.log_other_access (
    		'database change script inserted: ' || _filename || ' (' || _version || ')'
    	);
    	select into _hash md5(gm.concat_table_structure());
    	return _hash;
    end;

## Function: gm.nullify_empty_string(text)

### Returns: text

### Language: PLPGSQL

    DECLARE
    	_input alias for $1;
    BEGIN
    	if _input is null then
    		return null;
    	end if;
    	if trim(_input) = '' then
    		return null;
    	end if;
    	return _input;
    END;

## Function: gm.register_notifying_table(name, name)

### Returns: boolean

### Language: PLPGSQL

Register given table for notification trigger generator. Parameters are: (schema, table)

    DECLARE
    	_namespace alias for $1;
    	_table alias for $2;
    	dummy RECORD;
    BEGIN
    	-- does table exist ?
    	select relname into dummy from pg_class where
    		relname = _table and
    		relnamespace = (select oid from pg_namespace where nspname = _namespace)
    	;
    	if not found then
    		raise exception 'register_notifying_table(): Table [%.%] does not exist.', _namespace, _table;
    	end if;
    	-- make sure we can insert
    	delete from gm.notifying_tables where
    		table_name = _table
    		and schema_name = _namespace;
    	insert into gm.notifying_tables (
    		schema_name,
    		table_name
    	) values (
    		_namespace,
    		_table
    	);
    	return true;
    END;

## Function: gm.strip_allzeros_fraction(numeric)

### Returns: numeric

### Language: PLPGSQL

Remove fractions containing only zeros (n.000...) from NUMERICs/DECIMALs.

    DECLARE
    	_numeric_value alias for $1;
    	_fraction numeric;
    	_msg text;
    BEGIN
    	_fraction := _numeric_value - trunc(_numeric_value);
    	if _fraction <> 0 then
    		return _numeric_value;
    	end if;
    	BEGIN
    		return _numeric_value::bigint::numeric;
    	EXCEPTION
    		WHEN numeric_value_out_of_range THEN
    			RAISE NOTICE '[gm.strip_allzeros_fraction]: cannot strip from %', _numeric_value;
    			RETURN _numeric_value;
    	END;
    END;

## Function: gm.transfer_users(text)

### Returns: boolean

### Language: SQL

    select gm.transfer_users($1, current_database());

## Function: gm.transfer_users(text, text)

### Returns: boolean

### Language: PLPGSQL

This function transfers adds users from the group role given in the argument to the group role corresponding to the current database name. This enables group membership based authentication as used in GNUmed. This operation is typically only run on database upgrade and is only available to gm-dbo.

    DECLARE
    	_source_group alias for $1;
    	_target_group alias for $2;
    	member_ids int[];
    	member_id int;
    	member_name text;
    	tmp text;
    BEGIN
    	-- source group exists ?
    	perform 1 from pg_group where groname = _source_group;
    	if not FOUND then
    		raise exception 'gm_transfer_users(): source group [%] does not exist', _source_group;
    		return false;
    	end if;
    	-- target group exists ?
    	perform 1 from pg_group where groname = _target_group;
    	if not FOUND then
    		raise exception 'gm_transfer_users(): target group [%] does not exist', _target_group;
    		return false;
    	end if;
    	-- loop over group member IDs
    	select into member_ids grolist from pg_group where groname = _source_group;
    	FOR idx IN coalesce(array_lower(member_ids, 1), 0) .. coalesce(array_upper(member_ids, 1), -1) LOOP
    		member_id := member_ids[idx];
    		select into member_name usename from pg_user where usesysid = member_id;
    		tmp := 'gm_transfer_users(text): transferring "'
    				|| member_name || '" ('
    				|| member_id || ') from group "'
    				|| _source_group || '" to group "'
    				|| _target_group || '"';
    		raise notice '%', tmp;
    		-- satisfy "database = samegroup" in pg_hba.conf
    		tmp := 'alter group ' || quote_ident(_target_group) || ' add user ' || quote_ident(member_name) || ';';
    		execute tmp;
    	end LOOP;
    	return true;
    END;

## Function: gm.trf_announce_table_del()

### Returns: trigger

### Language: PLPGSQL

Trigger function announcing a DELETE on a table. sends signal: gm_table_mod payload: operation=DELETE, table=the table that is updated, PK name=the name of the PK column of the table (requires single column PKs), row PK=the PK of the affected row, person PK=the PK of the affected person,

    declare
    	_payload text;
    	_pk_accessor_SQL text;
    	_pk_col_val integer;
    	_identity_accessor_SQL text;
    	_pk_identity integer;
    begin
    	_pk_accessor_SQL := TG_ARGV[1];
    	EXECUTE _pk_accessor_SQL INTO STRICT _pk_col_val USING OLD;
    	_payload := TG_ARGV[0] || '::row PK=' || coalesce(_pk_col_val::text, 'NULL');
    	_identity_accessor_SQL := TG_ARGV[2];
    	if _identity_accessor_SQL <> '<NULL>' then
    		--raise notice '%.%: %', TG_TABLE_SCHEMA, TG_TABLE_NAME, _identity_accessor_SQL;
    		EXECUTE _identity_accessor_SQL INTO STRICT _pk_identity USING OLD;
    		_payload := _payload || '::person PK=' || coalesce(_pk_identity::text, 'NULL');
    	end if;
    	perform pg_notify('gm_table_mod', _payload);
    	return NULL;
    end;

## Function: gm.trf_announce_table_ins_upd()

### Returns: trigger

### Language: PLPGSQL

Trigger function announcing an INSERT or UPDATE to a table. sends signal: gm_table_mod payload: operation=INSERT/UPDATE, table=the table that is updated, PK name=the name of the PK column of the table (requires single column PKs), row PK=the PK of the affected row, person PK=the PK of the affected person,

    declare
    	_payload text;
    	_pk_accessor_SQL text;
    	_pk_col_val integer;
    	_identity_accessor_SQL text;
    	_pk_identity integer;
    begin
    	_pk_accessor_SQL := TG_ARGV[1];
    	EXECUTE _pk_accessor_SQL INTO STRICT _pk_col_val USING NEW;
    	_payload := 'operation=' || TG_OP || '::' || TG_ARGV[0] || '::row PK=' || coalesce(_pk_col_val::text, 'NULL');
    	_identity_accessor_SQL := TG_ARGV[2];
    	if _identity_accessor_SQL <> '<NULL>' then
    		EXECUTE _identity_accessor_SQL INTO STRICT _pk_identity USING NEW;
    		_payload := _payload || '::person PK=' || coalesce(_pk_identity::text, 'NULL');
    	end if;
    	perform pg_notify('gm_table_mod', _payload);
    	return NULL;
    end;

## Function: gm.user_exists(name)

### Returns: boolean

### Language: PLPGSQL

    BEGIN
    	perform 1 from pg_user where usename = $1;
    	if not FOUND then
    		raise notice 'Cannot set database language. User % does not exist.', $1;
    		return false;
    	end if;
    	return true;
    END;

## Function: gm.xid2int(xid)

### Returns: integer

### Language: SQL

    select $1::text::integer;

# Schema i18n

## Table: i18n.curr_lang

holds the currently selected per-user default language for fixed strings in the database

i18n.curr_lang Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| db_user |  | UNIQUE

i18n.curr_lang Constraints
Name | Constraint
--- | ---
user_must_exist | CHECK ((gm.user_exists(db_user) IS TRUE))

Index - Schema i18n

## Table: i18n.keys

this table holds all the original strings that need translation so give this to your language teams, the function i18n.i18n() will take care to enter relevant strings into this table, the table table does NOT play any role in runtime translation activity

i18n.keys Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| orig |  | UNIQUE

Index - Schema i18n

## Table: i18n.translations

this table holds all the translated strings

i18n.translations Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| orig |  | UNIQUE#1
| lang |  | UNIQUE#1
| pk |  | PRIMARY KEY

i18n.translations Constraints
Name | Constraint
--- | ---
i18n_translations_sane_trans | CHECK ((trans <> orig))

idx_orig orig

Index - Schema i18n

## View: i18n.v_missing_translations

lists per language which strings are lacking a translation

i18n.v_missing_translations Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT i_cl.lang
    ,
        i_k.orig
    ,
        _
    (i_k.orig
         ,'en'::text
    ) AS english

    FROM (
    SELECT DISTINCT
        ON (curr_lang.lang) curr_lang.lang

      FROM i18n.curr_lang
    ) i_cl
    ,
        i18n.keys i_k

    WHERE (NOT
         (i_k.orig IN
               (
                SELECT i_t.orig

                  FROM i18n.translations i_t

                 WHERE (i_t.lang = i_cl.lang)
               )
         )
    );

Index - Schema i18n

## Function: i18n._(text)

### Returns: text

### Language: SQL

will return either the translation into i18n.curr_lang.lang for the current user or the input, created in public schema for easy access

    select i18n._($1, i18n.get_curr_lang())

## Function: i18n._(text, text)

### Returns: text

### Language: PLPGSQL

will return either the translation into <lang>::text (2nd argument) for the current user or the input, created in public schema for easy access, will fallback to "xx" if xx_XX does not exist

    DECLARE
    	_orig alias for $1;
    	_lang alias for $2;
    	trans_str text;
    BEGIN
    	select into trans_str trans from i18n.translations where lang = _lang and orig = _orig;
    	if not found then
    		-- reduce xx_XX@YY to xx
    		select into trans_str trans from i18n.translations where lang = regexp_replace(_lang, '_.*$', '') and orig = _orig;
    		if not found then
    			return _orig;
    		end if;
    --		if not found then
    --			-- check "generic" dummy translation used to work around accentuation problems
    --			select into trans_str trans from i18n.translations where lang = 'generic' and orig = _orig;
    --
    --			if not found then
    --				return _orig;
    --			end if;
    --		end if;
    	end if;
    	return trans_str;
    END;

## Function: i18n.force_curr_lang(text)

### Returns: boolean

### Language: PLPGSQL

force preferred language to some language: - for "current user"

    DECLARE
        _lang ALIAS FOR $1;
    BEGIN
        raise notice 'Forcing current language to [%] without checking for translations..', _lang;
        delete from i18n.curr_lang where db_user = SESSION_USER;
    	insert into i18n.curr_lang (lang, db_user) values (_lang, SESSION_USER);
        return true;
    END;

## Function: i18n.get_curr_lang()

### Returns: text

### Language: SQL

    select i18n.get_curr_lang(CURRENT_USER)

## Function: i18n.get_curr_lang(text)

### Returns: text

### Language: SQL

    select lang from i18n.curr_lang where db_user = $1

## Function: i18n.i18n(text)

### Returns: text

### Language: PLPGSQL

insert original strings into i18n.keys for later translation

    DECLARE
    	original ALIAS FOR $1;
    BEGIN
    	if not exists(select pk from i18n.keys where orig = original) then
    		insert into i18n.keys (orig) values (original);
    	end if;
    	return original;
    END;

## Function: i18n.set_curr_lang(text)

### Returns: boolean

### Language: PLPGSQL

set preferred language: - for "current (session) user" - only if translations for this language are available

    DECLARE
    	_lang ALIAS FOR $1;
    BEGIN
    	if exists(select pk from i18n.translations where lang = _lang) then
    		delete from i18n.curr_lang where db_user = SESSION_USER;
    		insert into i18n.curr_lang (lang, db_user) values (_lang, SESSION_USER);
    		return true;
    	end if;
    	raise notice 'Cannot set current language to [%]. No translations available.', _lang;
    	return false;
    END;

## Function: i18n.set_curr_lang(text, name)

### Returns: boolean

### Language: PLPGSQL

set language to first argument for the user named in the second argument if translations are available

    DECLARE
    	_lang ALIAS FOR $1;
    	_db_user ALIAS FOR $2;
    	lang_has_tx boolean;
    BEGIN
    	select into lang_has_tx exists(select pk from i18n.translations where lang = _lang);
    	if lang_has_tx is False then
    		raise notice 'Cannot set current language to [%]. No translations available.', _lang;
    		return False;
    	end if;
    	delete from i18n.curr_lang where db_user = _db_user;
    	insert into i18n.curr_lang (db_user, lang) values (_db_user, _lang);
    	return true;
    END;

## Function: i18n.tx_or_null(text)

### Returns: text

### Language: SQL

will return either the translation into i18n.curr_lang.lang for the current user or null

    select i18n.tx_or_null($1, i18n.get_curr_lang())

## Function: i18n.tx_or_null(text, text)

### Returns: text

### Language: PLPGSQL

will return either the translation into language <text> (2nd argument) or null

    DECLARE
    	_orig alias for $1;
    	_lang alias for $2;
    	trans_str text;
    BEGIN
    	select into trans_str trans from i18n.translations where lang = _lang and orig = _orig;
    	if not found then
    		return null;
    	end if;
    	return trans_str;
    END;

## Function: i18n.unset_curr_lang()

### Returns: void

### Language: SQL

unset the db language for the current user

    select i18n.unset_curr_lang(CURRENT_USER);

## Function: i18n.unset_curr_lang(name)

### Returns: void

### Language: PLPGSQL

unset the db language for a user (thereby reverting to the default English)

    BEGIN
    	delete from i18n.curr_lang where db_user = $1;
    	return;
    END;

## Function: i18n.untranslate(text, text)

### Returns: text

### Language: PLPGSQL

Return "original" from a "translated" string (1st argument) as per language (2nd argument).

    DECLARE
    	_trans alias for $1;
    	_lang alias for $2;
    	_orig text;
    BEGIN
    	select orig into _orig
    	from i18n.translations
    	where
    		trans = _trans
    			and
    		lang = _lang;
    	return _orig;
    END;

## Function: i18n.upd_tx(text, text)

### Returns: boolean

### Language: SQL

    select i18n.upd_tx((select i18n.get_curr_lang()), $1, $2)

## Function: i18n.upd_tx(text, text, text)

### Returns: boolean

### Language: PLPGSQL

    declare
    	_lang alias for $1;
    	_orig alias for $2;
    	_trans alias for $3;
    	_tmp text;
    begin
    	if _lang is null then
    		raise notice 'i18n.upd_tx(text, text, text): Cannot create translation for language <NULL>.';
    		return False;
    	end if;
    	if _trans = _orig then
    		raise notice 'i18n.upd_tx(text, text, text): Original = translation. Skipping.';
    		return True;
    	end if;
    	select into _tmp '1' from i18n.keys where orig = _orig;
    	if not found then
    		raise notice 'i18n.upd_tx(text, text, text): [%] not found in i18n.keys. Creating entry.', _orig;
    		insert into i18n.keys (orig) values (_orig);
    	end if;
    	delete from i18n.translations where lang = _lang and orig = _orig;
    	insert into i18n.translations (lang, orig, trans) values (_lang, _orig, _trans);
    	raise notice 'i18n.upd_tx(%: [%] ==> [%])', _lang, _orig, _trans;
    	return True;
    end;

# Schema pgtrgm

## Function: pgtrgm.gin_extract_query_trgm(text, internal, smallint, internal, internal, internal, internal)

### Returns: internal

### Language: C

    gin_extract_query_trgm

## Function: pgtrgm.gin_extract_value_trgm(text, internal)

### Returns: internal

### Language: C

    gin_extract_value_trgm

## Function: pgtrgm.gin_trgm_consistent(internal, smallint, text, integer, internal, internal, internal, internal)

### Returns: boolean

### Language: C

    gin_trgm_consistent

## Function: pgtrgm.gin_trgm_triconsistent(internal, smallint, text, integer, internal, internal, internal)

### Returns: "char"

### Language: C

    gin_trgm_triconsistent

## Function: pgtrgm.gtrgm_compress(internal)

### Returns: internal

### Language: C

    gtrgm_compress

## Function: pgtrgm.gtrgm_consistent(internal, text, smallint, oid, internal)

### Returns: boolean

### Language: C

    gtrgm_consistent

## Function: pgtrgm.gtrgm_decompress(internal)

### Returns: internal

### Language: C

    gtrgm_decompress

## Function: pgtrgm.gtrgm_distance(internal, text, smallint, oid, internal)

### Returns: double precision

### Language: C

    gtrgm_distance

## Function: pgtrgm.gtrgm_in(cstring)

### Returns: gtrgm

### Language: C

    gtrgm_in

## Function: pgtrgm.gtrgm_options(internal)

### Returns: void

### Language: C

    gtrgm_options

## Function: pgtrgm.gtrgm_out(pgtrgm.gtrgm)

### Returns: cstring

### Language: C

    gtrgm_out

## Function: pgtrgm.gtrgm_penalty(internal, internal, internal)

### Returns: internal

### Language: C

    gtrgm_penalty

## Function: pgtrgm.gtrgm_picksplit(internal, internal)

### Returns: internal

### Language: C

    gtrgm_picksplit

## Function: pgtrgm.gtrgm_same(pgtrgm.gtrgm, pgtrgm.gtrgm, internal)

### Returns: internal

### Language: C

    gtrgm_same

## Function: pgtrgm.gtrgm_union(internal, internal)

### Returns: gtrgm

### Language: C

    gtrgm_union

## Function: pgtrgm.set_limit(real)

### Returns: real

### Language: C

    set_limit

## Function: pgtrgm.show_limit()

### Returns: real

### Language: C

    show_limit

## Function: pgtrgm.show_trgm(text)

### Returns: text[]

### Language: C

    show_trgm

## Function: pgtrgm.similarity(text, text)

### Returns: real

### Language: C

    similarity

## Function: pgtrgm.similarity_dist(text, text)

### Returns: real

### Language: C

    similarity_dist

## Function: pgtrgm.similarity_op(text, text)

### Returns: boolean

### Language: C

    similarity_op

## Function: pgtrgm.strict_word_similarity(text, text)

### Returns: real

### Language: C

    strict_word_similarity

## Function: pgtrgm.strict_word_similarity_commutator_op(text, text)

### Returns: boolean

### Language: C

    strict_word_similarity_commutator_op

## Function: pgtrgm.strict_word_similarity_dist_commutator_op(text, text)

### Returns: real

### Language: C

    strict_word_similarity_dist_commutator_op

## Function: pgtrgm.strict_word_similarity_dist_op(text, text)

### Returns: real

### Language: C

    strict_word_similarity_dist_op

## Function: pgtrgm.strict_word_similarity_op(text, text)

### Returns: boolean

### Language: C

    strict_word_similarity_op

## Function: pgtrgm.word_similarity(text, text)

### Returns: real

### Language: C

    word_similarity

## Function: pgtrgm.word_similarity_commutator_op(text, text)

### Returns: boolean

### Language: C

    word_similarity_commutator_op

## Function: pgtrgm.word_similarity_dist_commutator_op(text, text)

### Returns: real

### Language: C

    word_similarity_dist_commutator_op

## Function: pgtrgm.word_similarity_dist_op(text, text)

### Returns: real

### Language: C

    word_similarity_dist_op

## Function: pgtrgm.word_similarity_op(text, text)

### Returns: boolean

### Language: C

    word_similarity_op

# Schema public

standard public schema

## Table: public.basic_unit

basic units are SI units, units derived from them and the Unity

public.basic_unit Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| name_short |  | UNIQUE
| pk |  | PRIMARY KEY
| name_long |  | UNIQUE

Tables referencing this one via Foreign Key Constraints:

- public.unit

Index - Schema public

## Table: public.form_field_types

public.form_field_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| name |  | UNIQUE
| pk |  | PRIMARY KEY

Tables referencing this one via Foreign Key Constraints:

- public.form_fields

Index - Schema public

## Table: public.form_fields

List of fields for a particular form

public.form_fields Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| long_name |  | UNIQUE#1
| template_placeholder |  | UNIQUE#2
public.form_field_types.pk | fk_type |  |
ref.paperwork_templates.pk | fk_form |  | UNIQUE#1 UNIQUE#2

Tables referencing this one via Foreign Key Constraints:

- clin.form_data

Index - Schema public

## Table: public.form_job_queue

Queue table for rendered form instances. Note that the rows in this table will get deleted after processing. This is NOT an archive of form jobs.

public.form_job_queue Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.form_instances.pk | fk_form_instance |  |
| pk |  | PRIMARY KEY
public.form_job_targets.pk | fk_job_target |  |

Index - Schema public

## Table: public.form_job_targets

the form job targets (eg. printers, faxes, smtp servers) in whatever granularity is needed locally, can be used for load balancing/round robin servicing busy queues

public.form_job_targets Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| target |  | UNIQUE

Tables referencing this one via Foreign Key Constraints:

- public.form_job_queue

Index - Schema public

## Table: public.form_print_defs

public.form_print_defs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| fk_form |  | UNIQUE
ref.papersizes.pk | fk_papersize |  |
| pk |  | PRIMARY KEY

Index - Schema public

## Table: public.gm_client_db_match

allows lookup of whether a given client version can work with a particular database revision

public.gm_client_db_match Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| client_type |  | UNIQUE#1
| client_version |  | UNIQUE#1
| db_identity_hash |  | UNIQUE#1

Index - Schema public

## Table: public.housekeeping_todo

this table stores items that originate in headless processes running in the background but need to be brought to the attention of someone, say, errors that an integrity checker may find

public.housekeeping_todo Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

public.housekeeping_todo Constraints
Name | Constraint
--- | ---
housekeeping_todo_reported_to_check | CHECK ((reported_to = ANY (ARRAY['user'::text, 'admin'::text])))

Index - Schema public

## Table: public.test_norm

each row defines one set of measurement reference data

public.test_norm Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| fk_ref_src |  | UNIQUE#1
| pk |  | PRIMARY KEY
| data |  | UNIQUE#1

Index - Schema public

## Table: public.unit

units as used in real life

public.unit Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
public.basic_unit.pk | fk_basic_unit |  |

Index - Schema public

## Function: public._(text)

### Returns: text

### Language: SQL

will return either the translation into i18n.curr_lang.lang for the current user or the input, created in public schema for easy access

    select i18n._($1)

## Function: public._(text, text)

### Returns: text

### Language: SQL

will return either the translation into <text> (2nd argument) for the current user or the input, created in public schema for easy access

    select i18n._($1, $2)

## Function: public.f_rfi_type2item()

### Returns: trigger

### Language: PLPGSQL

function used to check referential integrity from clin.lnk_type2item to clin.clin_root_item with a custom trigger

    declare
    	dummy integer;
    	msg text;
    begin
    	-- does fk_item change at all ?
    	if TG_OP = 'UPDATE' then
    		if NEW.fk_item = OLD.fk_item then
    			return NEW;
    		end if;
    	end if;
    	-- check referential integrity
    	select into dummy 1 from clin.clin_root_item where pk_item=NEW.fk_item;
    	if not found then
    		msg := 'referential integrity violation: clin.lnk_type2item.fk_item [' || NEW.fk_item || '] not in <clin_root_item.pk_item>';
    		raise exception '%', msg;
    		return NULL;
    	end if;
    	return NEW;
    end;

## Function: public.f_set_encounter_timezone()

### Returns: trigger

### Language: PLPGSQL

    begin
    	if TG_OP = 'INSERT' then
    		NEW.source_time_zone := (select (extract(timezone from (select now()))::text || 'seconds')::interval);
    	else
    		NEW.source_time_zone := OLD.source_time_zone;
    	end if;
    	return NEW;
    end;

# Schema ref

This schema holds data that is "reference material" which comes pre-installed with a GNUmed database. Examples are: - document types - ICD codes - form templates

## Table: ref.atc

holds ATC data

ref.atc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.data_source.pk | fk_data_source |  |
| pk |  | PRIMARY KEY

Table ref.atc Inherits coding_system_root,

idx_ref_atc_fk_data_src fk_data_source

Index - Schema ref

## Table: ref.atc_staging

used for importing ATC data

ref.atc_staging Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Index - Schema ref

## Table: ref.auto_hint

This table stores SQL queries and the associated hints. If the query returns TRUE the client should display the hint.

ref.auto_hint Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| title |  | UNIQUE
| query |  | UNIQUE

Table ref.auto_hint Inherits audit_fields,

ref.auto_hint Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
ref_auto_hint_sane_hint | CHECK ((gm.is_null_or_blank_string(hint) IS FALSE))
ref_auto_hint_sane_lang | CHECK ((gm.is_null_or_blank_string(lang) IS FALSE))
ref_auto_hint_sane_popup_type | CHECK (((popup_type > '-1'::integer) AND (popup_type < 3)))
ref_auto_hint_sane_query | CHECK ((gm.is_null_or_blank_string(query) IS FALSE))
ref_auto_hint_sane_rec_query | CHECK (gm.is_null_or_non_empty_string(recommendation_query))
ref_auto_hint_sane_source | CHECK ((gm.is_null_or_blank_string(source) IS FALSE))
ref_auto_hint_sane_title | CHECK ((gm.is_null_or_blank_string(title) IS FALSE))
ref_auto_hint_sane_url | CHECK (gm.is_null_or_non_empty_string(url))

Tables referencing this one via Foreign Key Constraints:

- clin.suppressed_hint

Index - Schema ref

## Table: ref.billable

items that *can* be billed to patients

ref.billable Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
ref.data_source.pk | fk_data_source |  |

Table ref.billable Inherits coding_system_root,

ref.billable Constraints
Name | Constraint
--- | ---
ref_billable_sane_amount | CHECK ((amount >= (0)::numeric))
ref_billable_sane_currency | CHECK ((gm.is_null_or_blank_string(currency) IS FALSE))
ref_billable_sane_vat_multiplier | CHECK ((vat_multiplier >= (0)::numeric))

Tables referencing this one via Foreign Key Constraints:

- bill.bill_item

- bill.lnk_enc_type2billable

idx_ref_billable_fk_data_src fk_data_source

Index - Schema ref

## Table: ref.coda

Holds CodA/CodZ codes.

ref.coda Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
ref.data_source.pk | fk_data_source |  |

Table ref.coda Inherits coding_system_root,

ref.coda Constraints
Name | Constraint
--- | ---
chk_ref_coda_sane_icd10_text | CHECK ((gm.is_null_or_blank_string(icd10_text) IS FALSE))

idx_ref_coda_fk_data_src fk_data_source

Index - Schema ref

## Table: ref.code_thesaurus_root

Synonyms for coded terms.

ref.code_thesaurus_root Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_thesaurus |  | PRIMARY KEY

ref.code_thesaurus_root Constraints
Name | Constraint
--- | ---
ref_code_thes_root_sane_synonym | CHECK ((gm.is_null_or_blank_string(synonym) IS FALSE))

Index - Schema ref

## Table: ref.coding_system_root

Base table for coding system tables providing common fields.

ref.coding_system_root Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| term |  | UNIQUE#2
ref.data_source.pk | fk_data_source |  | UNIQUE#1 UNIQUE#2
| pk_coding_system |  | PRIMARY KEY
| code |  | UNIQUE#1

Index - Schema ref

## Table: ref.data_source

lists the available coding systems, classifications, ontologies and term lists

ref.data_source Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| version |  | UNIQUE#1 UNIQUE#2
| name_long |  | UNIQUE#1
| pk |  | PRIMARY KEY
| name_short |  | UNIQUE#2

Table ref.data_source Inherits audit_fields,

ref.data_source Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- dem.org

- ref.atc

- ref.billable

- ref.coda

- ref.coding_system_root

- ref.drug_product

- ref.icd10

- ref.icd9

- ref.icpc

- ref.loinc

- ref.ops

- ref.other_code

idx_ref_data_source_lang lang

Index - Schema ref

## Table: ref.document_type

pre-installed document types, do not change these as they will be overwritten during database upgrades at the discretion of the GNUmed team

ref.document_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

Index - Schema ref

## Table: ref.dose

Links doses to consumable substances.

ref.dose Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.substance.pk | fk_substance |  |
| pk |  | PRIMARY KEY

Table ref.dose Inherits audit_fields,

ref.dose Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
ref_dose_sane_amount | CHECK ((amount > (0)::numeric))
ref_dose_sane_dose_unit | CHECK ((gm.is_null_or_non_empty_string(dose_unit) IS TRUE))
ref_dose_sane_unit | CHECK ((gm.is_null_or_blank_string(unit) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- ref.lnk_dose2drug

- staging.lnk_vacc_ind2subst_dose

Index - Schema ref

## Table: ref.drug_product

The medicine chest of this praxis. Stores brands of drugs patients have been taking regardless of whether that brand still exists or in fact ever existed as such (as in lifestyle thingies).

ref.drug_product Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.data_source.pk | fk_data_source |  |
| pk |  | PRIMARY KEY

Table ref.drug_product Inherits audit_fields,

ref.drug_product Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
desc_not_empty | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))
drug_sane_external_code | CHECK ((gm.is_null_or_non_empty_string(external_code) IS TRUE))
drug_sane_external_code_type | CHECK ((((external_code IS NULL) AND (external_code_type IS NULL)) OR ((external_code IS NOT NULL) AND (external_code_type IS NOT NULL))))
prep_not_empty | CHECK ((gm.is_null_or_blank_string(preparation) IS FALSE))
sane_atc | CHECK ((gm.is_null_or_non_empty_string(atc_code) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- ref.lnk_dose2drug

- ref.vaccine

idx_drug_data_source fk_data_source idx_drug_description description idx_drug_ext_code external_code

Index - Schema ref

## Table: ref.form_types

types of forms which are available, generally by purpose (radiology, pathology, sick leave, Therapiebericht etc.)

ref.form_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| name |  | UNIQUE
| pk |  | PRIMARY KEY

Tables referencing this one via Foreign Key Constraints:

- ref.paperwork_templates

Index - Schema ref

## Table: ref.icd10

Holds ICD-10 codes.

ref.icd10 Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
ref.data_source.pk | fk_data_source |  |

Table ref.icd10 Inherits coding_system_root,

ref.icd10 Constraints
Name | Constraint
--- | ---
chk_ref_icd10_sane_aux_code | CHECK ((gm.is_null_or_non_empty_string(aux_code) IS TRUE))
chk_ref_icd10_sane_star_code | CHECK ((gm.is_null_or_non_empty_string(star_code) IS TRUE))

idx_ref_icd10_fk_data_src fk_data_source

Index - Schema ref

## Table: ref.icd9

Holds ICD-9 codes.

ref.icd9 Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
ref.data_source.pk | fk_data_source |  |

Table ref.icd9 Inherits coding_system_root,

idx_ref_icd9_fk_data_src fk_data_source

Index - Schema ref

## Table: ref.icpc

This table holds ICPC2 codes along with local extensions.

ref.icpc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| code_extension |  | UNIQUE#1
ref.icpc_component.component | fk_component |  |
| code |  | UNIQUE#1
ref.icpc_chapter.chapter | fk_chapter |  |
| pk |  | PRIMARY KEY
ref.data_source.pk | fk_data_source |  |

Table ref.icpc Inherits coding_system_root,

ref.icpc Constraints
Name | Constraint
--- | ---
ref_icpc_sane_code_ext | CHECK ((gm.is_null_or_non_empty_string(code_extension) IS TRUE))
ref_icpc_sane_criteria | CHECK ((gm.is_null_or_non_empty_string(criteria) IS TRUE))
ref_icpc_sane_exclusions | CHECK (((exclusions IS NULL) OR (array_length(exclusions, 1) > 0)))
ref_icpc_sane_icd10 | CHECK (((icd10 IS NULL) OR (array_length(icd10, 1) > 0)))
ref_icpc_sane_inclusions | CHECK ((gm.is_null_or_non_empty_string(inclusions) IS TRUE))
ref_icpc_sane_see_also | CHECK (((see_also IS NULL) OR (array_length(see_also, 1) > 0)))
ref_icpc_sane_term | CHECK ((gm.is_null_or_blank_string(term) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- ref.icpc_thesaurus

idx_ref_icpc_chapter fk_chapter idx_ref_icpc_code code idx_ref_icpc_component fk_component idx_ref_icpc_fk_data_src fk_data_source idx_ref_icpc_term term

Index - Schema ref

## Table: ref.icpc_chapter

The chapters of the ICPC.

ref.icpc_chapter Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| description |  | UNIQUE
| chapter |  | UNIQUE

ref.icpc_chapter Constraints
Name | Constraint
--- | ---
ref_icpc_chapter_sane_desc | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- ref.icpc

Index - Schema ref

## Table: ref.icpc_component

The Components of the ICPC chapters.

ref.icpc_component Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| component |  | UNIQUE
| description |  | UNIQUE
| pk |  | PRIMARY KEY

ref.icpc_component Constraints
Name | Constraint
--- | ---
ref_icpc_component_sane_desc | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- ref.icpc

Index - Schema ref

## Table: ref.icpc_thesaurus

Synonyms for ICPC terms.

ref.icpc_thesaurus Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
ref.icpc.pk_coding_system | fk_code |  |

Table ref.icpc_thesaurus Inherits code_thesaurus_root,

ref.icpc_thesaurus Constraints
Name | Constraint
--- | ---
ref_code_thes_root_sane_synonym | CHECK ((gm.is_null_or_blank_string(synonym) IS FALSE))
ref_icpc_thes_sane_synonym | CHECK ((gm.is_null_or_blank_string(synonym) IS FALSE))

Index - Schema ref

## Table: ref.keyword_expansion

Arbitrary binary or textual snippets of data. Used as text macros or document "ribbons".

ref.keyword_expansion Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| keyword |  | UNIQUE#1
dem.staff.pk | fk_staff |  | UNIQUE#1
| pk |  | PRIMARY KEY

ref.keyword_expansion Constraints
Name | Constraint
--- | ---
keyword_expansion_keyword_check | CHECK ((btrim(keyword) <> ''::text))
ref_kwd_exp_binary_xor_textual | CHECK ((((binary_data IS NULL) AND (textual_data IS NOT NULL)) OR ((binary_data IS NOT NULL) AND (textual_data IS NULL))))
ref_kwd_exp_sane_data | CHECK (((binary_data IS NULL) OR (octet_length(binary_data) > 0)))
ref_kwd_exp_sane_keyword | CHECK ((gm.is_null_or_blank_string(keyword) IS FALSE))
ref_kwd_exp_sane_text | CHECK ((gm.is_null_or_non_empty_string(textual_data) IS TRUE))

Index - Schema ref

## Table: ref.lnk_dose2drug

Links doses to drug products

ref.lnk_dose2drug Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.drug_product.pk | fk_drug_product |  |
ref.dose.pk | fk_dose |  |
| pk |  | PRIMARY KEY

Table ref.lnk_dose2drug Inherits audit_fields,

ref.lnk_dose2drug Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- clin.substance_intake

Index - Schema ref

## Table: ref.lnk_loinc2substance

Links LOINC codes to substances (for monitoring).

ref.lnk_loinc2substance Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
ref.substance.pk | fk_substance |  |

Table ref.lnk_loinc2substance Inherits audit_fields,

ref.lnk_loinc2substance Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
ref_ll2s_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))
ref_ll2s_sane_loinc | CHECK ((gm.is_null_or_blank_string(loinc) IS FALSE))

Index - Schema ref

## Table: ref.loinc

holds LOINC codes

ref.loinc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
ref.data_source.pk | fk_data_source |  |

Table ref.loinc Inherits coding_system_root,

idx_ref_loinc_fk_data_src fk_data_source

Index - Schema ref

## Table: ref.ops

Holds OPS (German ICPM-CM) codes.

ref.ops Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.data_source.pk | fk_data_source |  |
| pk |  | PRIMARY KEY

Table ref.ops Inherits coding_system_root,

idx_ref_ops_fk_data_src fk_data_source

Index - Schema ref

## Table: ref.other_code

Holds codes from "other" coding systems for which no specific tables exist just yet.

ref.other_code Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.data_source.pk | fk_data_source |  |
| pk |  | PRIMARY KEY

Table ref.other_code Inherits coding_system_root,

idx_ref_other_code_fk_data_src fk_data_source

Index - Schema ref

## Table: ref.papersizes

ref.papersizes Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| name |  | UNIQUE

Tables referencing this one via Foreign Key Constraints:

- public.form_print_defs

Index - Schema ref

## Table: ref.paperwork_templates

form and letter template definitions

ref.paperwork_templates Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| gnumed_revision |  | UNIQUE#1
| name_short |  | UNIQUE#2
| name_long |  | UNIQUE#1 UNIQUE#2
| pk |  | PRIMARY KEY
ref.form_types.pk | fk_template_type |  |
| external_version |  | UNIQUE#1

Table ref.paperwork_templates Inherits audit_fields,

ref.paperwork_templates Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
ref_templates_engine_range | CHECK ((engine = ANY (ARRAY['T'::text, 'L'::text, 'H'::text, 'O'::text, 'I'::text, 'G'::text, 'P'::text, 'A'::text, 'X'::text, 'S'::text])))

Tables referencing this one via Foreign Key Constraints:

- clin.form_instances

- public.form_fields

Index - Schema ref

## Table: ref.substance

Holds substances that are consumed by patients for various reasons.

ref.substance Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY

Table ref.substance Inherits audit_fields,

ref.substance Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
ref_substance_sane_desc | CHECK ((gm.is_null_or_non_empty_string(description) IS TRUE))
ref_substance_sane_instructions | CHECK ((gm.is_null_or_non_empty_string(intake_instructions) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- ref.dose

- ref.lnk_loinc2substance

idx_substance_atc atc

Index - Schema ref

## Table: ref.tag_image

Text+image tags that can be applied to a person for characterization.

ref.tag_image Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk |  | PRIMARY KEY
| description |  | UNIQUE

Table ref.tag_image Inherits audit_fields,

ref.tag_image Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
ref_tag_image_sane_desc | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))
ref_tag_image_sane_filename | CHECK ((gm.is_null_or_non_empty_string(filename) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- dem.identity_tag

Index - Schema ref

## View: ref.v_atc

ref.v_atc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT a.pk AS pk_atc
    ,
        a.code AS atc
    ,
        a.term
    ,
        a.administration_route
    ,
        a.comment
    ,

    (octet_length
         (a.code) < 7
    ) AS is_group_code
    ,

    (octet_length
         (a.code) -
         (octet_length
               (a.code) / 3
         )
    ) AS atc_level
    ,
        rds.name_long
    ,
        rds.name_short
    ,
        rds.version
    ,
        rds.lang
    ,
        a.pk_coding_system
    ,
        a.fk_data_source AS pk_data_source

    FROM (ref.atc a

      JOIN ref.data_source rds
        ON (
               (rds.pk = a.fk_data_source)
         )
    );

Index - Schema ref

## View: ref.v_auto_hints

ref.v_auto_hints Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT auto_hint.pk AS pk_auto_hint
    ,
        auto_hint.query
    ,
        auto_hint.recommendation_query
    ,
        auto_hint.title
    ,
        auto_hint.hint
    ,
        auto_hint.url
    ,
        auto_hint.is_active
    ,
        auto_hint.source
    ,
        auto_hint.lang
    ,
        auto_hint.popup_type
    ,
        auto_hint.highlight_as_priority
    ,
        NULL::text AS rationale4suppression
    ,
        NULL::text AS recommendation
    ,
        md5
    (
         (
               (
                     (
                           (COALESCE
                                 (auto_hint.query
                                       ,''::text
                                 ) || COALESCE
                                 (auto_hint.recommendation_query
                                       ,''::text
                                 )
                           ) || COALESCE
                           (auto_hint.title
                                 ,''::text
                           )
                     ) || COALESCE
                     (auto_hint.hint
                           ,''::text
                     )
               ) || COALESCE
               (auto_hint.url
                     ,''::text
               )
         )
    ) AS md5_sum
    ,
        auto_hint.xmin AS xmin_auto_hint

    FROM ref.auto_hint;

Index - Schema ref

## View: ref.v_billables

ref.v_billables Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_b.pk AS pk_billable
    ,
        r_b.code AS billable_code
    ,
        r_b.term AS billable_description
    ,
        r_b.amount AS raw_amount
    ,

    (r_b.amount +
         (r_b.amount * r_b.vat_multiplier)
    ) AS amount_with_vat
    ,
        r_b.currency
    ,
        r_b.comment
    ,
        r_b.vat_multiplier
    ,
        r_b.active
    ,
        r_b.discountable
    ,
        r_ds.name_long AS catalog_long
    ,
        r_ds.name_short AS catalog_short
    ,
        r_ds.version AS catalog_version
    ,
        r_ds.lang AS catalog_language
    ,
        r_b.fk_data_source AS pk_data_source
    ,
        r_b.pk_coding_system AS pk_coding_system_root
    ,
        r_b.xmin AS xmin_billable

    FROM (ref.billable r_b

    LEFT JOIN ref.data_source r_ds
        ON (
               (r_b.fk_data_source = r_ds.pk)
         )
    );

Index - Schema ref

## View: ref.v_coded_terms

This view aggregates all official (reference) terms, including "official" synonyms, for which a corresponding code is known to the system.

ref.v_coded_terms Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_csr.code
    ,
        r_csr.term
    ,
        r_ds.name_short AS coding_system
    ,
        r_ds.name_long AS coding_system_long
    ,
        r_ds.version
    ,
        r_ds.lang
    ,
        r_csr.pk_coding_system AS pk_generic_code

    FROM (ref.coding_system_root r_csr

      JOIN ref.data_source r_ds
        ON (
               (r_csr.fk_data_source = r_ds.pk)
         )
    )
    UNION

    SELECT ri.code
    ,
        r_it.synonym AS term
    ,
        r_ds.name_short AS coding_system
    ,
        r_ds.name_long AS coding_system_long
    ,
        r_ds.version
    ,
        r_ds.lang
    ,
        r_it.fk_code AS pk_generic_code

    FROM (
         (ref.icpc_thesaurus r_it

       LEFT JOIN ref.icpc ri
              ON (
                     (r_it.fk_code = ri.pk_coding_system)
               )
         )

    LEFT JOIN ref.data_source r_ds
        ON (
               (ri.fk_data_source = r_ds.pk)
         )
    );

Index - Schema ref

## View: ref.v_drug_components

ref.v_drug_components Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_ld2d.pk AS pk_component
    ,
        r_dp.description AS product
    ,
        r_vsd.substance
    ,
        r_vsd.amount
    ,
        r_vsd.unit
    ,
        r_vsd.dose_unit
    ,
        r_dp.preparation
    ,
        _
    (r_dp.preparation) AS l10n_preparation
    ,
        r_vsd.intake_instructions
    ,
        r_vsd.loincs
    ,
        r_vsd.atc_substance
    ,
        r_dp.atc_code AS atc_drug
    ,
        r_dp.external_code
    ,
        r_dp.external_code_type
    ,
        r_dp.is_fake AS is_fake_product
    ,

    (EXISTS
         (
          SELECT 1

            FROM clin.substance_intake c_si

           WHERE (c_si.fk_drug_component = r_ld2d.pk)
             LIMIT 1
         )
    ) AS is_in_use
    ,
        r_dp.pk AS pk_drug_product
    ,
        r_vsd.pk_dose
    ,
        r_vsd.pk_substance
    ,
        r_dp.fk_data_source AS pk_data_source
    ,
        r_ld2d.xmin AS xmin_lnk_dose2drug

    FROM (
         (ref.lnk_dose2drug r_ld2d

            JOIN ref.drug_product r_dp
              ON (
                     (r_ld2d.fk_drug_product = r_dp.pk)
               )
         )

      JOIN ref.v_substance_doses r_vsd
        ON (
               (r_ld2d.fk_dose = r_vsd.pk_dose)
         )
    );

Index - Schema ref

## View: ref.v_drug_products

ref.v_drug_products Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_dp.pk AS pk_drug_product
    ,
        r_dp.description AS product
    ,
        r_dp.preparation
    ,
        _
    (r_dp.preparation) AS l10n_preparation
    ,
        r_dp.atc_code AS atc
    ,
        r_dp.external_code
    ,
        r_dp.external_code_type
    ,
        r_dp.is_fake AS is_fake_product
    ,

    (EXISTS
         (
          SELECT 1

            FROM ref.vaccine c_v

           WHERE (c_v.fk_drug_product = r_dp.pk)
         )
    ) AS is_vaccine
    ,
        ARRAY
    (
    SELECT row_to_json
         (component_row.*) AS row_to_json

      FROM (
          SELECT r_vsd.substance
               ,
                        r_vsd.amount
               ,
                        r_vsd.unit
               ,
                        r_vsd.dose_unit
               ,
                        r_vsd.intake_instructions
               ,
                        r_vsd.loincs
               ,
                        r_vsd.atc_substance
               ,
                        r_ld2d.pk AS pk_component
               ,
                        r_vsd.pk_dose
               ,
                        r_vsd.pk_substance

            FROM (ref.lnk_dose2drug r_ld2d

                  JOIN ref.v_substance_doses r_vsd
                    ON (
                           (r_ld2d.fk_dose = r_vsd.pk_dose)
                     )
               )

           WHERE (r_ld2d.fk_drug_product = r_dp.pk)
         ) component_row
    ) AS components
    ,
        r_dp.fk_data_source AS pk_data_source
    ,
        r_dp.xmin AS xmin_drug_product

    FROM ref.drug_product r_dp;

Index - Schema ref

## View: ref.v_generic_codes

Denormalized generic codes.

ref.v_generic_codes Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_csr.pk_coding_system AS pk_generic_code
    ,
        r_csr.code
    ,
        r_csr.term
    ,
        r_ds.name_long
    ,
        r_ds.name_short
    ,
        r_ds.version
    ,
        r_ds.lang
    ,

    (r_csr.tableoid)::regclass AS code_table
    ,
        r_csr.fk_data_source AS pk_data_source

    FROM (ref.coding_system_root r_csr

      JOIN ref.data_source r_ds
        ON (
               (r_ds.pk = r_csr.fk_data_source)
         )
    );

Index - Schema ref

## View: ref.v_icpc

View over denormalized ICPC2 data.

ref.v_icpc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT ri.code
    ,
        ri.code_extension
    ,

    (ri.code || COALESCE
         (ri.code_extension
               ,''::text
         )
    ) AS extended_code
    ,
        ri.term
    ,
        ri.short_description
    ,
        ri.fk_chapter AS code_chapter
    ,
        rich.description AS chapter
    ,
        _
    (rich.description) AS l10n_chapter
    ,
        ri.fk_component AS code_component
    ,
        rico.description AS component
    ,
        _
    (rico.description) AS l10n_component
    ,
        rico.typical_soap_cat
    ,
        ri.icd10
    ,
        ri.criteria
    ,
        ri.inclusions
    ,
        ri.exclusions
    ,
        ri.see_also
    ,
        ri.comment
    ,
        rds.name_short
    ,
        rds.name_long
    ,
        rds.version
    ,
        rds.lang
    ,
        ri.pk AS pk_icpc
    ,
        ri.fk_data_source AS pk_data_source

    FROM (
         (
               (ref.icpc ri

                  JOIN ref.data_source rds
                    ON (
                           (ri.fk_data_source = rds.pk)
                     )
               )

            JOIN ref.icpc_chapter rich
              ON (
                     (ri.fk_chapter = rich.chapter)
               )
         )

      JOIN ref.icpc_component rico
        ON (
               (ri.fk_component = rico.component)
         )
    );

Index - Schema ref

## View: ref.v_icpc_thesaurus

View over denormalized ICPC2 thesaurus.

ref.v_icpc_thesaurus Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT rit.pk AS pk_icpc_thesaurus
    ,
        ri.code
    ,
        ri.term
    ,
        rit.synonym
    ,
        rit.pk_thesaurus
    ,
        rit.fk_code AS pk_coding_system
    ,
        ri.pk AS pk_icpc

    FROM (ref.icpc_thesaurus rit

      JOIN ref.icpc ri
        ON (
               (rit.fk_code = ri.pk_coding_system)
         )
    );

Index - Schema ref

## View: ref.v_indications4vaccine

Denormalizes indications per vaccine.

ref.v_indications4vaccine Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_v.pk AS pk_vaccine
    ,
        r_dp.description AS vaccine
    ,
        r_dp.preparation
    ,
        _
    (r_dp.preparation) AS l10n_preparation
    ,
        r_dp.atc_code
    ,
        r_dp.is_fake AS is_fake_vaccine
    ,
        r_vr.abbreviation AS route_abbreviation
    ,
        r_vr.description AS route_description
    ,
        r_v.is_live
    ,
        r_v.min_age
    ,
        r_v.max_age
    ,
        r_v.comment
    ,
        _
    (
         (r_s.atc || '-target'::text)
         ,'en'::text
    ) AS indication
    ,
            CASE
                WHEN
    (_
         (
               (r_s.atc || '-target'::text)
         ) =
         (r_s.atc || '-target'::text)
    ) THEN _
    (
         (r_s.atc || '-target'::text)
         ,'en'::text
    )
                ELSE _
    (
         (r_s.atc || '-target'::text)
    )
            END AS l10n_indication
    ,
        r_dp.external_code
    ,
        r_dp.external_code_type
    ,
        ARRAY
    (
    SELECT row_to_json
         (indication_row.*) AS row_to_json

      FROM (
          SELECT _
               (
                     (r_s_1.atc || '-target'::text)
                     ,'en'::text
               ) AS indication
               ,
                            CASE
                                WHEN
               (_
                     (
                           (r_s_1.atc || '-target'::text)
                     ) =
                     (r_s_1.atc || '-target'::text)
               ) THEN _
               (
                     (r_s_1.atc || '-target'::text)
                     ,'en'::text
               )
                                ELSE _
               (
                     (r_s_1.atc || '-target'::text)
               )
                            END AS l10n_indication
               ,
                        r_s_1.atc AS atc_indication

            FROM (
                     (ref.lnk_dose2drug r_ld2d_1

                        JOIN ref.dose r_d_1
                          ON (
                                 (r_d_1.pk = r_ld2d_1.fk_dose)
                           )
                     )

                  JOIN ref.substance r_s_1
                    ON (
                           (r_d_1.fk_substance = r_s_1.pk)
                     )
               )

           WHERE (r_ld2d_1.fk_drug_product = r_dp.pk)
         ) indication_row
    ) AS indications
    ,
        r_v.id_route AS pk_route
    ,
        r_v.fk_drug_product AS pk_drug_product
    ,
        r_dp.fk_data_source AS pk_data_source
    ,
        r_s.atc AS atc_indication
    ,
        r_v.xmin AS xmin_vaccine

    FROM (
         (
               (
                     (
                           (ref.vaccine r_v

                         LEFT JOIN ref.vacc_route r_vr
                                ON (
                                       (r_vr.id = r_v.id_route)
                                 )
                           )

                        JOIN ref.drug_product r_dp
                          ON (
                                 (r_dp.pk = r_v.fk_drug_product)
                           )
                     )

                  JOIN ref.lnk_dose2drug r_ld2d
                    ON (
                           (r_ld2d.fk_drug_product = r_dp.pk)
                     )
               )

            JOIN ref.dose r_d
              ON (
                     (r_d.pk = r_ld2d.fk_dose)
               )
         )

      JOIN ref.substance r_s
        ON (
               (r_d.fk_substance = r_s.pk)
         )
    );

Index - Schema ref

## View: ref.v_keyword_expansions

Just a slightly more convenient view over expansions.

ref.v_keyword_expansions Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_ke.pk AS pk_expansion
    ,
        r_ke.fk_staff AS pk_staff
    ,
        r_ke.keyword
    ,
        r_ke.textual_data AS expansion
    ,
        r_ke.encrypted AS is_encrypted
    ,

    (r_ke.binary_data IS NULL) AS is_textual
    ,
        octet_length
    (r_ke.binary_data) AS data_size
    ,

    (r_ke.fk_staff IS NULL) AS public_expansion
    ,

    (r_ke.fk_staff IS NOT NULL) AS private_expansion
    ,
        r_ke.owner
    ,
        r_ke.xmin AS xmin_expansion

    FROM ref.keyword_expansion r_ke;

Index - Schema ref

## View: ref.v_lnk_loincs2substances

ref.v_lnk_loincs2substances Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_ll2s.pk AS pk_lnk_loinc2substance
    ,
        r_s.description AS substance
    ,
        r_ll2s.loinc
    ,
        r_ll2s.max_age
    ,
        r_ll2s.comment
    ,
        r_s.atc
    ,
        r_s.pk AS pk_substance
    ,
        r_ll2s.xmin AS xmin_lnk_loinc2substance

    FROM (ref.substance r_s

      JOIN ref.lnk_loinc2substance r_ll2s
        ON (
               (r_ll2s.fk_substance = r_s.pk)
         )
    );

Index - Schema ref

## View: ref.v_paperwork_templates

ref.v_paperwork_templates Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_pt.pk AS pk_paperwork_template
    ,
        r_pt.name_short
    ,
        r_pt.name_long
    ,
        r_pt.external_version
    ,
        r_pt.gnumed_revision
    ,

    (
    SELECT r_ft.name

      FROM ref.form_types r_ft

     WHERE (r_ft.pk = r_pt.fk_template_type)
    ) AS template_type
    ,

    (
    SELECT _
         (r_ft.name) AS _

      FROM ref.form_types r_ft

     WHERE (r_ft.pk = r_pt.fk_template_type)
    ) AS l10n_template_type
    ,
        COALESCE
    (r_pt.instance_type
         , (
          SELECT r_ft.name

            FROM ref.form_types r_ft

           WHERE (r_ft.pk = r_pt.fk_template_type)
         )
    ) AS instance_type
    ,
        COALESCE
    (_
         (r_pt.instance_type)
         , (
          SELECT _
               (r_ft.name) AS _

            FROM ref.form_types r_ft

           WHERE (r_ft.pk = r_pt.fk_template_type)
         )
    ) AS l10n_instance_type
    ,
        r_pt.engine
    ,
        r_pt.in_use
    ,
        r_pt.edit_after_substitution
    ,
        r_pt.filename
    ,
            CASE
                WHEN
    (r_pt.data IS NOT NULL) THEN true
                ELSE false
            END AS has_template_data
    ,
        r_pt.modified_when AS last_modified
    ,
        COALESCE
    (
         (
          SELECT d_s.short_alias

            FROM dem.staff d_s

           WHERE (d_s.db_user = r_pt.modified_by)
         )
         , (
               ('<'::text ||
                     (r_pt.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,
        r_pt.fk_template_type AS pk_template_type
    ,
        r_pt.xmin AS xmin_paperwork_template

    FROM ref.paperwork_templates r_pt;

Index - Schema ref

## View: ref.v_substance_doses

ref.v_substance_doses Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_d.pk AS pk_dose
    ,
        r_vs.substance
    ,
        r_d.amount
    ,
        r_d.unit
    ,
        r_d.dose_unit
    ,
        r_vs.intake_instructions
    ,
        r_vs.atc AS atc_substance
    ,
        r_vs.loincs
    ,
        r_vs.pk_substance
    ,
        r_d.xmin AS xmin_dose

    FROM (ref.dose r_d

      JOIN ref.v_substances r_vs
        ON (
               (r_d.fk_substance = r_vs.pk_substance)
         )
    );

Index - Schema ref

## View: ref.v_substances

ref.v_substances Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_s.pk AS pk_substance
    ,
        r_s.description AS substance
    ,
        r_s.intake_instructions
    ,
        r_s.atc
    ,
        ARRAY
    (
    SELECT row_to_json
         (loinc_row.*) AS row_to_json

      FROM (
          SELECT r_ll2s.loinc
               ,
                        r_ll2s.comment
               ,
                        date_part
               ('epoch'::text
                     , r_ll2s.max_age
               ) AS max_age_in_secs
               ,

               (r_ll2s.max_age)::text AS max_age_str

            FROM ref.lnk_loinc2substance r_ll2s

           WHERE (r_ll2s.fk_substance = r_s.pk)
         ) loinc_row
    ) AS loincs
    ,
        r_s.xmin AS xmin_substance

    FROM ref.substance r_s;

Index - Schema ref

## View: ref.v_tag_images_no_data

ref.v_tag_images_no_data Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT rti.pk AS pk_tag_image
    ,
        rti.description
    ,
        _
    (rti.description) AS l10n_description
    ,
        rti.filename
    ,
        octet_length
    (COALESCE
         (rti.image
               ,'\x'::bytea
         )
    ) AS size
    ,

    (EXISTS
         (
          SELECT 1

            FROM dem.identity_tag dit

           WHERE (dit.fk_tag = rti.pk)
             LIMIT 1
         )
    ) AS is_in_use
    ,
        rti.xmin AS xmin_tag_image

    FROM ref.tag_image rti;

Index - Schema ref

## View: ref.v_vaccines

A list of vaccines.

ref.v_vaccines Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT r_v.pk AS pk_vaccine
    ,
        r_dp.description AS vaccine
    ,
        r_dp.preparation
    ,
        _
    (r_dp.preparation) AS l10n_preparation
    ,
        r_dp.atc_code
    ,
        r_dp.is_fake AS is_fake_vaccine
    ,
        r_vr.abbreviation AS route_abbreviation
    ,
        r_vr.description AS route_description
    ,
        r_v.is_live
    ,
        r_v.min_age
    ,
        r_v.max_age
    ,
        r_v.comment
    ,
        ARRAY
    (
    SELECT row_to_json
         (indication_row.*) AS row_to_json

      FROM (
          SELECT _
               (
                     (r_s.atc || '-target'::text)
                     ,'en'::text
               ) AS indication
               ,
                            CASE
                                WHEN
               (_
                     (
                           (r_s.atc || '-target'::text)
                     ) =
                     (r_s.atc || '-target'::text)
               ) THEN _
               (
                     (r_s.atc || '-target'::text)
                     ,'en'::text
               )
                                ELSE _
               (
                     (r_s.atc || '-target'::text)
               )
                            END AS l10n_indication
               ,
                        r_s.atc AS atc_indication

            FROM (
                     (ref.lnk_dose2drug r_ld2d

                        JOIN ref.dose r_d
                          ON (
                                 (r_d.pk = r_ld2d.fk_dose)
                           )
                     )

                  JOIN ref.substance r_s
                    ON (
                           (r_d.fk_substance = r_s.pk)
                     )
               )

           WHERE (r_ld2d.fk_drug_product = r_dp.pk)
         ) indication_row
    ) AS indications
    ,
        r_dp.external_code
    ,
        r_dp.external_code_type
    ,
        r_v.id_route AS pk_route
    ,
        r_v.fk_drug_product AS pk_drug_product
    ,
        r_dp.fk_data_source AS pk_data_source
    ,
        r_v.xmin AS xmin_vaccine

    FROM (
         (ref.vaccine r_v

            JOIN ref.drug_product r_dp
              ON (
                     (r_v.fk_drug_product = r_dp.pk)
               )
         )

    LEFT JOIN ref.vacc_route r_vr
        ON (
               (r_v.id_route = r_vr.id)
         )
    );

Index - Schema ref

## View: ref.v_your_keyword_expansions

View over the text expansions relevant to the current user: a private expansion set up for the current user overrides a public expansion of the same keyword.

ref.v_your_keyword_expansions Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

    SELECT DISTINCT
    ON (union_result.keyword) union_result.pk_expansion
    ,
        union_result.pk_staff
    ,
        union_result.keyword
    ,
        union_result.expansion
    ,
        union_result.is_encrypted
    ,
        union_result.is_textual
    ,
        union_result.data_size
    ,
        union_result.public_expansion
    ,
        union_result.private_expansion
    ,
        union_result.owner
    ,
        union_result.xmin_expansion

    FROM (
    SELECT r_ke.pk AS pk_expansion
         ,
                r_ke.fk_staff AS pk_staff
         ,
                r_ke.keyword
         ,
                r_ke.textual_data AS expansion
         ,
                r_ke.encrypted AS is_encrypted
         ,

         (r_ke.binary_data IS NULL) AS is_textual
         ,
                octet_length
         (r_ke.binary_data) AS data_size
         ,
                false AS public_expansion
         ,
                true AS private_expansion
         ,
                r_ke.owner
         ,
                r_ke.xmin AS xmin_expansion

      FROM ref.keyword_expansion r_ke

     WHERE (r_ke.fk_staff =
               (
                SELECT staff.pk

                  FROM dem.staff

                 WHERE (staff.db_user = "current_user"
                           ()
                     )
               )
         )

    UNION ALL

    SELECT r_ke.pk AS pk_expansion
         ,
                r_ke.fk_staff AS pk_staff
         ,
                r_ke.keyword
         ,
                r_ke.textual_data AS expansion
         ,
                r_ke.encrypted AS is_encrypted
         ,

         (r_ke.binary_data IS NULL) AS is_textual
         ,
                octet_length
         (r_ke.binary_data) AS data_size
         ,
                true AS public_expansion
         ,
                false AS private_expansion
         ,
                r_ke.owner
         ,
                r_ke.xmin AS xmin_expansion

      FROM ref.keyword_expansion r_ke

     WHERE (r_ke.fk_staff IS NULL)

    ORDER BY 9 DESC
    ) union_result;

Index - Schema ref

## Table: ref.vacc_route

definition of route via which vaccine is given, currently i.m. and p.o. only but may include "via genetically engineered food" etc in the future

ref.vacc_route Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| abbreviation |  | UNIQUE
| description |  | UNIQUE
| id |  | PRIMARY KEY

Table ref.vacc_route Inherits audit_fields,

ref.vacc_route Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))

Tables referencing this one via Foreign Key Constraints:

- ref.vaccine

Index - Schema ref

## Table: ref.vaccine

definition of a vaccine as available on the market

ref.vaccine Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
ref.drug_product.pk | fk_drug_product |  | UNIQUE
ref.vacc_route.id | id_route |  |
| pk |  | PRIMARY KEY

Table ref.vaccine Inherits audit_fields,

ref.vaccine Constraints
Name | Constraint
--- | ---
audit_audit_fields_sane_modified_when | CHECK (((modified_when <= clock_timestamp()) IS TRUE))
vaccine_sane_max_age | CHECK (((max_age IS NULL) OR (max_age < '150 years'::interval)))
vaccine_sane_min_age | CHECK (((min_age IS NULL) OR (((max_age IS NULL) AND (min_age < '150 years'::interval)) OR ((max_age IS NOT NULL) AND (min_age <= max_age)))))

Tables referencing this one via Foreign Key Constraints:

- clin.vaccination

idx_c_vaccine_id_route id_route

Index - Schema ref

## Function: ref.trf_announce_substance_in_brand_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "substance_in_brand_mod_db:"';
    	return NULL;
    end;

## Function: ref.trf_assert_product_has_components()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_msg text;
    BEGIN
    	PERFORM 1 FROM ref.lnk_dose2drug WHERE fk_drug_product = NEW.pk LIMIT 1;
    	IF FOUND THEN
    		RETURN NEW;
    	END IF;
    	_msg := '[ref.trf_assert_product_has_components()]: '
    		|| TG_OP
    		|| ' failed: no components (doses) linked to drug product ['
    		|| NEW.pk
    		|| '].'
    	;
    	RAISE EXCEPTION integrity_constraint_violation using message = _msg;
    	RETURN NEW;
    END;

## Function: ref.trf_assert_product_keeps_components()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_msg text;
    BEGIN
    	PERFORM 1 FROM ref.lnk_dose2drug WHERE fk_drug_product = OLD.pk LIMIT 1;
    	-- any components left ?
    	IF FOUND THEN
    		-- does not matter
    		RETURN OLD;
    	END IF;
    	PERFORM 1 FROM ref.drug_product WHERE pk = OLD.fk_drug_product LIMIT 1;
    	-- drug AND components deleted ?
    	IF NOT FOUND THEN
    		-- does not matter
    		RETURN OLD;
    	END IF;
    	_msg := '[ref.trf_assert_product_keeps_components()]: '
    		|| TG_OP
    		|| ' failed: no components (doses) linked to drug product ['
    		|| OLD.pk
    		|| '] anymore.'
    	;
    	RAISE EXCEPTION integrity_constraint_violation using message = _msg;
    	-- does not matter
    	RETURN OLD;
    END;

## Function: ref.trf_consumable_subst_normalize_amount()

### Returns: trigger

### Language: PLPGSQL

On INSERT/UPDATE drop .000 all-zero fractions from amounts.

    BEGIN
    	NEW.amount := gm.strip_allzeros_fraction(NEW.amount);
    	return NEW;
    END;

## Function: ref.trf_del_ref_code_tbl_check_backlink()

### Returns: trigger

### Language: PLPGSQL

When deleting from any child of ref.coding_system_root check whether its row is being used in any clin.lnk_code2item_root child.

    DECLARE
    	_msg text;
    BEGIN
    	perform 1 from clin.lnk_code2item_root where fk_generic_code = NEW.pk_coding_system;
    	if not FOUND then
    		return OLD;
    	end if;
    	_msg := 'ref.trf_del_ref_code_tbl_check_backlink(): DELETE from '
    		|| TG_TABLE_SCHEMA || '.' || TG_TABLE_NAME || ': '
    		|| 'pk_coding_system=(' || NEW.pk_coding_system || ') '
    		|| 'in use in clin.lnk_code2item_root.fk_generic_code, '
    		|| 'old pk_coding_system=(' || OLD.pk_coding_system || ')';
    	raise foreign_key_violation using message = _msg;
    	return OLD;
    END;

## Function: ref.trf_do_not_update_component_if_taken_by_patient()

### Returns: trigger

### Language: PLPGSQL

If this drug component is taken by any patient do not modify it ( amount, unit, substance, brand).

    BEGIN
    	if OLD.fk_brand = NEW.fk_brand then
    		if OLD.fk_substance = NEW.fk_substance then
    			return NEW;
    		end if;
    	end if;
    	perform 1 from clin.substance_intake c_si
    	where c_si.fk_drug_component = OLD.pk
    	limit 1;
    	if NOT FOUND then
    		return NEW;
    	end if;
    	raise exception '[ref.trf_do_not_update_component_if_taken_by_patient]: as long as drug component <%> is taken by a patient you cannot modify it', OLD.pk;
    	return NEW;
    END;

## Function: ref.trf_do_not_update_substance_if_taken_by_patient()

### Returns: trigger

### Language: PLPGSQL

If this substance is taken by any patient do not modify description, amount, or unit (case changes allowed).

    DECLARE
    	_msg text;
    BEGIN
    	-- allow for case insensitive non-changes
    	if upper(OLD.description) = upper(NEW.description) then
    		if OLD.amount = NEW.amount then
    			if upper(OLD.unit) = upper(NEW.unit) then
    				return NEW;
    			end if;
    		end if;
    	end if;
    	_msg := '[ref.trf_do_not_update_substance_if_taken_by_patient]: as long as substance <' || OLD.description || '> is taken by a patient you cannot modify it';
    	perform 1 from clin.substance_intake c_si
    	where c_si.fk_substance = OLD.pk
    	limit 1;
    	if FOUND then
    		raise exception '%', _msg;
    	end if;
    	PERFORM 1
    	FROM clin.substance_intake c_si
    	WHERE c_si.fk_drug_component IN (
    		-- get all PKs in component link table which
    		-- represent the substance we want to modify
    		SELECT
    			r_ls2b.pk
    		FROM
    			ref.lnk_substance2brand r_ls2b
    		WHERE
    			r_ls2b.fk_substance = OLD.pk
    	)
    	LIMIT 1;
    	if FOUND then
    		raise exception '%', _msg;
    	end if;
    	return NEW;
    END;

## Function: ref.trf_ins_upd_assert_dose_unit_across_drug_components()

### Returns: trigger

### Language: PLPGSQL

Assert that all substance doses linked into a multi-component drug carry the same <dose_unit>

    DECLARE
    	_dose_unit_count integer;
    	_msg text;
    BEGIN
    	SELECT count(1) into strict _dose_unit_count
    	FROM (
    		SELECT dose_unit
    		FROM ref.v_drug_components
    		WHERE pk_drug_product = NEW.fk_drug_product
    		GROUP BY dose_unit
    	) AS dose_unit_count;
    	if _dose_unit_count = 1 then
    		return NEW;
    	end if;
    	_msg := '[ref.trf_ins_upd_assert_dose_unit_across_drug_components()]: cannot link substance dose [' || NEW.fk_dose || '] '
    		|| 'to drug product [' || NEW.fk_drug_product || '] '
    		|| 'because all components must have the same <dose_unit>';
    	raise exception check_violation using message = _msg;
    	return NEW;
    END;

## Function: ref.trf_protect_template_data()

### Returns: trigger

### Language: PLPGSQL

Do not allow updates to the template data if any forms already use this template.

    BEGIN
    	if NEW.data != OLD.data then
    		-- look for references in clin.form_instances
    		-- if there are any we fail this update no matter what
    		perform 1 from clin.form_instances where fk_form_def = NEW.pk;
    		if FOUND then
    			raise exception 'Updating ref.paperwork_templates.data not allowed because it is referenced from existing forms.';
    		end if;
    	end if;
    	-- otherwise let it happen
    	return NEW;
    END;

## Function: ref.trf_true_brands_must_have_components()

### Returns: trigger

### Language: PLPGSQL

There must always be at least one component for any existing non-fake branded drug.

    DECLARE
    	_brand_is_deleted boolean;
    	_is_fake_brand boolean;
    	_has_other_components boolean;
    BEGIN
    	-- if an UPDATE does NOT move the component to another drug
    	-- there WILL be at least one component left
    	if TG_OP = 'UPDATE' then
    		if NEW.fk_brand = OLD.fk_brand then
    			return NEW;
    		end if;
    	end if;
    	-- fake drugs may become devoid of components
    	select
    		is_fake into _is_fake_brand
    	from
    		ref.branded_drug
    	where
    		pk = OLD.fk_brand
    	;
    	if _is_fake_brand is TRUE then
    		return OLD;
    	end if;
    	-- DELETEs may proceed if the drug has been deleted, too
    	if TG_OP = 'DELETE' then
    		select not exists (
    			select 1 from ref.branded_drug
    			where pk = OLD.fk_brand
    		) into _brand_is_deleted;
    		if _brand_is_deleted is TRUE then
    			return OLD;
    		end if;
    	end if;
    	-- if there are other components left after the
    	-- UPDATE or DELETE everything is fine
    	select exists (
    		select 1 from ref.lnk_substance2brand
    		where
    			fk_brand = OLD.fk_brand
    				and
    			fk_substance != OLD.fk_substance
    		limit 1
    	) into _has_other_components;
    	if _has_other_components is TRUE then
    		return OLD;
    	end if;
    	raise exception '[ref.trf_true_brands_must_have_components::%] brand must have components (brand <%> component <%>)', TG_OP, OLD.fk_brand, OLD.fk_substance;
    	return OLD;
    END;

## Function: ref.trf_upd_assert_dose_unit_in_multi_component_drugs()

### Returns: trigger

### Language: PLPGSQL

Assert that after updates to ref.dose.dose_unit all substance doses linked into a multi-component drug still carry the same <dose_unit>.

    DECLARE
    	_pk_drug_product integer;
    	_component_count integer;
    	_dose_unit_count integer;
    	_msg text;
    BEGIN
    	SELECT fk_drug_product into strict _pk_drug_product
    	FROM ref.lnk_dose2drug
    	WHERE fk_dose = NEW.pk;
    	if FOUND IS FALSE then
    		return NEW;
    	end if;
    	SELECT count(1) into strict _component_count
    	FROM ref.lnk_dose2drug
    	WHERE fk_drug_product = _pk_drug_product;
    	if _component_count = 1 then
    		return NEW;
    	end if;
    	SELECT count(1) into strict _dose_unit_count
    	FROM (
    		SELECT dose_unit
    		FROM ref.v_drug_components
    		WHERE pk_drug_product = _pk_drug_product
    		GROUP BY dose_unit
    	) AS dose_unit_count;
    	if _dose_unit_count = 1 then
    		return NEW;
    	end if;
    	_msg := '[ref.trf_upd_assert_dose_unit_in_multi_component_drugs()]: cannot change <dose_unit> on dose [' || NEW.pk || '] '
    		|| 'from [' || coalesce(OLD.dose_unit, '<NULL>') || '] '
    		|| 'to [' || coalesce(NEW.dose_unit, '<NULL>') || '] '
    		|| 'because all doses linked to drug product [' || _pk_drug_product || '] '
    		|| 'must have the same <dose_unit>';
    	raise exception check_violation using message = _msg;
    	return NEW;
    END;

## Function: ref.trf_upd_ref_code_tbl_check_backlink()

### Returns: trigger

### Language: PLPGSQL

When updating any child of ref.coding_system_root check whether its row is being used in any clin.lnk_code2item_root child.

    DECLARE
    	_msg text;
    BEGIN
    	if NEW.pk_coding_system = OLD.pk_coding_system then
    		return NEW;
    	end if;
    	perform 1 from clin.lnk_code2item_root where fk_generic_code = NEW.pk_coding_system;
    	if not FOUND then
    		return NEW;
    	end if;
    	_msg := 'ref.trf_upd_ref_code_tbl_check_backlink(): UPDATE of '
    		|| TG_TABLE_SCHEMA || '.' || TG_TABLE_NAME || ': '
    		|| 'pk_coding_system=(' || NEW.pk_coding_system || ') '
    		|| 'in use in clin.lnk_code2item_root.fk_generic_code, '
    		|| 'old pk_coding_system=(' || OLD.pk_coding_system || ')';
    	raise foreign_key_violation using message = _msg;
    	return OLD;
    END;

# Schema staging

A schema used for staging data imports.

## Table: staging.lab_request

Used to stage lab requests (from hl7 files, currently).

staging.lab_request Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
clin.test_org.pk | fk_test_org |  | UNIQUE#1
| request_id |  | UNIQUE#1
| pk |  | PRIMARY KEY

staging.lab_request Constraints
Name | Constraint
--- | ---
clin_root_item_soap_cat_check | CHECK (((soap_cat IS NULL) OR (lower(soap_cat) = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text]))))
lab_request_request_id_check | CHECK ((btrim(request_id) <> ''::text))
lab_request_request_status_check | CHECK ((request_status = ANY (ARRAY['pending'::text, 'preliminary'::text, 'partial'::text, 'final'::text])))
staging_request_sane_request_id | CHECK ((gm.is_null_or_blank_string(request_id) IS FALSE))
staging_request_sane_status | CHECK ((request_status = ANY (ARRAY['pending'::text, 'preliminary'::text, 'partial'::text, 'final'::text])))

Tables referencing this one via Foreign Key Constraints:

- staging.test_result

lab_request_fk_episode_key fk_episode

Index - Schema staging

## Table: staging.lnk_vacc_ind2subst_dose

staging.lnk_vacc_ind2subst_dose Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| is_live |  | UNIQUE#2
| fk_indication |  | UNIQUE#1 UNIQUE#2
ref.dose.pk | fk_dose |  | UNIQUE#1

Index - Schema staging

## Table: staging.loinc_staging

used for importing LOINC data, columns correspond 1:1 with the LOINC CSV file fields

staging.loinc_staging Structure
F-Key | Name | Type | Description
--- | --- | --- | ---

Index - Schema staging

## Table: staging.test_result

Used to stage test results (from hl7 files, currently).

staging.test_result Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
staging.lab_request.pk | fk_request |  |
| pk |  | PRIMARY KEY

staging.test_result Constraints
Name | Constraint
--- | ---
clin_root_item_soap_cat_check | CHECK (((soap_cat IS NULL) OR (lower(soap_cat) = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text]))))
numval_needs_unit | CHECK ((((val_num IS NOT NULL) AND (btrim(COALESCE(val_unit, ''::text)) <> ''::text)) OR (val_num IS NULL)))
staging_numval_needs_unit | CHECK ((((val_num IS NOT NULL) AND (btrim(COALESCE(val_unit, ''::text)) <> ''::text)) OR (val_num IS NULL)))
staging_sane_value | CHECK (((val_num IS NOT NULL) OR (val_alpha IS NOT NULL) OR ((val_num IS NULL) AND (val_alpha <> ''::text) AND (val_alpha IS NOT NULL))))
test_result_check | CHECK (((val_num IS NOT NULL) OR (val_alpha IS NOT NULL) OR ((val_num IS NULL) AND (val_alpha <> ''::text) AND (val_alpha IS NOT NULL))))

test_result_fk_episode_key fk_episode test_result_fk_type_key fk_type

Index - Schema staging

Generated by PostgreSQL Autodoc

W3C HTML 4.01 Strict