Dumped on 2012-02-09

# Index of database - gnumed_v16

- au

- referral

- audit

- audit_fields
- audit_trail
- audited_tables
- log_access_log
- log_active_substance
- log_address
- log_allergy
- log_allergy_state
- log_beh_fall_typ
- log_behandlungsfall
- log_branded_drug
- 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_encounter
- log_episode
- 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_constraint2vacc_course
- log_lnk_identity2ext_id
- log_lnk_identity2primary_doc
- log_lnk_job2person
- 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_prax_geb_paid
- log_procedure
- log_referral
- log_relation_types
- log_report_query
- log_staff
- log_staff_role
- log_state
- log_street
- log_substance_in_brand
- log_substance_intake
- log_tag_image
- log_test_org
- 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_beh_fall_typ()
- ft_del_behandlungsfall()
- ft_del_branded_drug()
- 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_encounter()
- ft_del_episode()
- 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_constraint2vacc_course()
- ft_del_lnk_identity2ext_id()
- ft_del_lnk_identity2primary_doc()
- ft_del_lnk_job2person()
- 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_prax_geb_paid()
- ft_del_procedure()
- ft_del_ref_source()
- ft_del_referral()
- ft_del_relation_types()
- ft_del_report_query()
- ft_del_staff()
- ft_del_staff_role()
- ft_del_state()
- ft_del_street()
- ft_del_substance_in_brand()
- ft_del_substance_intake()
- ft_del_tag_image()
- ft_del_test_org()
- 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_beh_fall_typ()
- ft_ins_behandlungsfall()
- ft_ins_branded_drug()
- 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_encounter()
- ft_ins_episode()
- 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_constraint2vacc_course()
- ft_ins_lnk_identity2ext_id()
- ft_ins_lnk_identity2primary_doc()
- ft_ins_lnk_job2person()
- 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_prax_geb_paid()
- ft_ins_procedure()
- ft_ins_ref_source()
- ft_ins_referral()
- ft_ins_relation_types()
- ft_ins_report_query()
- ft_ins_staff()
- ft_ins_staff_role()
- ft_ins_state()
- ft_ins_street()
- ft_ins_substance_in_brand()
- ft_ins_substance_intake()
- ft_ins_tag_image()
- ft_ins_test_org()
- 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_beh_fall_typ()
- ft_upd_behandlungsfall()
- ft_upd_branded_drug()
- 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_encounter()
- ft_upd_episode()
- 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_constraint2vacc_course()
- ft_upd_lnk_identity2ext_id()
- ft_upd_lnk_identity2primary_doc()
- ft_upd_lnk_job2person()
- 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_prax_geb_paid()
- ft_upd_procedure()
- ft_upd_ref_source()
- ft_upd_referral()
- ft_upd_relation_types()
- ft_upd_report_query()
- ft_upd_staff()
- ft_upd_staff_role()
- ft_upd_state()
- ft_upd_street()
- ft_upd_substance_in_brand()
- ft_upd_substance_intake()
- ft_upd_tag_image()
- ft_upd_test_org()
- 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_item
- trf_announce_bill_item_mod()

- blobs

- doc_desc
- doc_med
- doc_obj
- doc_type
- lnk_doc2hospital_stay
- 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
- delete_document(integer, integer)
- trf_announce_doc_mod()
- trf_announce_doc_obj_review_mod_no_pk()
- trf_announce_doc_page_mod_no_pk()
- trf_announce_doc_type_mod_no_pk()
- 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
- active_substance
- allergy
- allergy_state
- clin_aux_note
- clin_diag
- clin_item_type
- clin_narrative
- clin_root_item
- encounter
- encounter_type
- episode
- family_history
- fhx_relation_type
- form_data
- form_instances
- health_issue
- hospital_stay
- incoming_data_unmatchable
- incoming_data_unmatched
- keyword_expansion
- lab_request
- lnk_code2aoe
- lnk_code2episode
- lnk_code2fhx
- lnk_code2h_issue
- lnk_code2item_root
- lnk_code2narrative
- lnk_code2procedure
- lnk_code2rfe
- lnk_constraint2vacc_course
- lnk_pat2vaccination_course
- lnk_substance2episode
- lnk_tst2norm
- lnk_ttype2unified_type
- lnk_type2item
- lnk_vaccination_course2schedule
- lnk_vaccine2inds
- meta_test_type
- procedure
- review_root
- reviewed_test_results
- soap_cat_ranks
- substance_intake
- test_org
- test_result
- test_type
- v_emr_journal
- v_family_history
- v_family_history_journal
- v_health_issues
- v_health_issues_journal
- v_indications4vaccine
- v_keyword_expansions
- v_linked_codes
- v_meta_test_types
- v_most_recent_encounters
- 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_hospital_stays
- v_pat_hospital_stays_journal
- v_pat_items
- v_pat_last_vacc4indication
- v_pat_narrative
- v_pat_narrative_journal
- v_pat_procedures
- v_pat_procedures_journal
- v_pat_substance_intake
- v_pat_substance_intake_journal
- v_pat_vaccinations
- v_pat_vaccinations_journal
- v_pat_vaccs4indication
- v_potential_problem_list
- v_problem_list
- v_reviewed_items
- v_test_orgs
- v_test_results
- v_test_results_journal
- v_test_types
- v_unified_test_types
- v_vaccination_courses_in_schedule
- v_vaccination_definitions4course
- v_vaccines
- v_waiting_list
- v_your_keyword_expansions
- vacc_indication
- vacc_route
- vaccination
- vaccination_course
- vaccination_course_constraint
- vaccination_definition
- vaccination_schedule
- vaccine
- vaccine_batches
- waiting_list
- add_coded_phrase(text, text, text)
- f_announce_clin_item_mod()
- 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()
- move_waiting_list_entry(integer, integer)
- remove_old_empty_encounters(integer)
- remove_old_empty_encounters(integer, interval)
- trf_announce_active_substance_mod_no_pk()
- trf_announce_allg_mod()
- trf_announce_allg_state_mod()
- trf_announce_aoe_code_mod_no_pk()
- trf_announce_clin_narrative_mod()
- trf_announce_consumed_substance_mod_no_pk()
- trf_announce_encounter_mod()
- trf_announce_episode_code_mod_no_pk()
- trf_announce_episode_mod()
- trf_announce_family_history_mod()
- trf_announce_fhx_code_mod_no_pk()
- trf_announce_health_issue_code_mod_no_pk()
- trf_announce_health_issue_mod()
- trf_announce_hospital_stay_mod()
- trf_announce_narrative_code_mod_no_pk()
- trf_announce_narrative_mod()
- trf_announce_procedure_code_mod_no_pk()
- trf_announce_procedure_mod()
- trf_announce_reviewed_test_results_mod_no_pk()
- trf_announce_rfe_code_mod_no_pk()
- trf_announce_substance_intake_mod()
- trf_announce_test_result_mod()
- trf_announce_vacc_mod()
- trf_announce_waiting_list_generic_mod_no_pk()
- trf_announce_waiting_list_mod()
- trf_delete_intake_document_deleted()
- trf_delete_intake_turns_other_components_into_substances()
- trf_ensure_one_allergy_state_per_patient()
- trf_ins_lc2sth_fk_generic_code()
- trf_insert_intake_links_all_drug_components()
- trf_insert_intake_prevent_duplicate_component_links()
- trf_invalidate_review_on_result_change()
- trf_normalize_proc_is_ongoing()
- trf_notify_reviewer_of_review_change()
- trf_sanity_check_enc_epi_insert()
- trf_sanity_check_enc_vs_issue_on_epi()
- trf_sanity_check_procedure_episode()
- trf_sanity_check_substance_episode()
- trf_sanity_check_vaccine_has_indications()
- trf_sync_allergic_state_on_allergies_modified()
- trf_undiscontinue_unsets_reason()
- trf_unique_indication_in_schedule()
- trf_upd_lc2sth_fk_generic_code()
- trf_update_intake_must_link_all_drug_components()
- trf_update_intake_updates_all_drug_components()
- trf_warn_on_duplicate_vaccinations()

- de_de

- beh_fall_typ
- behandlungsfall
- 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
- relation_types
- staff
- staff_role
- state
- street
- urb
- v_address
- v_basic_address
- v_basic_person
- v_external_ids4identity
- v_gender_labels
- v_identity_tags
- v_inbox_item_type
- v_message_inbox
- v_org_unit_comms
- v_org_units
- v_orgs
- v_pat_addresses
- v_person_comms
- v_person_jobs
- v_person_names
- v_staff
- v_state
- 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)
- 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_states()
- new_pupic()
- remove_person(integer)
- set_nickname(integer, text)
- trf_announce_comm_channel_mod()
- trf_announce_identity_mod()
- trf_announce_identity_tag_mod()
- trf_announce_message_inbox_generic_mod_no_pk()
- trf_announce_message_inbox_mod()
- trf_announce_name_mod()
- trf_announce_org_mod_no_pk()
- trf_announce_org_unit_comm_channel_mod_no_pk()
- trf_announce_org_unit_mod_no_pk()
- trf_normalize_time_in_dob()
- trf_null_empty_title()

- gm

- access_log
- notifying_tables
- schema_revision
- add_missing_array_bits()
- add_table_for_notifies(name, name)
- add_table_for_notifies(name, 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_v2()
- concat_table_structure_v3()
- create_generic_combi_vaccine(text, text[], text, boolean)
- create_generic_combi_vaccines()
- create_generic_monovalent_vaccines()
- 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)
- log_access2emr(text)
- log_other_access(text)
- log_script_insertion(text, text)
- nullify_empty_string(text)
- register_notifying_table(name, name)
- register_notifying_table(name, name, name)
- transfer_users(text)
- transfer_users(text, text)
- user_exists(name)
- xid2int(xid)

- i18n

- curr_lang
- keys
- translations
- v_missing_translations
- _(text)
- _(text, text)
- force_curr_lang(text)
- force_curr_lang(text, name)
- 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)
- upd_tx(text, text)
- upd_tx(text, 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
- branded_drug
- code_thesaurus_root
- coding_system_root
- consumable_substance
- data_source
- document_type
- form_types
- icd10
- icd9
- icpc
- icpc_chapter
- icpc_component
- icpc_thesaurus
- lnk_substance2brand
- loinc
- loinc_staging
- ops
- other_code
- papersizes
- paperwork_templates
- tag_image
- v_atc
- v_branded_drugs
- v_coded_terms
- v_drug_components
- v_generic_codes
- v_icpc
- v_icpc_thesaurus
- v_paperwork_templates
- v_tag_images_no_data
- trf_announce_branded_drug_mod_no_pk()
- trf_announce_consumable_substance_mod_no_pk()
- trf_announce_lnk_substance2brand_mod_no_pk()
- trf_announce_substance_in_brand_mod_no_pk()
- trf_announce_tag_image_mod_no_pk()
- 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_protect_template_data()
- trf_true_brands_must_have_components()
- trf_upd_ref_code_tbl_check_backlink()

- staging

- lab_request
- test_result

# Schema au

## Table: au.referral

table for referrals to defined individuals

au.referral Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now()
clin.encounter.pk | fk_encounter | integer | NOT NULL
clin.episode.pk | fk_episode | integer | NOT NULL
| narrative | text | inherited from clin.clin_root_item; stores text of referral letter
| soap_cat | text |
| id | serial | PRIMARY KEY
dem.identity.pk | fk_referee | integer | NOT NULL person to whom the referral is directed
clin.form_instances.pk | fk_form | integer | NOT NULL foreign key to the form instance of this referral.

Table au.referral Inherits clin_root_item,

au.referral 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]))))

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 | serial | PRIMARY KEY
| row_version | integer | NOT NULL the version of the row; mainly just a count
| modified_when | timestamp with time zone | NOT NULL DEFAULT now() when has this row been committed (created/modified)
| modified_by | name | NOT NULL DEFAULT "current_user"() by whom has this row been committed (created/modified)

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 | serial | PRIMARY KEY
| orig_version | integer | NOT NULL the version of this row in the original table previous to the modification
| orig_when | timestamp with time zone | NOT NULL previous modification date in the original table
| orig_by | name | NOT NULL who committed the row to the original table
| orig_tableoid | oid | NOT NULL the table oid of the original table, use this to identify the source table
| audit_action | text | NOT NULL either "update" or "delete"
| audit_when | timestamp with time zone | NOT NULL DEFAULT now() when committed to this table for auditing
| audit_by | name | NOT NULL DEFAULT "current_user"() committed to this table for auditing by whom

audit.audit_trail Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| id | serial | PRIMARY KEY
| schema | name | UNIQUE#1 NOT NULL DEFAULT 'public'::name
| table_name | name | UNIQUE#1 NOT NULL

Index - Schema audit

## Table: audit.log_access_log

audit.log_access_log Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| user_action | text |

Table audit.log_access_log Inherits audit_trail,

audit.log_access_log Constraints
Name | Constraint
--- | ---
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_active_substance

audit.log_active_substance Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| atc_code | text |

Table audit.log_active_substance Inherits audit_trail,

audit.log_active_substance Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| id_street | integer |
| aux_street | text |
| number | text |
| subunit | text |
| addendum | text |
| lat_lon | point |

Table audit.log_address Inherits audit_trail,

audit.log_address Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |
| substance | text |
| substance_code | text |
| generics | text |
| allergene | text |
| atc_code | text |
| fk_type | integer |
| generic_specific | boolean |
| definite | boolean |

Table audit.log_allergy Inherits audit_trail,

audit.log_allergy Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| has_allergy | integer |
| comment | text |
| last_confirmed | timestamp with time zone |
| fk_encounter | integer |

Table audit.log_allergy_state Inherits audit_trail,

audit.log_allergy_state Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| code | text |
| kurzform | text |
| name | text |

Table audit.log_beh_fall_typ Inherits audit_trail,

audit.log_beh_fall_typ Constraints
Name | Constraint
--- | ---
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_behandlungsfall

audit.log_behandlungsfall Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| pk | integer |
| fk_patient | integer |
| fk_falltyp | integer |
| started | date |
| must_pay_prax_geb | boolean |

Table audit.log_behandlungsfall Inherits audit_trail,

audit.log_behandlungsfall Constraints
Name | Constraint
--- | ---
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_branded_drug

audit.log_branded_drug Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| preparation | text |
| atc_code | text |
| is_fake | boolean |
| fk_data_source | integer |
| external_code | text |
| external_code_type | text |

Table audit.log_branded_drug Inherits audit_trail,

audit.log_branded_drug Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |

Table audit.log_clin_aux_note Inherits audit_trail,

audit.log_clin_aux_note Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_narrative | integer |
| laterality | bpchar |
| is_chronic | boolean |
| is_active | boolean |
| is_definite | boolean |
| clinically_relevant | boolean |

Table audit.log_clin_diag Inherits audit_trail,

audit.log_clin_diag Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| type | text |
| code | text |

Table audit.log_clin_item_type Inherits audit_trail,

audit.log_clin_item_type Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |

Table audit.log_clin_narrative Inherits audit_trail,

audit.log_clin_narrative Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| atc_code | text |
| amount | numeric |
| unit | text |

Table audit.log_consumable_substance Inherits audit_trail,

audit.log_consumable_substance Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| atc_code | text |

Table audit.log_consumed_substance Inherits audit_trail,

audit.log_consumed_substance Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| name_short | text |
| name_long | text |
| version | text |
| description | text |
| source | text |
| lang | text |

Table audit.log_data_source Inherits audit_trail,

audit.log_data_source Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_doc | integer |
| text | text |

Table audit.log_doc_desc Inherits audit_trail,

audit.log_doc_desc Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_encounter | integer |
| fk_episode | integer |
| fk_type | integer |
| comment | text |
| clin_when | timestamp with time zone |
| ext_ref | text |

Table audit.log_doc_med Inherits audit_trail,

audit.log_doc_med Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_patient | integer |
| fk_type | integer |
| fk_location | integer |
| source_time_zone | interval |
| reason_for_encounter | text |
| assessment_of_encounter | text |
| started | timestamp with time zone |
| last_affirmed | timestamp with time zone |

Table audit.log_encounter Inherits audit_trail,

audit.log_encounter Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_health_issue | integer |
| description | text |
| is_open | boolean |
| fk_encounter | integer |
| diagnostic_certainty_classification | text |
| summary | text |

Table audit.log_episode Inherits audit_trail,

audit.log_episode Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |
| fk_relation_type | integer |
| age_noted | text |
| age_of_death | interval |
| contributed_to_death | boolean |
| name_relative | text |
| dob_relative | timestamp with time zone |
| comment | text |

Table audit.log_family_history Inherits audit_trail,

audit.log_family_history Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| is_genetic | boolean |

Table audit.log_fhx_relation_type Inherits audit_trail,

audit.log_fhx_relation_type Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_instance | integer |
| fk_form_field | integer |
| value | text |

Table audit.log_form_data Inherits audit_trail,

audit.log_form_data Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |
| fk_form_def | integer |
| form_name | text |

Table audit.log_form_instances Inherits audit_trail,

audit.log_form_instances Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| tag | text |
| label | text |
| sort_weight | integer |
| comment | text |

Table audit.log_gender_label Inherits audit_trail,

audit.log_gender_label Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| laterality | character varying |
| age_noted | interval |
| is_active | boolean |
| clinically_relevant | boolean |
| is_confidential | boolean |
| is_cause_of_death | boolean |
| fk_encounter | integer |
| grouping | text |
| diagnostic_certainty_classification | text |
| summary | text |

Table audit.log_health_issue Inherits audit_trail,

audit.log_health_issue Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |
| discharge | timestamp with time zone |

Table audit.log_hospital_stay Inherits audit_trail,

audit.log_hospital_stay Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_narrative_condition | integer |
| fk_relative | integer |
| name_relative | text |
| dob_relative | timestamp with time zone |
| condition | text |
| age_noted | text |
| age_of_death | interval |
| is_cause_of_death | boolean |

Table audit.log_hx_family_item Inherits audit_trail,

audit.log_hx_family_item Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| deleted | boolean |
| pupic | bpchar |
| gender | text |
| karyotype | text |
| dob | timestamp with time zone |
| fk_marital_status | integer |
| cob | bpchar |
| deceased | timestamp with time zone |
| title | text |
| tob | time without time zone |
| emergency_contact | text |
| fk_emergency_contact | integer |
| comment | text |
| fk_primary_provider | integer |

Table audit.log_identity Inherits audit_trail,

audit.log_identity Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_identity | integer |
| fk_tag | integer |
| comment | text |

Table audit.log_identity_tag Inherits audit_trail,

audit.log_identity_tag Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| is_user | boolean |

Table audit.log_inbox_item_category Inherits audit_trail,

audit.log_inbox_item_category Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_inbox_item_category | integer |
| description | text |
| is_user | boolean |

Table audit.log_inbox_item_type Inherits audit_trail,

audit.log_inbox_item_type Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_patient_candidates | integer[] |
| request_id | text |
| firstnames | text |
| lastnames | text |
| dob | date |
| postcode | text |
| other_info | text |
| type | text |
| data | bytea |
| gender | text |
| requestor | text |
| external_data_id | text |
| fk_identity_disambiguated | integer |

Table audit.log_incoming_data_unmatchable Inherits audit_trail,

audit.log_incoming_data_unmatchable Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_patient_candidates | integer[] |
| request_id | text |
| firstnames | text |
| lastnames | text |
| dob | date |
| postcode | text |
| other_info | text |
| type | text |
| data | bytea |
| gender | text |
| requestor | text |
| external_data_id | text |
| fk_identity_disambiguated | integer |
| comment | text |
| fk_provider_disambiguated | integer |

Table audit.log_incoming_data_unmatched Inherits audit_trail,

audit.log_incoming_data_unmatched Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |
| fk_test_org | integer |
| request_id | text |
| fk_requestor | integer |
| lab_request_id | text |
| lab_rxd_when | timestamp with time zone |
| results_reported_when | timestamp with time zone |
| request_status | text |
| is_pending | boolean |
| diagnostic_service_section | text |
| ordered_service | text |
| note_test_org | text |

Table audit.log_lab_request Inherits audit_trail,

audit.log_lab_request Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| id_test | integer |

Table audit.log_lab_test_gnr Inherits audit_trail,

audit.log_lab_test_gnr Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_lnk_code2item | integer |
| fk_generic_code | integer |
| fk_item | integer |
| code_modifier | text |
| pk | integer |

Table audit.log_lnk_code2aoe Inherits audit_trail,

audit.log_lnk_code2aoe Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_lnk_code2item | integer |
| fk_generic_code | integer |
| fk_item | integer |
| code_modifier | text |
| pk | integer |

Table audit.log_lnk_code2episode Inherits audit_trail,

audit.log_lnk_code2episode Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_lnk_code2item | integer |
| fk_generic_code | integer |
| fk_item | integer |
| code_modifier | text |
| pk | integer |

Table audit.log_lnk_code2fhx Inherits audit_trail,

audit.log_lnk_code2fhx Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_lnk_code2item | integer |
| fk_generic_code | integer |
| fk_item | integer |
| code_modifier | text |
| pk | integer |

Table audit.log_lnk_code2h_issue Inherits audit_trail,

audit.log_lnk_code2h_issue Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_lnk_code2item | integer |
| fk_generic_code | integer |
| fk_item | integer |
| code_modifier | text |
| pk | integer |

Table audit.log_lnk_code2narrative Inherits audit_trail,

audit.log_lnk_code2narrative Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_lnk_code2item | integer |
| fk_generic_code | integer |
| fk_item | integer |
| code_modifier | text |
| pk | integer |

Table audit.log_lnk_code2procedure Inherits audit_trail,

audit.log_lnk_code2procedure Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_lnk_code2item | integer |
| fk_generic_code | integer |
| fk_item | integer |
| code_modifier | text |
| pk | integer |

Table audit.log_lnk_code2rfe Inherits audit_trail,

audit.log_lnk_code2rfe Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_vaccination_course | integer |
| fk_constraint | integer |

Table audit.log_lnk_constraint2vacc_course Inherits audit_trail,

audit.log_lnk_constraint2vacc_course Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| id_identity | integer |
| external_id | text |
| fk_origin | integer |
| comment | text |

Table audit.log_lnk_identity2ext_id Inherits audit_trail,

audit.log_lnk_identity2ext_id Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| pk | integer |
| fk_identity | integer |
| fk_primary_doc | integer |

Table audit.log_lnk_identity2primary_doc Inherits audit_trail,

audit.log_lnk_identity2primary_doc Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_identity | integer |
| fk_occupation | integer |
| activities | text |

Table audit.log_lnk_job2person Inherits audit_trail,

audit.log_lnk_job2person Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_org_unit | integer |
| url | text |
| fk_type | integer |
| is_confidential | boolean |

Table audit.log_lnk_org_unit2comm Inherits audit_trail,

audit.log_lnk_org_unit2comm Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_org_unit | integer |
| external_id | text |
| fk_type | integer |
| comment | text |

Table audit.log_lnk_org_unit2ext_id Inherits audit_trail,

audit.log_lnk_org_unit2ext_id Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_patient | integer |
| fk_course | integer |

Table audit.log_lnk_pat2vaccination_course Inherits audit_trail,

audit.log_lnk_pat2vaccination_course Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| id_identity | integer |
| id_relative | integer |
| id_relation_type | integer |
| started | date |
| ended | date |

Table audit.log_lnk_person2relative Inherits audit_trail,

audit.log_lnk_person2relative Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_brand | integer |
| fk_substance | integer |

Table audit.log_lnk_substance2brand Inherits audit_trail,

audit.log_lnk_substance2brand Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| id_test | integer |
| id_norm | integer |

Table audit.log_lnk_tst2norm Inherits audit_trail,

audit.log_lnk_tst2norm Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_type | integer |
| fk_item | integer |

Table audit.log_lnk_type2item Inherits audit_trail,

audit.log_lnk_type2item Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_course | integer |
| fk_schedule | integer |

Table audit.log_lnk_vaccination_course2schedule Inherits audit_trail,

audit.log_lnk_vaccination_course2schedule Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| fk_vaccine | integer |
| fk_indication | integer |

Table audit.log_lnk_vaccine2inds Inherits audit_trail,

audit.log_lnk_vaccine2inds Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_staff | integer |
| fk_inbox_item_type | integer |
| comment | text |
| data | text |
| importance | smallint |
| fk_patient | integer |
| ufk_context | integer[] |

Table audit.log_message_inbox Inherits audit_trail,

audit.log_message_inbox Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| name | text |

Table audit.log_occupation Inherits audit_trail,

audit.log_occupation Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_health_issue | integer |
| fk_encounter | integer |
| clin_where | text |
| comment | text |

Table audit.log_operation Inherits audit_trail,

audit.log_operation Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| fk_category | integer |
| fk_data_source | integer |

Table audit.log_org Inherits audit_trail,

audit.log_org Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| fk_org | integer |
| fk_address | integer |
| fk_category | integer |

Table audit.log_org_unit Inherits audit_trail,

audit.log_org_unit Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_template_type | integer |
| instance_type | text |
| name_short | text |
| name_long | text |
| external_version | text |
| gnumed_revision | double precision |
| engine | text |
| in_use | boolean |
| filename | text |
| data | bytea |

Table audit.log_paperwork_templates Inherits audit_trail,

audit.log_paperwork_templates Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_fall | integer |
| paid_amount | numeric |
| paid_when | date |
| paid_with | integer |

Table audit.log_prax_geb_paid Inherits audit_trail,

audit.log_prax_geb_paid Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |
| clin_where | text |
| fk_hospital_stay | integer |
| clin_end | timestamp with time zone |
| is_ongoing | boolean |

Table audit.log_procedure Inherits audit_trail,

audit.log_procedure Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| id | integer |
| fk_referee | integer |
| fk_form | integer |

Table audit.log_referral Inherits audit_trail,

audit.log_referral Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| inverse | integer |
| biological | boolean |
| biol_verified | boolean |
| description | text |

Table audit.log_relation_types Inherits audit_trail,

audit.log_relation_types Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| label | text |
| cmd | text |

Table audit.log_report_query Inherits audit_trail,

audit.log_report_query Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_identity | integer |
| fk_role | integer |
| db_user | name |
| short_alias | text |
| comment | text |
| is_active | boolean |

Table audit.log_staff Inherits audit_trail,

audit.log_staff Constraints
Name | Constraint
--- | ---
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_staff_role

audit.log_staff_role Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| name | text |
| comment | text |

Table audit.log_staff_role Inherits audit_trail,

audit.log_staff_role Constraints
Name | Constraint
--- | ---
audit_trail_audit_action_check | CHECK ((audit_action = ANY (ARRAY['UPDATE'::text, 'DELETE'::text])))

Index - Schema audit

## Table: audit.log_state

audit.log_state Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| code | text |
| country | bpchar |
| name | text |

Table audit.log_state Inherits audit_trail,

audit.log_state Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| id_urb | integer |
| name | text |
| postcode | text |
| suburb | text |
| lat_lon | point |

Table audit.log_street Inherits audit_trail,

audit.log_street Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_brand | integer |
| description | text |
| atc_code | text |

Table audit.log_substance_in_brand Inherits audit_trail,

audit.log_substance_in_brand Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |
| fk_substance | integer |
| preparation | text |
| schedule | text |
| aim | text |
| duration | interval |
| intake_is_approved_of | boolean |
| is_long_term | boolean |
| discontinued | timestamp with time zone |
| discontinue_reason | text |
| fk_drug_component | integer |

Table audit.log_substance_intake Inherits audit_trail,

audit.log_substance_intake Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |
| filename | text |
| image | bytea |

Table audit.log_tag_image Inherits audit_trail,

audit.log_tag_image Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_org_unit | integer |
| fk_adm_contact | integer |
| fk_med_contact | integer |
| comment | text |
| contact | text |

Table audit.log_test_org Inherits audit_trail,

audit.log_test_org Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |
| fk_type | integer |
| val_num | numeric |
| val_alpha | text |
| val_unit | text |
| val_normal_min | numeric |
| val_normal_max | numeric |
| val_normal_range | text |
| val_target_min | numeric |
| val_target_max | numeric |
| val_target_range | text |
| abnormality_indicator | text |
| norm_ref_group | text |
| note_test_org | text |
| material | text |
| material_detail | text |
| fk_intended_reviewer | integer |
| fk_request | integer |

Table audit.log_test_result Inherits audit_trail,

audit.log_test_result Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_test_org | integer |
| code | text |
| coding_system | text |
| name | text |
| comment | text |
| conversion_unit | text |
| loinc | text |
| abbrev | text |

Table audit.log_test_type Inherits audit_trail,

audit.log_test_type Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| id_state | integer |
| postcode | text |
| lat_lon | point |
| name | text |

Table audit.log_urb Inherits audit_trail,

audit.log_urb Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| description | text |
| atcs_single_indication | text[] |
| atcs_combi_indication | text[] |

Table audit.log_vacc_indication Inherits audit_trail,

audit.log_vacc_indication Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| abbreviation | text |
| description | text |

Table audit.log_vacc_route Inherits audit_trail,

audit.log_vacc_route Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk_item | integer |
| clin_when | timestamp with time zone |
| fk_encounter | integer |
| fk_episode | integer |
| narrative | text |
| soap_cat | text |
| pk | integer |
| fk_patient | integer |
| fk_provider | integer |
| fk_vaccine | integer |
| site | text |
| batch_no | text |
| reaction | text |

Table audit.log_vaccination Inherits audit_trail,

audit.log_vaccination Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_recommended_by | integer |
| fk_indication | integer |
| is_active | boolean |
| comment | text |

Table audit.log_vaccination_course Inherits audit_trail,

audit.log_vaccination_course Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| description | text |

Table audit.log_vaccination_course_constraint Inherits audit_trail,

audit.log_vaccination_course_constraint Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| id | integer |
| fk_course | integer |
| is_booster | boolean |
| seq_no | integer |
| min_age_due | interval |
| max_age_due | interval |
| min_interval | interval |
| comment | text |

Table audit.log_vaccination_definition Inherits audit_trail,

audit.log_vaccination_definition Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| name | text |
| comment | text |

Table audit.log_vaccination_schedule Inherits audit_trail,

audit.log_vaccination_schedule Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| id_route | integer |
| is_live | boolean |
| min_age | interval |
| max_age | interval |
| comment | text |
| fk_brand | integer |

Table audit.log_vaccine Inherits audit_trail,

audit.log_vaccine Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_vaccine | integer |
| batch_no | text |

Table audit.log_vaccine_batches Inherits audit_trail,

audit.log_vaccine_batches Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| fk_patient | integer |
| registered | timestamp with time zone |
| urgency | integer |
| list_position | integer |
| comment | text |
| area | text |

Table audit.log_waiting_list Inherits audit_trail,

audit.log_waiting_list Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_trail_pk_audit_seq'::regclass)
| orig_version | integer | NOT NULL the .row_version in the original row before the audited action took place, should be equal to .row_version
| orig_when | timestamp with time zone | NOT NULL the .modified_when in the original row before the audited action took place, should be equal to .modified_when
| orig_by | name | NOT NULL the .modified_by in the original row before the audited action took place, should be equal to .modified_by
| orig_tableoid | oid | NOT NULL the TG_RELID when the audit trigger was run
| audit_action | text | NOT NULL
| audit_when | timestamp with time zone | NOT NULL DEFAULT now()
| audit_by | name | NOT NULL DEFAULT "current_user"()
| row_version | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| pk | integer |
| xfk_identity | integer |
| pupic | text |
| data | text |

Table audit.log_xlnk_identity Inherits audit_trail,

audit.log_xlnk_identity Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| event_when | text |
| event_by | text |
| event_table | regclass |
| row_version_before | integer |
| row_version_after | integer |
| event | text |
| audit_when_ts | timestamp with time zone |
| pk_audit | integer |

    (
    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 ALLSELECT 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 ALLSELECT 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

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

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

### Returns: boolean

### Language: SQL

    select audit.register_table_for_auditing($1, $2);

## Function: audit.ft_del_access_log()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_access_log (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, user_action
    	) 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.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

    BEGIN
    	INSERT INTO audit.log_address (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_allergy (
    		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, 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_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.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

    BEGIN
    	INSERT INTO audit.log_allergy_state (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, has_allergy, comment, last_confirmed, fk_encounter
    	) 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.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_beh_fall_typ()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_beh_fall_typ (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, code, kurzform, name
    	) 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.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_branded_drug()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_branded_drug (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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_clin_aux_note()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_clin_aux_note (
    		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
    	) 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
    	);
    	return OLD;
    END;

## Function: audit.ft_del_clin_diag()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_clin_diag (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_clin_item_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, type, 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.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

    BEGIN
    	INSERT INTO audit.log_clin_narrative (
    		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
    	) 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
    	);
    	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

    BEGIN
    	INSERT INTO audit.log_consumable_substance (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, atc_code, amount, unit
    	) 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, 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

    BEGIN
    	INSERT INTO audit.log_data_source (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_doc_desc (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_doc, text
    	) 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_doc, OLD.text
    	);
    	return OLD;
    END;

## Function: audit.ft_del_doc_med()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_doc_med (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_encounter, fk_episode, fk_type, comment, clin_when, ext_ref
    	) 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_encounter, OLD.fk_episode, OLD.fk_type, OLD.comment, OLD.clin_when, OLD.ext_ref
    	);
    	return OLD;
    END;

## Function: audit.ft_del_encounter()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_encounter (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_episode (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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_family_history()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_family_history (
    		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, 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_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.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

    BEGIN
    	INSERT INTO audit.log_fhx_relation_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, is_genetic
    	) 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.is_genetic
    	);
    	return OLD;
    END;

## Function: audit.ft_del_form_data()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_form_data (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_instance, fk_form_field, value
    	) 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_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

    BEGIN
    	INSERT INTO audit.log_form_instances (
    		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, fk_form_def, form_name
    	) 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.fk_form_def, OLD.form_name
    	);
    	return OLD;
    END;

## Function: audit.ft_del_gender_label()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_gender_label (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, tag, label, sort_weight, 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.tag, OLD.label, OLD.sort_weight, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_health_issue()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_health_issue (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_hospital_stay (
    		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, discharge
    	) 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.discharge
    	);
    	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

    BEGIN
    	INSERT INTO audit.log_identity (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, deleted, pupic, gender, karyotype, dob, fk_marital_status, cob, deceased, title, tob, emergency_contact, fk_emergency_contact, comment, fk_primary_provider
    	) 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.deleted, OLD.pupic, OLD.gender, OLD.karyotype, 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
    	);
    	return OLD;
    END;

## Function: audit.ft_del_identity_tag()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_identity_tag (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_identity, fk_tag, 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_identity, OLD.fk_tag, OLD.comment
    	);
    	return OLD;
    END;

## Function: audit.ft_del_inbox_item_category()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_inbox_item_category (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, 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.description, OLD.is_user
    	);
    	return OLD;
    END;

## Function: audit.ft_del_inbox_item_type()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_inbox_item_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_inbox_item_category, description, 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_inbox_item_category, OLD.description, OLD.is_user
    	);
    	return OLD;
    END;

## Function: audit.ft_del_incoming_data_unmatchable()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_incoming_data_unmatchable (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_incoming_data_unmatched (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lab_request (
    		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, 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_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.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

    BEGIN
    	INSERT INTO audit.log_lab_test_gnr (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, id_test
    	) 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.id, OLD.id_test
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_code2aoe()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_code2aoe (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lnk_code2episode (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lnk_code2fhx (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lnk_code2h_issue (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lnk_code2narrative (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lnk_code2procedure (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lnk_code2rfe (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lnk_constraint2vacc_course (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_vaccination_course, fk_constraint
    	) 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_vaccination_course, OLD.fk_constraint
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_identity2ext_id()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_identity2ext_id (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, id_identity, external_id, fk_origin, 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.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

    BEGIN
    	INSERT INTO audit.log_lnk_job2person (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_identity, fk_occupation, activities
    	) 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_identity, OLD.fk_occupation, OLD.activities
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_org_unit2comm()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_org_unit2comm (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_org_unit, url, fk_type, is_confidential
    	) 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_org_unit, OLD.url, OLD.fk_type, OLD.is_confidential
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_org_unit2ext_id()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_org_unit2ext_id (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lnk_pat2vaccination_course (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_patient, fk_course
    	) 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_patient, OLD.fk_course
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_person2relative()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_person2relative (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_lnk_substance2brand (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_brand, fk_substance
    	) 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.fk_substance
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_tst2norm()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_tst2norm (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, id_test, id_norm
    	) 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.id, OLD.id_test, OLD.id_norm
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_type2item()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_type2item (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_type, fk_item
    	) 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.fk_item
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_vaccination_course2schedule()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_vaccination_course2schedule (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_course, fk_schedule
    	) 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_course, OLD.fk_schedule
    	);
    	return OLD;
    END;

## Function: audit.ft_del_lnk_vaccine2inds()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_lnk_vaccine2inds (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, fk_vaccine, fk_indication
    	) 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.id, OLD.fk_vaccine, OLD.fk_indication
    	);
    	return OLD;
    END;

## Function: audit.ft_del_message_inbox()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_message_inbox (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_staff, fk_inbox_item_type, comment, data, importance, fk_patient, ufk_context
    	) 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_staff, OLD.fk_inbox_item_type, OLD.comment, OLD.data, OLD.importance, OLD.fk_patient, OLD.ufk_context
    	);
    	return OLD;
    END;

## Function: audit.ft_del_occupation()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_occupation (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, name
    	) 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.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

    BEGIN
    	INSERT INTO audit.log_org (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, fk_category, fk_data_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.description, OLD.fk_category, OLD.fk_data_source
    	);
    	return OLD;
    END;

## Function: audit.ft_del_org_unit()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_org_unit (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, fk_org, fk_address, fk_category
    	) 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.fk_org, OLD.fk_address, OLD.fk_category
    	);
    	return OLD;
    END;

## Function: audit.ft_del_paperwork_templates()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_paperwork_templates (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_template_type, instance_type, name_short, name_long, external_version, gnumed_revision, engine, in_use, filename, 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.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
    	);
    	return OLD;
    END;

## Function: audit.ft_del_prax_geb_paid()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_prax_geb_paid (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_fall, OLD.paid_amount, OLD.paid_when, OLD.paid_with
    	);
    	return OLD;
    END;

## Function: audit.ft_del_procedure()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_procedure (
    		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, clin_where, fk_hospital_stay, clin_end, is_ongoing
    	) 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.clin_where, OLD.fk_hospital_stay, OLD.clin_end, OLD.is_ongoing
    	);
    	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

    BEGIN
    	INSERT INTO audit.log_referral (
    		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, id, fk_referee, fk_form
    	) 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.id, OLD.fk_referee, OLD.fk_form
    	);
    	return OLD;
    END;

## Function: audit.ft_del_relation_types()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_relation_types (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, inverse, biological, biol_verified, 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.id, OLD.inverse, OLD.biological, OLD.biol_verified, OLD.description
    	);
    	return OLD;
    END;

## Function: audit.ft_del_report_query()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_report_query (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, label, cmd
    	) 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.label, OLD.cmd
    	);
    	return OLD;
    END;

## Function: audit.ft_del_staff()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_staff (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_identity, fk_role, db_user, short_alias, comment, is_active
    	) 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_identity, OLD.fk_role, 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_state()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_state (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, code, country, name
    	) 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.id, OLD.code, OLD.country, OLD.name
    	);
    	return OLD;
    END;

## Function: audit.ft_del_street()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_street (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, id_urb, name, postcode, suburb, lat_lon
    	) 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.id, OLD.id_urb, OLD.name, OLD.postcode, OLD.suburb, OLD.lat_lon
    	);
    	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

    BEGIN
    	INSERT INTO audit.log_substance_intake (
    		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, fk_substance, preparation, schedule, aim, duration, intake_is_approved_of, is_long_term, discontinued, discontinue_reason, fk_drug_component
    	) 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.fk_substance, OLD.preparation, OLD.schedule, OLD.aim, OLD.duration, OLD.intake_is_approved_of, OLD.is_long_term, OLD.discontinued, OLD.discontinue_reason, OLD.fk_drug_component
    	);
    	return OLD;
    END;

## Function: audit.ft_del_tag_image()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_tag_image (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, filename, image
    	) 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.filename, OLD.image
    	);
    	return OLD;
    END;

## Function: audit.ft_del_test_org()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_test_org (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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_result()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_test_result (
    		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, 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
    	) 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.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
    	);
    	return OLD;
    END;

## Function: audit.ft_del_test_type()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_test_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_test_org, code, coding_system, name, comment, conversion_unit, loinc, abbrev
    	) 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_test_org, OLD.code, OLD.coding_system, OLD.name, OLD.comment, OLD.conversion_unit, OLD.loinc, OLD.abbrev
    	);
    	return OLD;
    END;

## Function: audit.ft_del_urb()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_urb (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, id_state, postcode, lat_lon, name
    	) 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.id, OLD.id_state, OLD.postcode, OLD.lat_lon, OLD.name
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vacc_indication()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_vacc_indication (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, description, atcs_single_indication, atcs_combi_indication
    	) 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.id, OLD.description, OLD.atcs_single_indication, OLD.atcs_combi_indication
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vacc_route()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_vacc_route (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, abbreviation, 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.id, OLD.abbreviation, OLD.description
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccination()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_vaccination (
    		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, fk_provider, fk_vaccine, site, batch_no, reaction
    	) 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.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

    BEGIN
    	INSERT INTO audit.log_vaccination_course (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_vaccination_course_constraint (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, 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.description
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccination_definition()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_vaccination_definition (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	INSERT INTO audit.log_vaccination_schedule (
    		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_vaccine()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_vaccine (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, id_route, is_live, min_age, max_age, comment, fk_brand
    	) 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.id_route, OLD.is_live, OLD.min_age, OLD.max_age, OLD.comment, OLD.fk_brand
    	);
    	return OLD;
    END;

## Function: audit.ft_del_vaccine_batches()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_vaccine_batches (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_vaccine, batch_no
    	) 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_vaccine, OLD.batch_no
    	);
    	return OLD;
    END;

## Function: audit.ft_del_waiting_list()

### Returns: trigger

### Language: PLPGSQL

    BEGIN
    	INSERT INTO audit.log_waiting_list (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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_beh_fall_typ()

### 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_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_branded_drug()

### 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_aux_note()

### 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_diag()

### 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_item_type()

### 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_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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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_state()

### 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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, user_action
    	) 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.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

    BEGIN
    	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,
    		pk_audit, row_version, modified_when, modified_by, 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.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_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.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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, has_allergy, comment, last_confirmed, fk_encounter
    	) 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.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_beh_fall_typ()

### 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_beh_fall_typ (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, code, kurzform, name
    	) 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.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_branded_drug()

### 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_branded_drug (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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_clin_aux_note()

### 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_aux_note (
    		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
    	) 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
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_clin_diag()

### 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_diag (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, type, 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.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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_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
    	);
    	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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, description, atc_code, amount, unit
    	) 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, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, fk_doc, text
    	) 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_doc, OLD.text
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_doc_med()

### 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_doc_med (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_encounter, fk_episode, fk_type, comment, clin_when, ext_ref
    	) 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_encounter, OLD.fk_episode, OLD.fk_type, OLD.comment, OLD.clin_when, OLD.ext_ref
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_encounter()

### 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_encounter (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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_family_history()

### 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_family_history (
    		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, 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_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.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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, description, is_genetic
    	) 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.is_genetic
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_form_data()

### 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_data (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_instance, fk_form_field, value
    	) 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_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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_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.fk_form_def, OLD.form_name
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_gender_label()

### 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_gender_label (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, tag, label, sort_weight, 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.tag, OLD.label, OLD.sort_weight, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_health_issue()

### 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_health_issue (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, discharge
    	) 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.discharge
    	);
    	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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, deleted, pupic, gender, karyotype, dob, fk_marital_status, cob, deceased, title, tob, emergency_contact, fk_emergency_contact, comment, fk_primary_provider
    	) 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.deleted, OLD.pupic, OLD.gender, OLD.karyotype, 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
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_identity_tag()

### 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_identity_tag (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_identity, fk_tag, 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_identity, OLD.fk_tag, OLD.comment
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_inbox_item_category()

### 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_inbox_item_category (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, 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.description, OLD.is_user
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_inbox_item_type()

### 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_inbox_item_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_inbox_item_category, description, 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_inbox_item_category, OLD.description, OLD.is_user
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_incoming_data_unmatchable()

### 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_incoming_data_unmatchable (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_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.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

    BEGIN
    	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,
    		pk_audit, row_version, modified_when, modified_by, id, id_test
    	) 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.id, OLD.id_test
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_code2aoe()

### 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_code2aoe (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, fk_vaccination_course, fk_constraint
    	) 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_vaccination_course, OLD.fk_constraint
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_identity2ext_id()

### 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_identity2ext_id (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, id_identity, external_id, fk_origin, 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.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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, fk_identity, fk_occupation, activities
    	) 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_identity, OLD.fk_occupation, OLD.activities
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_org_unit2comm()

### 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_org_unit2comm (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_org_unit, url, fk_type, is_confidential
    	) 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_org_unit, OLD.url, OLD.fk_type, OLD.is_confidential
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_org_unit2ext_id()

### 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_org_unit2ext_id (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, fk_patient, fk_course
    	) 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_patient, OLD.fk_course
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_person2relative()

### 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_person2relative (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, fk_brand, fk_substance
    	) 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.fk_substance
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_tst2norm()

### 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_tst2norm (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, id_test, id_norm
    	) 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.id, OLD.id_test, OLD.id_norm
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_type2item()

### 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_type2item (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_type, fk_item
    	) 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.fk_item
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_vaccination_course2schedule()

### 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_vaccination_course2schedule (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_course, fk_schedule
    	) 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_course, OLD.fk_schedule
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_lnk_vaccine2inds()

### 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_vaccine2inds (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, fk_vaccine, fk_indication
    	) 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.id, OLD.fk_vaccine, OLD.fk_indication
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_message_inbox()

### 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_message_inbox (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_staff, fk_inbox_item_type, comment, data, importance, fk_patient, ufk_context
    	) 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_staff, OLD.fk_inbox_item_type, OLD.comment, OLD.data, OLD.importance, OLD.fk_patient, OLD.ufk_context
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_occupation()

### 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_occupation (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, name
    	) 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.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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, description, fk_category, fk_data_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.description, OLD.fk_category, OLD.fk_data_source
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_org_unit()

### 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_org_unit (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, fk_org, fk_address, fk_category
    	) 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.fk_org, OLD.fk_address, OLD.fk_category
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_paperwork_templates()

### 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_paperwork_templates (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_template_type, instance_type, name_short, name_long, external_version, gnumed_revision, engine, in_use, filename, 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.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
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_prax_geb_paid()

### 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_prax_geb_paid (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, OLD.pk, OLD.fk_fall, OLD.paid_amount, OLD.paid_when, OLD.paid_with
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_procedure()

### 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_procedure (
    		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, clin_where, fk_hospital_stay, clin_end, is_ongoing
    	) 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.clin_where, OLD.fk_hospital_stay, OLD.clin_end, OLD.is_ongoing
    	);
    	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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_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.id, OLD.fk_referee, OLD.fk_form
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_relation_types()

### 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_relation_types (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, inverse, biological, biol_verified, 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.id, OLD.inverse, OLD.biological, OLD.biol_verified, OLD.description
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_report_query()

### 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_report_query (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, label, cmd
    	) 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.label, OLD.cmd
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_staff()

### 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 (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_identity, fk_role, db_user, short_alias, comment, is_active
    	) 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_identity, OLD.fk_role, 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_state()

### 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_state (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, code, country, name
    	) 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.id, OLD.code, OLD.country, OLD.name
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_street()

### 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_street (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, id_urb, name, postcode, suburb, lat_lon
    	) 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.id, OLD.id_urb, OLD.name, OLD.postcode, OLD.suburb, OLD.lat_lon
    	);
    	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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk_item, clin_when, fk_encounter, fk_episode, narrative, soap_cat, pk, fk_substance, preparation, schedule, aim, duration, intake_is_approved_of, is_long_term, discontinued, discontinue_reason, fk_drug_component
    	) 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.fk_substance, OLD.preparation, OLD.schedule, OLD.aim, OLD.duration, OLD.intake_is_approved_of, OLD.is_long_term, OLD.discontinued, OLD.discontinue_reason, OLD.fk_drug_component
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_tag_image()

### 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_tag_image (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, description, filename, image
    	) 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.filename, OLD.image
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_test_org()

### 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_test_org (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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_result()

### 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_test_result (
    		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, 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
    	) 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.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
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_test_type()

### 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_test_type (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_test_org, code, coding_system, name, comment, conversion_unit, loinc, abbrev
    	) 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_test_org, OLD.code, OLD.coding_system, OLD.name, OLD.comment, OLD.conversion_unit, OLD.loinc, OLD.abbrev
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_urb()

### 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_urb (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, id_state, postcode, lat_lon, name
    	) 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.id, OLD.id_state, OLD.postcode, OLD.lat_lon, OLD.name
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vacc_indication()

### 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_vacc_indication (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, description, atcs_single_indication, atcs_combi_indication
    	) 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.id, OLD.description, OLD.atcs_single_indication, OLD.atcs_combi_indication
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vacc_route()

### 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_vacc_route (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, id, abbreviation, 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.id, OLD.abbreviation, OLD.description
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccination()

### 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_vaccination (
    		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, fk_provider, fk_vaccine, site, batch_no, reaction
    	) 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.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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_audit, row_version, modified_when, modified_by, pk, 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.description
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccination_definition()

### 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_vaccination_definition (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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.pk_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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

    BEGIN
    	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_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_vaccine()

### 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_vaccine (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, id_route, is_live, min_age, max_age, comment, fk_brand
    	) 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.id_route, OLD.is_live, OLD.min_age, OLD.max_age, OLD.comment, OLD.fk_brand
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_vaccine_batches()

### 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_vaccine_batches (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, pk, fk_vaccine, batch_no
    	) 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_vaccine, OLD.batch_no
    	);
    	return NEW;
    END;

## Function: audit.ft_upd_waiting_list()

### 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_waiting_list (
    		orig_version, orig_when, orig_by, orig_tableoid, audit_action,
    		pk_audit, row_version, modified_when, modified_by, 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_audit, OLD.row_version, OLD.modified_when, OLD.modified_by, 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_item

Holds items ready for being billed.

bill.bill_item Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.staff.pk | fk_provider | integer | NOT NULL by whom or on whose behalf did the billable activity happen
clin.encounter.pk | fk_encounter | integer | NOT NULL the encounter during which the billable action for this item took place
| date_to_bill | date | NOT NULL DEFAULT ('now'::text)::date the date under which this item is to be billed
| code | text | a code for the billing item
| system | text | the coding system for the code for the billing item
| description | text | a human comprehensible description of the item
| receiver | text | who is to receive the bill
| amount_to_bill | numeric | how much to bill for this item if known
| currency | text | what currency to bill in
| locale | text |
| status | text | DEFAULT 'new'::text the status of this item

Table bill.bill_item Inherits audit_fields,

bill.bill_item Constraints
Name | Constraint
--- | ---
code_not_empty | CHECK (gm.is_null_or_non_empty_string(code))
currency_not_empty_if_amount | CHECK (((amount_to_bill IS NULL) OR (gm.is_null_or_blank_string(currency) IS FALSE)))
desc_not_empty | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))
sane_receiver | CHECK (gm.is_null_or_non_empty_string(description))
system_not_empty_if_code | CHECK (((code IS NULL) OR (system IS NOT NULL)))
valid_stati | CHECK ((status = ANY (ARRAY['new'::text, 'transferred'::text])))

Index - Schema bill

## Function: bill.trf_announce_bill_item_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'bill.trf_announce_bill_item_mod(): cannot determine identity PK on table <bill.bill_item>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "bill_item_mod_db:' || _pk_identity || '"';
    	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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
blobs.doc_med.pk | fk_doc | integer | UNIQUE#1
| text | text | UNIQUE#1

Table blobs.doc_desc Inherits audit_fields,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.encounter.pk | fk_encounter | integer | NOT NULL the encounter in which this document was entered into the system
clin.episode.pk | fk_episode | integer | NOT NULL the episode this document pertains to, this may not be the only one applicable to the document (think discharge letters), see also lnk_doc_med2episode
blobs.doc_type.pk | fk_type | integer | NOT NULL semantic type of document (not type of file or mime type), such as "referral letter", "discharge summary", etc.
| comment | text | additional short comment such as "abdominal", "ward 3, Dr. Stein", etc.
| clin_when | timestamp with time zone | NOT NULL DEFAULT now() date of document content creation (such as exam date), NOT date of document creation or date of import; may be imprecise such as "7/99"
| ext_ref | text | external reference string of physical document, original paper copy can be found with this

Table blobs.doc_med Inherits audit_fields,

Tables referencing this one via Foreign Key Constraints:

- blobs.doc_desc

- blobs.doc_obj

- blobs.lnk_doc2hospital_stay

- blobs.lnk_doc_med2episode

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 | serial | PRIMARY KEY
blobs.doc_med.pk | fk_doc | integer | NOT NULL
| seq_idx | integer | index of this object in the sequence of objects for this document
| comment | text | optional tiny comment for this object, such as "page 1"
dem.staff.pk | fk_intended_reviewer | integer | NOT NULL who is *supposed* to review this item
| data | bytea | NOT NULL actual binary object data; here is why we use bytea: == -------------------------------------------------- To: leon@oss.minimetria.com Cc: pgsql-sql@postgresql.org Subject: Re: [SQL] Recommendation on bytea or blob for binary data like images Date: Fri, 02 Sep 2005 16:33:09 -0400 Message-ID: <17794.1125693189@sss.pgh.pa.us> From: Tom Lane <tgl@sss.pgh.pa.us> List-Archive: <http://archives.postgresql.org/pgsql-sql> List-Help: <mailto:majordomo@postgresql.org?body=help> List-ID: <pgsql-sql.postgresql.org> leon@oss.minimetria.com writes: > Hi, I"d like to know what the official recommendation is on which binary > datatype to use for common small-binary size use. If bytea will work for you, it"s definitely the thing to use. The only real drawback to bytea is that there"s currently no API to read and write bytea values in a streaming fashion. If your objects are small enough that you can load and store them as units, bytea is fine. BLOBs, on the other hand, have a number of drawbacks --- hard to dump, impossible to secure, etc. regards, tom lane == --------------------------------------------------
| filename | text | the filename from when the data was imported - if any, can be NULL, useful for re-export since legacy devices/applications might expect particular file names and not use mime types for file detection

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

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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| name | text | UNIQUE NOT NULL the name/label of the document type

Tables referencing this one via Foreign Key Constraints:

- blobs.doc_med

Index - Schema blobs

## Table: blobs.lnk_doc2hospital_stay

links documents to any hospital stay they might pertain to

blobs.lnk_doc2hospital_stay Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.hospital_stay.pk | fk_stay | integer | NOT NULL
blobs.doc_med.pk | fk_document | integer | UNIQUE NOT NULL

Table blobs.lnk_doc2hospital_stay Inherits audit_fields,

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.episode.pk | fk_episode | integer | UNIQUE#1 NOT NULL
blobs.doc_med.pk | fk_doc_med | integer | UNIQUE#1 NOT NULL

Table blobs.lnk_doc_med2episode Inherits audit_fields,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | integer | PRIMARY KEY DEFAULT nextval('clin.review_root_pk_seq'::regclass)
blobs.doc_obj.pk | fk_reviewed_row | integer | UNIQUE#1 NOT NULL
| fk_reviewer | integer | UNIQUE#1 NOT NULL
| is_technically_abnormal | boolean | NOT NULL
| clinically_relevant | boolean | NOT NULL
| comment | text |

Table blobs.reviewed_doc_objs Inherits review_root,

Index - Schema blobs

## View: blobs.v_doc_desc

aggregates some document data descriptions

blobs.v_doc_desc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| pk_doc | integer |
| description | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| pk_doc_desc | integer |

    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
--- | --- | --- | ---
| pk_patient | integer |
| pk_doc | integer |
| clin_when | timestamp with time zone |
| type | text |
| l10n_type | text |
| ext_ref | text |
| episode | text |
| comment | text |
| episode_open | boolean |
| pk_type | integer |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| xmin_doc_med | xid |

    SELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = dm.fk_encounter)
    ) AS pk_patient
    , dm.pk AS pk_doc
    , dm.clin_when
    , dt.name AS type
    , _
    (dt.name) AS l10n_type
    , dm.ext_ref
    , cle.description AS episode
    , dm.comment
    , cle.is_open AS episode_open
    , dm.fk_type AS pk_type
    , dm.fk_encounter AS pk_encounter
    , dm.fk_episode AS pk_episode
    , cle.fk_health_issue AS pk_health_issue
    , dm.modified_when
    , dm.modified_by
    , dm.xmin AS xmin_doc_med
    FROM blobs.doc_med dm
    , blobs.doc_type dt
    , clin.episode cle
    WHERE (
         (dt.pk = dm.fk_type)
       AND (cle.pk = dm.fk_episode)
    );

Index - Schema blobs

## View: blobs.v_doc_med_journal

blobs.v_doc_med_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |

    SELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = dm.fk_encounter)
    ) AS pk_patient
    , dm.modified_when
    , dm.clin_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = dm.modified_by)
         )
         , (
               ('<'::text ||
                     (dm.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    , NULL::text AS soap_cat
    , (
         (
               (
                     (
                           (
                                 (_
                                       ('Document'::text) || ': '::text
                                 ) || _
                                 (dt.name)
                           ) || COALESCE
                           (
                                 (
                                       (' "'::text || dm.ext_ref) ||
                                   '" ('::text)
                                       , ' ('::text)
                                 ) || to_char
                                 (dm.clin_when
                                       ,'YYYY-MM-DD HH24:MI'::text
                                 )
                           ) ||
                   ')'::text
               ) || COALESCE
               (
                     ('
     '::text || dm.comment)
                     ,''::text
               )
         ) AS narrative
         , dm.fk_encounter AS pk_encounter
         , dm.fk_episode AS pk_episode
         , (
          SELECT episode.fk_health_issue
            FROM clin.episode
           WHERE (episode.pk = dm.fk_episode)
         ) AS pk_health_issue
         , dm.pk AS src_pk
         ,'blobs.doc_med'::text AS src_table
      FROM blobs.doc_med dm
         , blobs.doc_type dt
     WHERE (dt.pk = dm.fk_type);

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
--- | --- | --- | ---
| pk_doc_type | integer |
| type | text |
| l10n_type | text |
| is_user_defined | boolean |
| is_in_use | boolean |
| xmin_doc_type | xid |

    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
--- | --- | --- | ---
| pk_patient | integer |
| doc_comment | text |
| date_taken | timestamp with time zone |
| ext_ref | text |
| obj_seq_idx | integer |
| obj_comment | text |
| pk_doc | integer |
| pk_obj | integer |
| image | bytea |

    SELECT vo4d.pk_patient
    , vo4d.doc_comment
    , vo4d.date_generated AS date_taken
    , vo4d.ext_ref
    , vo4d.seq_idx AS obj_seq_idx
    , vo4d.obj_comment
    , vo4d.pk_doc
    , vo4d.pk_obj
    , bdo.data AS image
    FROM blobs.v_obj4doc_no_data vo4d
    , blobs.doc_obj bdo
    WHERE (
         (
               (vo4d.type = 'patient photograph'::text)
             AND (vo4d.seq_idx =
                     (
                      SELECT max
                           (vo4d1.seq_idx) AS max
                        FROM blobs.v_obj4doc_no_data vo4d1
                       WHERE (
                                 (vo4d1.pk_patient = vo4d.pk_patient)
                               AND (vo4d1.type = 'patient photograph'::text)
                           )
                    GROUP BY vo4d1.date_generated
                    ORDER BY vo4d1.date_generated DESC LIMIT 1
                     )
               )
         )
       AND (bdo.pk = 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
--- | --- | --- | ---
| pk_patient | integer |
| pk_obj | integer |
| seq_idx | integer |
| size | integer |
| date_generated | timestamp with time zone |
| type | text |
| l10n_type | text |
| ext_ref | text |
| episode | text |
| doc_comment | text |
| obj_comment | text |
| filename | text |
| pk_intended_reviewer | integer |
| reviewed | boolean |
| reviewed_by_you | boolean |
| reviewed_by_intended_reviewer | boolean |
| pk_doc | integer |
| pk_type | integer |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| xmin_doc_obj | xid |

    SELECT vdm.pk_patient
    , dobj.pk AS pk_obj
    , dobj.seq_idx
    , octet_length
    (COALESCE
         (dobj.data
               ,''::bytea
         )
    ) AS size
    , vdm.clin_when AS date_generated
    , vdm.type
    , vdm.l10n_type
    , vdm.ext_ref
    , vdm.episode
    , vdm.comment AS doc_comment
    , dobj.comment AS obj_comment
    , dobj.filename
    , dobj.fk_intended_reviewer AS pk_intended_reviewer
    , (EXISTS
         (
          SELECT 1
            FROM blobs.reviewed_doc_objs
           WHERE (reviewed_doc_objs.fk_reviewed_row = dobj.pk)
         )
    ) AS reviewed
    , (EXISTS
         (
          SELECT 1
            FROM blobs.reviewed_doc_objs
           WHERE (
                     (reviewed_doc_objs.fk_reviewed_row = dobj.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 = dobj.pk)
                   AND (reviewed_doc_objs.fk_reviewer = dobj.fk_intended_reviewer)
               )
         )
    ) AS reviewed_by_intended_reviewer
    , vdm.pk_doc
    , vdm.pk_type
    , vdm.pk_encounter
    , vdm.pk_episode
    , vdm.pk_health_issue
    , dobj.xmin AS xmin_doc_obj
    FROM blobs.v_doc_med vdm
    , blobs.doc_obj dobj
    WHERE (vdm.pk_doc = dobj.fk_doc);

Index - Schema blobs

## View: blobs.v_reviewed_doc_objects

blobs.v_reviewed_doc_objects Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_doc_obj | integer |
| reviewer | text |
| is_technically_abnormal | boolean |
| clinically_relevant | boolean |
| is_review_by_responsible_reviewer | boolean |
| is_your_review | boolean |
| comment | text |
| reviewed_when | timestamp with time zone |
| modified_by | name |
| pk_review_root | integer |
| pk_reviewer | integer |
| pk_patient | integer |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |

    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

## 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
    	);
    	delete from blobs.doc_obj where fk_doc = _pk_doc;
    	delete from blobs.doc_med where pk = _pk_doc;
    	return True;
    END;

## Function: blobs.trf_announce_doc_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'blobs.trf_announce_doc_mod(): cannot determine identity PK on table <blobs.doc_med>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "doc_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: blobs.trf_announce_doc_obj_review_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "doc_obj_review_mod_db:"';
    	return NULL;
    end;

## Function: blobs.trf_announce_doc_page_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "doc_page_mod_db:"';
    	return NULL;
    end;

## Function: blobs.trf_announce_doc_type_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "doc_type_mod_db:"';
    	return NULL;
    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 | integer | NOT NULL
| value | bytea | NOT NULL
| pk | serial | 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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
cfg.cfg_template.pk | fk_template | integer | UNIQUE#1 NOT NULL this points to the class of this option, think of this as a base object, this also defines the data type
| owner | name | UNIQUE#1 NOT NULL DEFAULT "current_user"() the database level user this option belongs to; this is the "role" of the user from the perspective of the database; can be "default" at the application level to indicate that it does not care
| workplace | text | UNIQUE#1 - the logical workplace this option pertains to - can be a hostname but should be a logical rather than a physical identifier as machines get moved, workplaces do not, kind of like a "role" for the machine - associate this with a physical workplace through a local config file or environment variable
| cookie | text | UNIQUE#1 an arbitrary, opaque entity the client code can use to associate this config item with even finer grained context; could be the pertinent patient ID for patient specific options

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 | integer | NOT NULL
| value | numeric | NOT NULL

Index - Schema cfg

## Table: cfg.cfg_str_array

cfg.cfg_str_array Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
cfg.cfg_item.pk | fk_item | integer | NOT NULL
| value | text[] | NOT NULL

Index - Schema cfg

## Table: cfg.cfg_string

cfg.cfg_string Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
cfg.cfg_item.pk | fk_item | integer | NOT NULL
| value | text | NOT NULL

Index - Schema cfg

## Table: cfg.cfg_template

meta definition of config items

cfg.cfg_template Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| name | text | NOT NULL DEFAULT 'must set this !'::text the name of the option; this MUST be set to something meaningful
cfg.cfg_type_enum.name | type | text | NOT NULL type of the value
| cfg_group | text | NOT NULL DEFAULT 'xxxDEFAULTxxx'::text just for logical grouping of options according to task sets to facilitate better config management
| description | text | NOT NULL DEFAULT 'programmer is an avid Camel Book Reader'::text arbitrary description (user visible)

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 | text | UNIQUE NOT NULL

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 | serial | PRIMARY KEY
| profile | character(25) | DEFAULT 'default'::bpchar allows multiple profiles per user/ pseudo user, one user may have different configuration profiles depending on role, need and location
| username | character(25) | DEFAULT "current_user"() user name as used within the GNUmed system
| ddb | integer | which GNUmed service are we mapping to a database here
| db | integer | how to reach the database host for this service
| crypt_pwd | text | password for user and database, encrypted
| crypt_algo | text | encryption algorithm used for password encryption
| pwd_hash | text | hash of the unencrypted password
| hash_algo | text | algorithm used for password hashing

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
--- | --- | --- | ---
| message | text | The actual message to show.
| singularizer | boolean | UNIQUE DEFAULT true Makes sure there only ever is one such banner at any given time.

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| label | text | UNIQUE NOT NULL
| cmd | text | NOT NULL

Table cfg.report_query Inherits audit_fields,

cfg.report_query Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| option | text |
| description | text |
| owner | name |
| workplace | text |
| cookie | text |
| type | text |
| group | text |
| pk_cfg_template | integer |
| pk_cfg_item | integer |

    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
--- | --- | --- | ---
| option | text |
| value | bytea |
| description | text |
| owner | name |
| workplace | text |
| cookie | text |
| group | text |
| pk_cfg_template | integer |
| pk_cfg_item | integer |

    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
--- | --- | --- | ---
| option | text |
| value | numeric |
| description | text |
| owner | name |
| workplace | text |
| cookie | text |
| group | text |
| pk_cfg_template | integer |
| pk_cfg_item | integer |

    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
--- | --- | --- | ---
| option | text |
| value | text[] |
| description | text |
| owner | name |
| workplace | text |
| cookie | text |
| group | text |
| pk_cfg_template | integer |
| pk_cfg_item | integer |

    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
--- | --- | --- | ---
| option | text |
| value | text |
| description | text |
| owner | name |
| workplace | text |
| cookie | text |
| group | text |
| pk_cfg_template | integer |
| pk_cfg_item | integer |

    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 | serial | PRIMARY KEY
| value | text | UNIQUE NOT NULL

Tables referencing this one via Foreign Key Constraints:

- clin.allergy

Index - Schema clin

## Table: clin.active_substance

(Active) substances (consumables) a patient may be taking.

clin.active_substance Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | UNIQUE NOT NULL The substance as such, say, Metoprolol.
| atc_code | text | UNIQUE ATC code, if any.

Table clin.active_substance Inherits audit_fields,

clin.active_substance Constraints
Name | Constraint
--- | ---
sane_atc | CHECK ((gm.is_null_or_non_empty_string(atc_code) IS TRUE))

idx_atc_brand atc_code idx_atc_substance atc_code

Index - Schema clin

## Table: clin.allergy

patient allergy details

clin.allergy Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now()
clin.encounter.pk | fk_encounter | integer | NOT NULL
clin.episode.pk | fk_episode | integer | NOT NULL
| narrative | text | used as field "reaction"
| soap_cat | text | DEFAULT 'o'::text
| pk | serial | PRIMARY KEY
| substance | text | NOT NULL real-world name of substance the patient reacted to, brand name if drug
| substance_code | text | data source specific opaque product code; must provide a link to a unique product/substance in the database in use; should follow the parseable convention of "<source>::<source version>::<identifier>", e.g. "MIMS::2003-1::190" for Zantac; it is left as an exercise to the application to know what to do with this information
| generics | text | names of generic compounds if drug; brand names change/disappear, generic names do not
| allergene | text | name of allergenic ingredient in substance if known
| atc_code | text | ATC code of allergene or substance if approprate, applicable for penicilline, not so for cat fur
clin._enum_allergy_type.pk | fk_type | integer | NOT NULL allergy/sensitivity
| generic_specific | boolean | DEFAULT false only meaningful for *drug*/*generic* reactions: 1) true: applies to one in "generics" forming "substance", if more than one generic listed in "generics" then "allergene" *must* contain the generic in question; 2) false: applies to drug class of "substance";
| definite | boolean | DEFAULT false true: definite, false: not definite

Table clin.allergy Inherits clin_root_item,

clin.allergy 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]))))

idx_allg_encounter fk_encounter idx_allg_episode fk_episode

Index - Schema clin

## Table: clin.allergy_state

clin.allergy_state Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| has_allergy | integer | patient allergenic state: - null: unknown, not asked, no data available - -1: unknown, asked, no data obtained - 0: known, asked, has no known allergies - 1: known, asked, does have allergies
| comment | text | A comment on the state, such as "patient says no allergies but I think he is holding back some".
| last_confirmed | timestamp with time zone | When was the state of allergies last confirmed. Must be not NULL if has_allergy is not NULL.
clin.encounter.pk | fk_encounter | integer | NOT NULL

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])))

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now()
clin.encounter.pk | fk_encounter | integer | NOT NULL
clin.episode.pk | fk_episode | integer | NOT NULL
| narrative | text |
| soap_cat | text |
| pk | serial | PRIMARY KEY

Table clin.clin_aux_note Inherits clin_root_item,

clin.clin_aux_note 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]))))

idx_clanote_encounter fk_encounter idx_clanote_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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.clin_narrative.pk | fk_narrative | integer | UNIQUE NOT NULL
| laterality | character(1) | DEFAULT NULL::bpchar
| is_chronic | boolean | NOT NULL DEFAULT false whether this diagnosis is chronic, eg. no complete cure is to be expected, regardless of whether it is *active* right now (think of active/non-active phases of Multiple Sclerosis which is sure chronic)
| is_active | boolean | NOT NULL DEFAULT true whether diagnosis is currently active or dormant
| is_definite | boolean | NOT NULL DEFAULT false
| clinically_relevant | boolean | NOT NULL DEFAULT true whether this diagnosis is considered clinically relevant, eg. significant; currently active diagnoses are considered to always be relevant, while inactive ones may or may not be

Table clin.clin_diag Inherits audit_fields,

clin.clin_diag Constraints
Name | Constraint
--- | ---
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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| type | text | UNIQUE NOT NULL DEFAULT 'history'::text the full name of the item type such as "family history"
| code | text | UNIQUE NOT NULL DEFAULT 'Hx'::text shorthand for the type, eg "FHx"

Table clin.clin_item_type Inherits audit_fields,

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now() when did the item reach clinical reality
clin.encounter.pk | fk_encounter | integer | NOT NULL
clin.episode.pk | fk_episode | integer | NOT NULL
| narrative | text |
| soap_cat | text |
| pk | serial | PRIMARY KEY

Table clin.clin_narrative Inherits clin_root_item,

clin.clin_narrative 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]))))
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_clnarr_encounter fk_encounter idx_clnarr_episode fk_episode idx_narr_soap soap_cat) WHERE (lower(soap_cat) = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text]) idx_narrative_modified_by modified_by

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | serial | PRIMARY KEY the primary key, not named "id" or "pk" as usual since child tables will have "id"/"pk"-named primary keys already and we would get duplicate columns while inheriting from this table
| clin_when | timestamp with time zone | NOT NULL DEFAULT now() when this clinical item became known, can be different from when it was entered into the system (= audit.audit_fields.modified_when)
clin.encounter.pk | fk_encounter | integer | NOT NULL the encounter this item belongs to
clin.episode.pk | fk_episode | integer | NOT NULL the episode this item belongs to
| narrative | text | each clinical item by default inherits a free text field for clinical narrative
| soap_cat | text | each clinical item must be either one of the S, O, A, P categories or NULL to indicate a non-clinical item

Table clin.clin_root_item Inherits audit_fields,

clin.clin_root_item 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]))))

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.identity.pk | fk_patient | integer | NOT NULL PK of subject of care, should be PUPIC, actually
clin.encounter_type.pk | fk_type | integer | NOT NULL DEFAULT 1 PK of type of this encounter
| fk_location | integer | PK of location *of care*, e.g. where the provider is at
| source_time_zone | interval | time zone of location, used to approximate source time zone for all timestamps in this encounter
| reason_for_encounter | text | the RFE for the encounter as related by either the patient or the provider (say, in a chart review)
| assessment_of_encounter | text | the Assessment of Encounter (eg consultation summary) as determined by the provider, may simply be a concatenation of soAp narrative, this assessment should go across all problems
| started | timestamp with time zone | NOT NULL DEFAULT now()
| last_affirmed | timestamp with time zone | NOT NULL DEFAULT now()

Table clin.encounter Inherits audit_fields,

clin.encounter Constraints
Name | Constraint
--- | ---
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.family_history

- clin.form_instances

- clin.health_issue

- clin.lab_request

- clin.lnk_code2aoe

- clin.lnk_code2rfe

- clin.test_result

- clin.vaccination

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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| description | text | UNIQUE NOT NULL

Tables referencing this one via Foreign Key Constraints:

- 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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.health_issue.pk | fk_health_issue | integer | health issue this episode belongs to
| description | text | NOT NULL description/name of this episode
| is_open | boolean | DEFAULT true whether the episode is open (eg. there is activity for it), means open in a temporal sense as in "not closed yet"; only one episode can be open per health issue
clin.encounter.pk | fk_encounter | integer | NOT NULL The encounter during which this episode was added (begun).
| diagnostic_certainty_classification | text | The certainty at which this problem is believed to be a diagnosis: A: sign (Symptom) B: cluster of signs (Symptomkomplex) C: syndromic diagnosis (Bild einer Diagnose) D: proven diagnosis (diagnostisch gesichert)
| summary | text | Used for tracking the summary of this episode.

Table clin.episode Inherits audit_fields,

clin.episode Constraints
Name | Constraint
--- | ---
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.lab_request

- clin.lnk_code2episode

- clin.lnk_substance2episode

- clin.test_result

- clin.vaccination

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.family_history

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

clin.family_history Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now() When the family history item became known to the patient (not the afflicted relative).
clin.encounter.pk | fk_encounter | integer | NOT NULL encounter during which family history item became known
clin.episode.pk | fk_episode | integer | NOT NULL episode to which family history item is of importance
| narrative | text | the condition this relative suffered from
| soap_cat | text |
| pk | serial | PRIMARY KEY
clin.fhx_relation_type.pk | fk_relation_type | integer | NOT NULL foreign key to the type of relation the patient has to the afflicated relative
| age_noted | text | age at which the condition was noted in the relative if known
| age_of_death | interval | age at which the relative died if known
| contributed_to_death | boolean | whether the condition contributed to the death of the relative if known
| name_relative | text | name of the relative suffering the condition
| dob_relative | timestamp with time zone | date of birth of the relative if known
| comment | text |

Table clin.family_history Inherits clin_root_item,

clin.family_history Constraints
Name | Constraint
--- | ---
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_soap_cat_check | CHECK (((soap_cat IS NULL) OR (lower(soap_cat) = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text]))))
narrative_neither_null_nor_empty | CHECK ((btrim(COALESCE(narrative, ''::text)) <> ''::text))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_code2fhx

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | UNIQUE#1 Description of the relation type, specific or unspecific: sister, father, ..., maternal family, ...
| is_genetic | boolean | UNIQUE#1 NOT NULL Whether or not this type of relation is biologic/genetic or not. Note that non-genetic relations may still pose a risk because of infectious diseases.

Table clin.fhx_relation_type Inherits audit_fields,

clin.fhx_relation_type Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.form_instances.pk | fk_instance | integer | UNIQUE#1 NOT NULL the form instance this value was used in
public.form_fields.pk | fk_form_field | integer | UNIQUE#1 NOT NULL points to the definition of the field in the form which in turn defines the place holder in the template to replace with <value>
| value | text | NOT NULL the value to replace the place holder with

Table clin.form_data Inherits audit_fields,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now()
clin.encounter.pk | fk_encounter | integer | NOT NULL
clin.episode.pk | fk_episode | integer | NOT NULL
| narrative | text | can be used as a status field, eg. "printed", "faxed" etc.
| soap_cat | text |
| pk | serial | PRIMARY KEY
ref.paperwork_templates.pk | fk_form_def | integer | NOT NULL points to the definition of this instance, this FK will fail once we start separating services, make it into a x_db_fk then
| form_name | text | NOT NULL a string uniquely identifying the form template, necessary for the audit trail

Table clin.form_instances Inherits clin_root_item,

clin.form_instances 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]))))
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_formi_encounter fk_encounter idx_formi_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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | NOT NULL descriptive name of this health issue, may change over time as evidence increases
| laterality | character varying(2) | DEFAULT NULL::character varying NULL: don't know s: sinister - left d: dexter - right sd: sinister and dexter - both sides na: not applicable
| age_noted | interval | at what age the patient acquired the condition
| is_active | boolean | DEFAULT true whether this health issue (problem) is active
| clinically_relevant | boolean | DEFAULT true whether this health issue (problem) has any clinical relevance
| is_confidential | boolean | DEFAULT false
| is_cause_of_death | boolean | NOT NULL DEFAULT false
clin.encounter.pk | fk_encounter | integer | NOT NULL The encounter during which this health issue was added.
| grouping | text | This can be used to entirely arbitrarily group health issues felt to belong to each other.
| diagnostic_certainty_classification | text | The certainty at which this issue is believed to be a diagnosis: A: sign (Symptom) B: cluster of signs (Symptomkomplex) C: syndromic diagnosis (Bild einer Diagnose) D: proven diagnosis (diagnostisch gesichert)
| summary | text | Used for tracking the summary of this health issue.

Table clin.health_issue Inherits audit_fields,

clin.health_issue Constraints
Name | Constraint
--- | ---
episode_sane_summary | CHECK (gm.is_null_or_non_empty_string(summary))
health_issue_laterality_check | CHECK (((laterality)::text = ANY ((ARRAY[NULL::character varying, 's'::character varying, 'd'::character varying, 'sd'::character varying, '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.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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now() to be used as when the patient was admitted
| fk_encounter | integer | NOT NULL
| fk_episode | integer | NOT NULL
| narrative | text | the hospital to which the patient was admitted
| soap_cat | text |
| pk | serial | PRIMARY KEY
| discharge | timestamp with time zone | when was the patient discharged

Table clin.hospital_stay Inherits clin_root_item,

clin.hospital_stay 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]))))
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:

- blobs.lnk_doc2hospital_stay

- clin.procedure

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| fk_patient_candidates | integer[] |
| request_id | text |
| firstnames | text |
| lastnames | text |
| dob | date |
| postcode | text |
| other_info | text |
| type | text |
| data | bytea | NOT NULL
| gender | text |
| requestor | text |
| external_data_id | text |
| fk_identity_disambiguated | integer |

Table clin.incoming_data_unmatchable Inherits audit_fields,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| fk_patient_candidates | integer[] | a matching algorithm can be applied to produce a list of likely candidate patients, the question remains whether this should not be done at runtime
| request_id | text | request ID as found in <data>
| firstnames | text | first names as found in <data>
| lastnames | text | last names as found in <data>
| dob | date | date of birth as found in <data>
| postcode | text | postcode as found in <data>
| other_info | text | other identifying information as found in <data>
| type | text | the type of <data>, eg HL7, LDT, ..., useful for selecting an importer
| data | bytea | NOT NULL the raw data
| gender | text | Gender of patient in source data if available.
| requestor | text | Requestor of data (e.g. who ordered test results) if available in source data.
| external_data_id | text | ID of content of .data in external system (e.g. importer) where appropriate
dem.identity.pk | fk_identity_disambiguated | integer | ID of patient the data is judged to really belong to.
| comment | text | a free text comment on this row, eg. why is it here
dem.staff.pk | fk_provider_disambiguated | integer | The provider the data is relevant to.

Table clin.incoming_data_unmatched Inherits audit_fields,

clin.incoming_data_unmatched Constraints
Name | Constraint
--- | ---
unmatched_data_sane_comment | CHECK ((gm.is_null_or_non_empty_string(comment) IS TRUE))

Index - Schema clin

## Table: clin.keyword_expansion

A table for expanding text typed by the user based on keywords.

clin.keyword_expansion Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
dem.staff.pk | fk_staff | integer | UNIQUE#1 The provider this expansion applies to. If NULL: applies to all providers.
| keyword | text | UNIQUE#1 NOT NULL The keyword to expand. Can only exist once per provider.
| expansion | text | NOT NULL The expansion for this keyword.
| owner | text | NOT NULL DEFAULT "current_user"() Who "owns" this text expansion.

clin.keyword_expansion Constraints
Name | Constraint
--- | ---
keyword_expansion_keyword_check | CHECK ((btrim(keyword) <> ''::text))

Index - Schema clin

## Table: clin.lab_request

test request metadata

clin.lab_request Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now() the time the sample for this request was taken LDT: 8432:8433 HL7: OBR.quantity_timing
clin.encounter.pk | fk_encounter | integer | NOT NULL
clin.episode.pk | fk_episode | integer | NOT NULL
| narrative | text | free text comment on request
| soap_cat | text | DEFAULT 'p'::text
| pk | serial | PRIMARY KEY
clin.test_org.pk | fk_test_org | integer | UNIQUE#1
| request_id | text | UNIQUE#1 NOT NULL ID this request had when sent to the lab LDT: 8310 HL7: OBR.filler_order_number
dem.identity.pk | fk_requestor | integer | who requested the test - really needed ?
| lab_request_id | text | ID this request had internally at the lab LDT: 8311
| lab_rxd_when | timestamp with time zone | when did the lab receive the request+sample LDT: 8301 HL7: OBR.requested_date_time
| results_reported_when | timestamp with time zone | when was the report on the result generated, LDT: 8302 HL7: OBR.results_report_status_change
| request_status | text | NOT NULL pending, final, preliminary, partial LDT: 8401
| is_pending | boolean | NOT NULL DEFAULT true true if any (even partial) results are still pending
| diagnostic_service_section | text | The (section of) the diagnostic service which performed the test. - HL7 2.3: OBR:24 Diagnostic Service Section ID - somewhat redundant with fk_test_org, which, however, points to more normalized data
| ordered_service | text | The (battery of) test(s)/service(s) ordered. - HL7 2.3: OBR:4 Universal Service ID
| note_test_org | text | A comment on this lab request by the performing organization (lab).

Table clin.lab_request Inherits clin_root_item,

clin.lab_request Constraints
Name | Constraint
--- | ---
clin_lab_req_sane_test_org_note | CHECK ((gm.is_null_or_non_empty_string(note_test_org) IS TRUE))
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])))

Tables referencing this one via Foreign Key Constraints:

- clin.test_result

idx_lreq_encounter fk_encounter idx_lreq_episode fk_episode

Index - Schema clin

## Table: clin.lnk_code2aoe

Links codes to encounter.aoe.

clin.lnk_code2aoe Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_lnk_code2item | integer | NOT NULL DEFAULT nextval('clin.lnk_code2item_root_pk_lnk_code2item_seq'::regclass)
| fk_generic_code | integer | UNIQUE#1 NOT NULL Custom foreign key to ref.coding_system_root.
clin.encounter.pk | fk_item | integer | UNIQUE#1 Foreign key to clin.encounter
| code_modifier | text |
| pk | serial | PRIMARY KEY

Table clin.lnk_code2aoe Inherits lnk_code2item_root,

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_lnk_code2item | integer | NOT NULL DEFAULT nextval('clin.lnk_code2item_root_pk_lnk_code2item_seq'::regclass)
| fk_generic_code | integer | UNIQUE#1 NOT NULL Custom foreign key to ref.coding_system_root.
clin.episode.pk | fk_item | integer | UNIQUE#1 Foreign key to clin.episode
| code_modifier | text |
| pk | serial | PRIMARY KEY

Table clin.lnk_code2episode Inherits lnk_code2item_root,

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_lnk_code2item | integer | NOT NULL DEFAULT nextval('clin.lnk_code2item_root_pk_lnk_code2item_seq'::regclass)
| fk_generic_code | integer | UNIQUE#1 NOT NULL Custom foreign key to ref.coding_system_root.
clin.family_history.pk | fk_item | integer | UNIQUE#1 Foreign key to clin.family_history
| code_modifier | text |
| pk | serial | PRIMARY KEY

Table clin.lnk_code2fhx Inherits lnk_code2item_root,

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_lnk_code2item | integer | NOT NULL DEFAULT nextval('clin.lnk_code2item_root_pk_lnk_code2item_seq'::regclass)
| fk_generic_code | integer | UNIQUE#1 NOT NULL Custom foreign key to ref.coding_system_root.
clin.health_issue.pk | fk_item | integer | UNIQUE#1 Foreign key to clin.health_issue
| code_modifier | text |
| pk | serial | PRIMARY KEY

Table clin.lnk_code2h_issue Inherits lnk_code2item_root,

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_lnk_code2item | serial | PRIMARY KEY
| fk_generic_code | integer | Custom foreign key to ref.coding_system_root.pk_coding_system.
| fk_item | integer | Foreign key to clin.* tables
| code_modifier | text | Usage specific modifier on the base code, say, certainty or laterality of ICD-10 codes.

Table clin.lnk_code2item_root Inherits audit_fields,

Index - Schema clin

## Table: clin.lnk_code2narrative

Links codes to SOAP narrative.

clin.lnk_code2narrative Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_lnk_code2item | integer | NOT NULL DEFAULT nextval('clin.lnk_code2item_root_pk_lnk_code2item_seq'::regclass)
| fk_generic_code | integer | UNIQUE#1 NOT NULL Custom foreign key to ref.coding_system_root.
clin.clin_narrative.pk | fk_item | integer | UNIQUE#1 Foreign key to clin.clin_narrative
| code_modifier | text |
| pk | serial | PRIMARY KEY

Table clin.lnk_code2narrative Inherits lnk_code2item_root,

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_lnk_code2item | integer | NOT NULL DEFAULT nextval('clin.lnk_code2item_root_pk_lnk_code2item_seq'::regclass)
| fk_generic_code | integer | UNIQUE#1 NOT NULL Custom foreign key to ref.coding_system_root.
clin.procedure.pk | fk_item | integer | UNIQUE#1 Foreign key to clin.procedure
| code_modifier | text |
| pk | serial | PRIMARY KEY

Table clin.lnk_code2procedure Inherits lnk_code2item_root,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_lnk_code2item | integer | NOT NULL DEFAULT nextval('clin.lnk_code2item_root_pk_lnk_code2item_seq'::regclass)
| fk_generic_code | integer | UNIQUE#1 NOT NULL Custom foreign key to ref.coding_system_root.
clin.encounter.pk | fk_item | integer | UNIQUE#1 Foreign key to clin.encounter
| code_modifier | text |
| pk | serial | PRIMARY KEY

Table clin.lnk_code2rfe Inherits lnk_code2item_root,

idx_c_lc2rfe_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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.vaccination_course.pk | fk_vaccination_course | integer | UNIQUE#1 NOT NULL
clin.vaccination_course_constraint.pk | fk_constraint | integer | UNIQUE#1 NOT NULL

Table clin.lnk_constraint2vacc_course Inherits audit_fields,

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.identity.pk | fk_patient | integer | UNIQUE#1 NOT NULL
clin.vaccination_course.pk | fk_course | integer | UNIQUE#1 NOT NULL

Table clin.lnk_pat2vaccination_course Inherits audit_fields,

Index - Schema clin

## Table: clin.lnk_substance2episode

clin.lnk_substance2episode Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.episode.pk | fk_episode | integer |
clin.substance_intake.pk | fk_substance | integer |

Table clin.lnk_substance2episode Inherits audit_fields,

Index - Schema clin

## Table: clin.lnk_tst2norm

links test result evaluation norms to tests

clin.lnk_tst2norm Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
clin.test_type.pk | id_test | integer | UNIQUE#1 NOT NULL which test does the linked norm apply to
| id_norm | integer | UNIQUE#1 NOT NULL the norm to apply to the linked test

Table clin.lnk_tst2norm Inherits audit_fields,

Index - Schema clin

## Table: clin.lnk_ttype2unified_type

clin.lnk_ttype2unified_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
clin.test_type.pk | fk_test_type | integer | NOT NULL
clin.meta_test_type.pk | fk_test_type_unified | integer | NOT NULL

idx_ltt2ut_fk_ttu fk_test_type_unified

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.clin_item_type.pk | fk_type | integer | UNIQUE#1 NOT NULL
| fk_item | integer | UNIQUE#1 NOT NULL the item this type is linked to, since PostgreSQL apparently cannot reference a value inserted from a child table (?) we must simulate referential integrity checks with a custom trigger, this, however, does not deal with update/delete cascading :-(

Table clin.lnk_type2item Inherits audit_fields,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.vaccination_course.pk | fk_course | integer | UNIQUE NOT NULL
clin.vaccination_schedule.pk | fk_schedule | integer | NOT NULL

Table clin.lnk_vaccination_course2schedule Inherits audit_fields,

Index - Schema clin

## Table: clin.lnk_vaccine2inds

links vaccines to their indications

clin.lnk_vaccine2inds Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
clin.vaccine.pk | fk_vaccine | integer | UNIQUE#1 NOT NULL
clin.vacc_indication.id | fk_indication | integer | UNIQUE#1 NOT NULL

Table clin.lnk_vaccine2inds Inherits audit_fields,

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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| abbrev | text | UNIQUE#1 NOT NULL
| name | text | UNIQUE#1 NOT NULL
| loinc | text |
| comment | text |

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_ttype2unified_type

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now()
| fk_encounter | integer | NOT NULL
| fk_episode | integer | NOT NULL
| narrative | text | Which procedure/operation was performed.
| soap_cat | text | DEFAULT 'p'::text
| pk | serial | PRIMARY KEY
| clin_where | text | Where was the procedure/operation performed, unless fk_hospital_stay is not null
clin.hospital_stay.pk | fk_hospital_stay | integer | At which hospital was the procedure performed, unless clin_where is not null, if null it was an ambulatory procedure.
| clin_end | timestamp with time zone | When did this procedure end/is expected to end. - NULL if unknown or .clin_when (=start) is sufficient (eg. insignificant duration)
| is_ongoing | boolean | NOT NULL DEFAULT false Whether this procedure is still going on (such as desensibilisation, chemotherapy, etc).

Table clin.procedure Inherits clin_root_item,

clin.procedure 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]))))
procedure_sane_end | CHECK (((clin_end IS NULL) OR (clin_end >= clin_when)))
procedure_sane_ongoing | CHECK (((is_ongoing IS FALSE) OR ((clin_end IS NULL) OR (clin_end > now()))))
sane_location | CHECK (gm.is_null_or_non_empty_string(clin_where))
sane_procedure | CHECK ((gm.is_null_or_blank_string(narrative) IS FALSE))
sane_soap_cat | CHECK ((soap_cat = ANY (ARRAY['a'::text, 'p'::text])))
single_location_definition | CHECK ((((fk_hospital_stay IS NULL) AND (clin_where IS NOT NULL)) OR ((fk_hospital_stay IS NOT NULL) AND (clin_where IS NULL))))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_code2procedure

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| fk_reviewed_row | integer | UNIQUE#1 NOT NULL the row the review status is for: to be qualified as a proper foreign key in child tables
dem.staff.pk | fk_reviewer | integer | UNIQUE#1 NOT NULL who has reviewed the item
| is_technically_abnormal | boolean | NOT NULL whether test provider flagged this result as abnormal, *not* a clinical assessment but rather a technical one LDT: exist(8422)
| clinically_relevant | boolean | NOT NULL whether this result is considered relevant clinically, need not correspond to the value of "techically_abnormal" since abnormal values may be irrelevant while normal ones can be of significance
| comment | text |

Table clin.review_root Inherits audit_fields,

Index - Schema clin

## Table: clin.reviewed_test_results

review table for test results

clin.reviewed_test_results Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | integer | PRIMARY KEY DEFAULT nextval('clin.review_root_pk_seq'::regclass)
clin.test_result.pk | fk_reviewed_row | integer | UNIQUE#1 UNIQUE NOT NULL
dem.staff.pk | fk_reviewer | integer | UNIQUE#1 NOT NULL DEFAULT clin.f_fk_reviewer_default()
| is_technically_abnormal | boolean | NOT NULL
| clinically_relevant | boolean | NOT NULL
| comment | text |

Table clin.reviewed_test_results Inherits review_root,

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 | serial | PRIMARY KEY
| rank | integer | NOT NULL
| soap_cat | character(1) |

clin.soap_cat_ranks Constraints
Name | Constraint
--- | ---
soap_cat_ranks_rank_check | CHECK ((rank = ANY (ARRAY[1, 2, 3, 4, 5])))
soap_cat_ranks_soap_cat_check | CHECK (((soap_cat IS NULL) OR (lower((soap_cat)::text) = ANY (ARRAY['s'::text, 'o'::text, 'a'::text, 'p'::text]))))

Index - Schema clin

## Table: clin.substance_intake

The substances a patient is actually currently taking.

clin.substance_intake Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now() When was this substance started.
| fk_encounter | integer | NOT NULL The encounter use of this substance was documented under.
| fk_episode | integer |
| narrative | text | Any notes on this substance use.
| soap_cat | text | DEFAULT 'p'::text
| pk | serial | PRIMARY KEY
ref.consumable_substance.pk | fk_substance | integer | Links to a substance the patient is taking. ********************************************* DO NOT TRY TO USE THIS TO FIND OUT THE BRAND. IT WILL BE WRONG. *********************************************
| preparation | text | How this substance is delivered, tablet, pill, liquid, cream.
| schedule | text | The schedule, if any, the substance is to be taken by. An XML snippet to be interpreted by the middleware.
| aim | text | The aim of taking this substance.
| duration | interval | How long is this substances intended to be taken.
| intake_is_approved_of | boolean | NOT NULL Whether or not intake of this substance is recommended/approved of by the provider
| is_long_term | boolean | whether this is expected to be a regular/ongoing/chronic/long-term/repeat/permament/perpetual/life-long substance intake
| discontinued | timestamp with time zone | why was this entry discontinued
| discontinue_reason | text |
ref.lnk_substance2brand.pk | fk_drug_component | integer | Links to the component of a branded drug taken by a patient.

Table clin.substance_intake Inherits clin_root_item,

clin.substance_intake 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]))))
clin_subst_intake_either_drug_or_substance | CHECK ((((fk_drug_component IS NULL) AND (fk_substance IS NOT NULL)) OR ((fk_drug_component IS NOT NULL) AND (fk_substance IS NULL))))
clin_subst_intake_sane_prep | CHECK ((((fk_drug_component IS NULL) AND (preparation IS NOT NULL)) OR ((fk_drug_component IS NOT NULL) AND (preparation IS NULL))))
discontinued_after_started | CHECK ((((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_fk_episode | CHECK (((intake_is_approved_of IS FALSE) OR ((intake_is_approved_of IS TRUE) AND (fk_episode IS NOT NULL))))
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_fk_substance_curr_med fk_substance

Index - Schema clin

## Table: clin.test_org

organisation providing results

clin.test_org Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.org_unit.pk | fk_org_unit | integer | UNIQUE NOT NULL link to organisation HL7: MSH.sending_facility/sending_application
dem.identity.pk | fk_adm_contact | integer | whom to call for admin questions (modem link, etc.)
dem.identity.pk | fk_med_contact | integer | whom to call for medical questions (result verification, additional test requests)
| comment | text | useful for, say, dummy records where you want to mark up stuff like "pharmacy such-and-such" if you don't have it in your contacts
| contact | text | free-text contact information for this lab

Table clin.test_org Inherits audit_fields,

clin.test_org Constraints
Name | Constraint
--- | ---
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_result

the results of a single measurement

clin.test_result Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now() the time when this result was *actually* obtained, if this is a lab result this should be between lab_request.clin_when and lab_request.results_reported_when, HL7: OBR.observation_date_time
clin.encounter.pk | fk_encounter | integer | NOT NULL
clin.episode.pk | fk_episode | integer | NOT NULL
| narrative | text | clinical comment, progress note
| soap_cat | text | DEFAULT 'o'::text
| pk | serial | PRIMARY KEY
clin.test_type.pk | fk_type | integer | NOT NULL the type of test this result is from
| val_num | numeric | numeric value if any, HL7: OBX.observation_results if OBX.value_type == NM
| val_alpha | text | alphanumeric value if any, HL7: OBX.observation_results if OBX.value_type == FT
| val_unit | text | the unit this result came in HL7: OBX.units
| val_normal_min | numeric | lower bound of normal range if numerical as defined by provider for this result
| val_normal_max | numeric | upper bound of normal range if numerical as defined by provider for this result
| val_normal_range | text | range of normal values if alphanumerical as defined by provider for this result, eg. "less than 0.5 but detectable" HL7: OBX.reference_range
| val_target_min | numeric | lower bound of target range if numerical as defined by clinician caring this patient
| val_target_max | numeric | upper bound of target range if numerical as defined by clinician caring for this patient
| val_target_range | text | range of target values if alphanumerical as defined by clinician caring for this patient
| abnormality_indicator | text | how the test provider flagged this result as abnormal, *not* a clinical assessment but rather a technical one LDT: 8422
| norm_ref_group | text | what sample of the population does this normal range applay to, eg what type of patient was assumed when interpreting this result, LDT: 8407
| note_test_org | text | A comment on the test result provided by the tester or testing entity.
| material | text | the submitted material, eg. smear, serum, urine, etc., LDT: 8430
| material_detail | text | details re the material, eg. site taken from, etc. LDT: 8431
dem.staff.pk | fk_intended_reviewer | integer | NOT NULL who is *supposed* to review this item
clin.lab_request.pk | fk_request | integer | The request this result was ordered under if any.

Table clin.test_result Inherits clin_root_item,

clin.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)))
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_test_result_fk_type fk_type idx_tres_encounter fk_encounter idx_tres_episode fk_episode

Index - Schema clin

## Table: clin.test_type

measurement type, like a "method" in a lab

clin.test_type Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.test_org.pk | fk_test_org | integer | UNIQUE#1 organisation carrying out this type of measurement, eg. a particular lab
| code | text | UNIQUE#1 short name, acronym or code of this type of measurement, may conform to some official list or other such as LOINC, Australian Pathology request codes or German lab-specific ELVs, actually, this column should be checked against the coding system tables, too, the only problem being that we do not know which one ... as it depends on the *value* in "coding_system", HL7: OBX.observation_identifier
| coding_system | text | UNIQUE#1 identifier of coding system that the code of this measurement type is taken from, should be verifiable against the "reference" service of GnuMed
| name | text | NOT NULL descriptive name of this measurement type, HL7: OBX.observation_identifier
| comment | text | arbitrary comment on this type of measurement/test such as "outdated" or "only reliable when ..."
| conversion_unit | text | the basic unit for this test type, preferably SI, used for comparing results delivered in differing units, this does not relate to what unit the test provider delivers results in but rather the unit we think those results need to be converted to in order to be comparable to OTHER results
| loinc | text |
| abbrev | text | NOT NULL

Table clin.test_type Inherits audit_fields,

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_tst2norm

- clin.lnk_ttype2unified_type

- clin.test_result

- de_de.lab_test_gnr

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
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                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
                                                                  FROM clin.v_pat_narrative_journal
                                                             UNION ALLSELECT 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
                                                                  FROM clin.v_health_issues_journal
                                                               )
                                                       UNION ALLSELECT 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
                                                            FROM clin.v_pat_encounters_journal
                                                         )
                                                 UNION ALLSELECT 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
                                                      FROM clin.v_pat_episodes_journal
                                                   )
                                           UNION ALLSELECT 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
                                                FROM clin.v_family_history_journal
                                             )
                                     UNION ALLSELECT 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
                                             , 0 AS row_version
                                          FROM clin.v_pat_allergies_journal
                                       )
                               UNION ALLSELECT 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.fk_encounter AS pk_encounter
                                       , v_pat_allergy_state_journal.fk_episode AS 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
                                    FROM clin.v_pat_allergy_state_journal
                                 )
                         UNION ALLSELECT 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
                              FROM clin.v_test_results_journal
                           )
                   UNION ALLSELECT v_pat_hospital_stays_journal.pk_patient
                           , v_pat_hospital_stays_journal.modified_when
                           , v_pat_hospital_stays_journal.clin_when
                           , v_pat_hospital_stays_journal.modified_by
                           , v_pat_hospital_stays_journal.soap_cat
                           , v_pat_hospital_stays_journal.narrative
                           , v_pat_hospital_stays_journal.pk_encounter
                           , v_pat_hospital_stays_journal.pk_episode
                           , v_pat_hospital_stays_journal.pk_health_issue
                           , v_pat_hospital_stays_journal.src_pk
                           , v_pat_hospital_stays_journal.src_table
                           , v_pat_hospital_stays_journal.row_version
                        FROM clin.v_pat_hospital_stays_journal
                     )
             UNION ALLSELECT 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
                     , 0 AS row_version
                  FROM blobs.v_doc_med_journal
               )
       UNION ALLSELECT v_pat_substance_intake_journal.pk_patient
               , v_pat_substance_intake_journal.modified_when
               , v_pat_substance_intake_journal.clin_when
               , v_pat_substance_intake_journal.modified_by
               , v_pat_substance_intake_journal.soap_cat
               , v_pat_substance_intake_journal.narrative
               , v_pat_substance_intake_journal.pk_encounter
               , v_pat_substance_intake_journal.pk_episode
               , v_pat_substance_intake_journal.pk_health_issue
               , v_pat_substance_intake_journal.src_pk
               , v_pat_substance_intake_journal.src_table
               , v_pat_substance_intake_journal.row_version
            FROM clin.v_pat_substance_intake_journal
         )
    UNION ALLSELECT v_pat_procedures_journal.pk_patient
         , v_pat_procedures_journal.modified_when
         , v_pat_procedures_journal.clin_when
         , v_pat_procedures_journal.modified_by
         , v_pat_procedures_journal.soap_cat
         , v_pat_procedures_journal.narrative
         , v_pat_procedures_journal.pk_encounter
         , v_pat_procedures_journal.pk_episode
         , v_pat_procedures_journal.pk_health_issue
         , v_pat_procedures_journal.src_pk
         , v_pat_procedures_journal.src_table
         , v_pat_procedures_journal.row_version
      FROM clin.v_pat_procedures_journal
    )
    UNION ALLSELECT v_pat_vaccinations_journal.pk_patient
    , v_pat_vaccinations_journal.modified_when
    , v_pat_vaccinations_journal.clin_when
    , v_pat_vaccinations_journal.modified_by
    , v_pat_vaccinations_journal.soap_cat
    , v_pat_vaccinations_journal.narrative
    , v_pat_vaccinations_journal.pk_encounter
    , v_pat_vaccinations_journal.pk_episode
    , v_pat_vaccinations_journal.pk_health_issue
    , v_pat_vaccinations_journal.src_pk
    , v_pat_vaccinations_journal.src_table
    , v_pat_vaccinations_journal.row_version
    FROM clin.v_pat_vaccinations_journal;

Index - Schema clin

## View: clin.v_family_history

family history denormalized

clin.v_family_history Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_family_history | integer |
| pk_patient | integer |
| soap_cat | text |
| relation | text |
| l10n_relation | text |
| condition | text |
| age_noted | text |
| age_of_death | interval |
| contributed_to_death | boolean |
| comment | text |
| episode | text |
| when_known_to_patient | timestamp with time zone |
| name_relative | text |
| dob_relative | timestamp with time zone |
| is_genetic_relative | boolean |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| pk_fhx_relation_type | integer |
| modified_when | timestamp with time zone |
| pk_generic_codes | integer[] |
| xmin_family_history | xid |

    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
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT cenc.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
    , cep.fk_health_issue AS pk_health_issue
    , c_fh.pk AS src_pk
    ,'clin.family_history'::text AS src_table
    , c_fh.row_version
    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_health_issues

clin.v_health_issues Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| pk_health_issue | integer |
| description | text |
| summary | text |
| laterality | character varying(2) |
| age_noted | interval |
| is_active | boolean |
| clinically_relevant | boolean |
| is_confidential | boolean |
| is_cause_of_death | boolean |
| pk_encounter | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| row_version | integer |
| grouping | text |
| diagnostic_certainty_classification | text |
| pk_generic_codes | integer[] |
| xmin_health_issue | xid |

    SELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = chi.fk_encounter)
    ) AS pk_patient
    , chi.pk AS pk_health_issue
    , chi.description
    , chi.summary
    , chi.laterality
    , chi.age_noted
    , chi.is_active
    , chi.clinically_relevant
    , chi.is_confidential
    , chi.is_cause_of_death
    , chi.fk_encounter AS pk_encounter
    , chi.modified_when
    , chi.modified_by
    , chi.row_version
    , chi.grouping
    , chi.diagnostic_certainty_classification
    , COALESCE
    (
         (
          SELECT array_agg
               (c_lc2h.fk_generic_code) AS array_agg
            FROM clin.lnk_code2h_issue c_lc2h
           WHERE (c_lc2h.fk_item = chi.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    , chi.xmin AS xmin_health_issue
    FROM clin.health_issue chi;

Index - Schema clin

## View: clin.v_health_issues_journal

clin.v_health_issues_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT cenc.fk_patient AS pk_patient
    , chi.modified_when
    , COALESCE
    (
         (
          SELECT (identity.dob + chi.age_noted)
            FROM dem.identity
           WHERE (identity.pk =
                     (
                      SELECT encounter.fk_patient
                        FROM clin.encounter
                       WHERE (encounter.pk = chi.fk_encounter)
                     )
               )
         )
         , cenc.started
    ) AS clin_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = chi.modified_by)
         )
         , (
               ('<'::text ||
                     (chi.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,'a'::text AS soap_cat
    , (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (_
                                                                                 ('Health Issue'::text) ||
                                                                              ' ('::text) || CASE WHEN chi.is_active THEN _
                                                                                 ('active'::text) ELSE _
                                                                                 ('inactive'::text) END
                                                                           ) ||
                                                                        ', '::text
                                                                     ) || CASE WHEN chi.clinically_relevant THEN _
                                                                     ('clinically relevant'::text) ELSE _
                                                                     ('clinically not relevant'::text) END
                                                               ) || COALESCE
                                                               (
                                                                     (
                                                                        ', '::text || chi.diagnostic_certainty_classification
                                                                     )
                                                                     ,''::text
                                                               )
                                                         ) ||
                                               '): '::text
                                             ) || chi.description
                                       ) || COALESCE
                                       (
                                             (
                                                   (
                                                         (
                                                               (';
    '::text || _
                                                                     ('noted at age'::text)
                                                               ) || ': '::text
                                                         ) ||
                                                         (chi.age_noted)::text
                                                   ) || ';
    '::text
                                             )
                                             ,';
    '::text
                                       )
                                 ) || COALESCE
                                 (
                                       (
                                             (
                                                   (_
                                                         ('Laterality'::text) || ': '::text
                                                   ) ||
                                                   (chi.laterality)::text
                                             ) || ' / '::text
                                       )
                                       ,''::text
                                 )
                           ) || CASE WHEN chi.is_confidential THEN
                           (_
                                 ('confidential'::text) || ' / '::text
                           ) ELSE ''::text END
                     ) || CASE WHEN chi.is_cause_of_death THEN _
                     ('cause of death'::text) ELSE ''::text END
               ) || COALESCE
               (
                     (
                           (
                                 (';
    '::text || _
                                       ('Summary'::text)
                                 ) || ':
    '::text
                           ) || chi.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 = chi.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    , chi.fk_encounter AS pk_encounter
    , (-1) AS pk_episode
    , chi.pk AS pk_health_issue
    , chi.pk AS src_pk
    ,'clin.health_issue'::text AS src_table
    , chi.row_version
    FROM (clin.health_issue chi
      JOIN clin.encounter cenc
        ON (
               (chi.fk_encounter = cenc.pk)
         )
    );

Index - Schema clin

## View: clin.v_indications4vaccine

Denormalizes indications per vaccine.

clin.v_indications4vaccine Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_vaccine | integer |
| vaccine | text |
| preparation | text |
| atc_code | text |
| is_fake_vaccine | boolean |
| route_abbreviation | text |
| route_description | text |
| is_live | boolean |
| min_age | interval |
| max_age | interval |
| comment | text |
| indication | text |
| l10n_indication | text |
| atcs_single_indication | text[] |
| atcs_combi_indication | text[] |
| external_code | text |
| external_code_type | text |
| indications | text[] |
| l10n_indications | text[] |
| pk_indications | integer[] |
| pk_route | integer |
| pk_brand | integer |
| pk_data_source | integer |
| pk_indication | integer |
| xmin_vaccine | xid |

    SELECT cv.pk AS pk_vaccine
    , rbd.description AS vaccine
    , rbd.preparation
    , rbd.atc_code
    , rbd.is_fake AS is_fake_vaccine
    , cvr.abbreviation AS route_abbreviation
    , cvr.description AS route_description
    , cv.is_live
    , cv.min_age
    , cv.max_age
    , cv.comment
    , cvi.description AS indication
    , _
    (cvi.description) AS l10n_indication
    , cvi.atcs_single_indication
    , cvi.atcs_combi_indication
    , rbd.external_code
    , rbd.external_code_type
    , (
    SELECT array_agg
         (cvi2.description) AS array_agg
      FROM (clin.lnk_vaccine2inds clv2i_2
            JOIN clin.vacc_indication cvi2
              ON (
                     (clv2i_2.fk_indication = cvi2.id)
               )
         )
     WHERE (clv2i_2.fk_vaccine = cv.pk)
    ) AS indications
    , (
    SELECT array_agg
         (_
               (cvi2.description)
         ) AS array_agg
      FROM (clin.lnk_vaccine2inds clv2i_2
            JOIN clin.vacc_indication cvi2
              ON (
                     (clv2i_2.fk_indication = cvi2.id)
               )
         )
     WHERE (clv2i_2.fk_vaccine = cv.pk)
    ) AS l10n_indications
    , (
    SELECT array_agg
         (clv2i_2.fk_indication) AS array_agg
      FROM (clin.lnk_vaccine2inds clv2i_2
            JOIN clin.vacc_indication cvi2
              ON (
                     (clv2i_2.fk_indication = cvi2.id)
               )
         )
     WHERE (clv2i_2.fk_vaccine = cv.pk)
    ) AS pk_indications
    , cv.id_route AS pk_route
    , cv.fk_brand AS pk_brand
    , rbd.fk_data_source AS pk_data_source
    , cvi.id AS pk_indication
    , cv.xmin AS xmin_vaccine
    FROM (
         (
               (
                     (clin.vaccine cv
                   LEFT JOIN clin.vacc_route cvr
                          ON (
                                 (cvr.id = cv.id_route)
                           )
                     )
                  JOIN ref.branded_drug rbd
                    ON (
                           (rbd.pk = cv.fk_brand)
                     )
               )
            JOIN clin.lnk_vaccine2inds clv2i
              ON (
                     (clv2i.fk_vaccine = cv.pk)
               )
         )
      JOIN clin.vacc_indication cvi
        ON (
               (cvi.id = clv2i.fk_indication)
         )
    );

Index - Schema clin

## View: clin.v_keyword_expansions

Just a slightly more convenient view over expansions.

clin.v_keyword_expansions Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_keyword_expansion | integer |
| pk_staff | integer |
| keyword | text |
| expansion | text |
| public_expansion | boolean |
| private_expansion | boolean |
| owner | text |

    SELECT cke.pk AS pk_keyword_expansion
    , cke.fk_staff AS pk_staff
    , cke.keyword
    , cke.expansion
    , (cke.fk_staff IS NULL) AS public_expansion
    , (cke.fk_staff IS NOT NULL) AS private_expansion
    , cke.owner
    FROM clin.keyword_expansion cke;

Index - Schema clin

## View: clin.v_linked_codes

Denormalized codes linked to EMR structures.

clin.v_linked_codes Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_item | integer |
| item_table | regclass |
| code | text |
| base_code | text |
| code_modifier | text |
| term | text |
| name_long | text |
| name_short | text |
| version | text |
| lang | text |
| code_table | regclass |
| pk_generic_code | integer |
| pk_data_source | integer |
| pk_lnk_code2item | integer |

    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_meta_test_types

denormalized view of meta_test_type + link table to test_type, shows all meta test types to which a test type is linked

clin.v_meta_test_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_meta_test_type | integer |
| pk_test_type | integer |
| abbrev_meta | text |
| name_meta | text |
| loinc_meta | text |
| comment_meta | text |
| pk_lnk_ttype2meta_type | integer |
| xmin_meta_test_type | xid |

    SELECT ttm.pk AS pk_meta_test_type
    , ltt2mt.fk_test_type AS pk_test_type
    , ttm.abbrev AS abbrev_meta
    , ttm.name AS name_meta
    , ttm.loinc AS loinc_meta
    , ttm.comment AS comment_meta
    , ltt2mt.pk AS pk_lnk_ttype2meta_type
    , ttm.xmin AS xmin_meta_test_type
    FROM clin.meta_test_type ttm
    , clin.lnk_ttype2unified_type ltt2mt
    WHERE (ltt2mt.fk_test_type_unified = ttm.pk);

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
--- | --- | --- | ---
| pk_encounter | integer |
| pk_patient | integer |
| reason_for_encounter | text |
| assessment_of_encounter | text |
| type | text |
| l10n_type | text |
| started | timestamp with time zone |
| last_affirmed | timestamp with time zone |
| pk_type | integer |
| pk_location | integer |

    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_pat_allergies

denormalizes clin.allergy

clin.v_pat_allergies Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_allergy | integer |
| pk_patient | integer |
| soap_cat | text |
| descriptor | text |
| allergene | text |
| substance | text |
| substance_code | text |
| generics | text |
| generic_specific | boolean |
| atc_code | text |
| type | text |
| l10n_type | text |
| definite | boolean |
| reaction | text |
| pk_type | integer |
| pk_item | integer |
| date | timestamp with time zone |
| pk_health_issue | integer |
| pk_episode | integer |
| pk_encounter | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| xmin_allergy | xid |

    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
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |

    SELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = a.fk_encounter)
    ) AS pk_patient
    , a.modified_when
    , a.clin_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.soap_cat
    , (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (_
                                                                           ('Allergy'::text) ||
                                                                        ' ('::text) || _
                                                                           (at.value)
                                                                     ) ||
                                                           '): '::text
                                                         ) || COALESCE
                                                         (a.narrative
                                                               ,''::text
                                                         )
                                                   ) || '
    '::text
                                             ) || _
                                             ('substance'::text)
                                       ) || ': '::text
                                 ) || a.substance
                           ) || '; '::text
                     ) || COALESCE
                     (
                           (
                                 (
                                       (_
                                             ('allergene'::text) || ': '::text
                                       ) || a.allergene
                                 ) || '; '::text
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           (
                                 (_
                                       ('generic'::text) || ': '::text
                                 ) || a.generics
                           ) || '; '::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (
                           (_
                                 ('ATC code'::text) || ': '::text
                           ) || a.atc_code
                     ) || '; '::text
               )
               ,''::text
         )
    ) AS narrative
    , a.fk_encounter AS pk_encounter
    , a.fk_episode AS pk_episode
    , (
    SELECT episode.fk_health_issue
      FROM clin.episode
     WHERE (episode.pk = a.fk_episode)
    ) AS pk_health_issue
    , a.pk AS src_pk
    ,'clin.allergy'::text AS src_table
    FROM clin.allergy a
    , clin._enum_allergy_type at
    WHERE (at.pk = a.fk_type);

Index - Schema clin

## View: clin.v_pat_allergy_state

clin.v_pat_allergy_state Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| modified_by | text |
| last_confirmed | timestamp with time zone |
| has_allergy | integer |
| comment | text |
| pk_encounter | integer |
| pk_allergy_state | integer |
| xmin_allergy_state | xid |

    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
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| fk_encounter | integer |
| fk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = a.fk_encounter)
    ) AS pk_patient
    , a.modified_when
    , a.last_confirmed AS clin_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
    ,'o'::text AS soap_cat
    , (
         (
               (
                     (_
                           ('Allergy state'::text) || ': '::text
                     ) || CASE WHEN
                     (a.has_allergy IS NULL) THEN _
                     (
          'unknown, unasked'::text
                     ) WHEN
                     (a.has_allergy = 0) THEN _
                     ('no known allergies'::text) WHEN
                     (a.has_allergy = 1) THEN _
                     ('does have allergies'::text) ELSE NULL::text END
               ) || COALESCE
               (
                     (
                           (
                                 (
                                    ' ('::text || _
                                             ('last confirmed'::text)
                                       ) || to_char
                                       (a.last_confirmed
                                             ,' YYYY-MM-DD HH24:MI'::text
                                       )
                                 ) ||
                         ')'::text
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               ('
     '::text || a.comment)
               ,''::text
         )
    ) AS narrative
    , a.fk_encounter
    , NULL::integer AS fk_episode
    , NULL::integer AS pk_health_issue
    , a.pk AS src_pk
    ,'clin.allergy_state'::text AS src_table
    , a.row_version
    FROM clin.allergy_state a;

Index - Schema clin

## View: clin.v_pat_encounters

Details on encounters.

clin.v_pat_encounters Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_encounter | integer |
| pk_patient | integer |
| started | timestamp with time zone |
| type | text |
| l10n_type | text |
| reason_for_encounter | text |
| assessment_of_encounter | text |
| last_affirmed | timestamp with time zone |
| source_time_zone | interval |
| started_original_tz | timestamp without time zone |
| last_affirmed_original_tz | timestamp without time zone |
| pk_location | integer |
| pk_type | integer |
| pk_generic_codes_rfe | integer[] |
| pk_generic_codes_aoe | integer[] |
| xmin_encounter | xid |

    SELECT c_enc.pk AS pk_encounter
    , c_enc.fk_patient AS pk_patient
    , c_enc.started
    , et.description AS type
    , _
    (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
    , c_enc.fk_location AS pk_location
    , 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
    FROM clin.encounter c_enc
    , clin.encounter_type et
    WHERE (c_enc.fk_type = et.pk);

Index - Schema clin

## View: clin.v_pat_encounters_journal

clin.v_pat_encounters_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT cenc.fk_patient AS pk_patient
    , cenc.modified_when
    , cenc.started AS clin_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = cenc.modified_by)
         )
         , (
               ('<'::text ||
                     (cenc.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 = cenc.fk_type)
                                             )
                                       ) || to_char
                                       (cenc.started
                                             ,' YYYY-MM-DD HH24:MI'::text
                                       )
                                 ) || to_char
                                 (cenc.last_affirmed
                                       ,' - HH24:MI'::text
                                 )
                           ) || COALESCE
                           (
                                 (
                                       (
                                             ('
     '::text || _
                                                   ('RFE'::text)
                                             ) || ': '::text
                                       ) || cenc.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 = cenc.pk)
                                             )
                                             ,'; '::text
                                       )
                                 ) || ';'::text
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           (
                                 ('
     '::text || _
                                       ('AOE'::text)
                                 ) || ': '::text
                           ) || cenc.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 = cenc.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    , cenc.pk AS pk_encounter
    , (-1) AS pk_episode
    , (-1) AS pk_health_issue
    , cenc.pk AS src_pk
    ,'clin.encounter'::text AS src_table
    , cenc.row_version
    FROM clin.encounter cenc;

Index - Schema clin

## View: clin.v_pat_episodes

clin.v_pat_episodes Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| description | text |
| summary | text |
| episode_open | boolean |
| health_issue | text |
| issue_active | boolean |
| issue_clinically_relevant | boolean |
| started_first | timestamp with time zone |
| started_last | timestamp with time zone |
| last_affirmed | timestamp with time zone |
| pk_episode | integer |
| pk_encounter | integer |
| pk_health_issue | integer |
| episode_modified_when | timestamp with time zone |
| episode_modified_by | name |
| diagnostic_certainty_classification | text |
| diagnostic_certainty_classification_issue | text |
| pk_generic_codes | integer[] |
| xmin_episode | xid |

    SELECT cenc.fk_patient AS pk_patient
    , cep.description
    , cep.summary
    , cep.is_open AS episode_open
    , NULL::unknown AS health_issue
    , NULL::unknown AS issue_active
    , NULL::unknown 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::unknown AS pk_health_issue
    , cep.modified_when AS episode_modified_when
    , cep.modified_by AS episode_modified_by
    , cep.diagnostic_certainty_classification
    , NULL::unknown 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 ALLSELECT 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
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT cenc.fk_patient AS pk_patient
    , cep.modified_when
    , cenc.started AS clin_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = cep.modified_by)
         )
         , (
               ('<'::text ||
                     (cep.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    ,'a'::text AS soap_cat
    , (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (_
                                                   ('Episode'::text) ||
                                                ' ('::text) || CASE WHEN cep.is_open THEN _
                                                   ('open'::text) ELSE _
                                                   ('closed'::text) END
                                             ) || COALESCE
                                             (
                                                   (
                                                      ', '::text || cep.diagnostic_certainty_classification
                                                   )
                                                   ,''::text
                                             )
                                       ) ||
                             '): '::text
                           ) || cep.description
                     ) || ';'::text
               ) || COALESCE
               (
                     (
                           ('
    '::text || cep.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 = cep.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    , cep.fk_encounter AS pk_encounter
    , cep.pk AS pk_episode
    , cep.fk_health_issue AS pk_health_issue
    , cep.pk AS src_pk
    ,'clin.episode'::text AS src_table
    , cep.row_version
    FROM (clin.episode cep
      JOIN clin.encounter cenc
        ON (
               (cep.fk_encounter = cenc.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_hospital_stays

clin.v_pat_hospital_stays Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_hospital_stay | integer |
| pk_patient | integer |
| hospital | text |
| admission | timestamp with time zone |
| discharge | timestamp with time zone |
| soap_cat | text |
| episode | text |
| health_issue | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| modified_when | timestamp with time zone |
| modified_by | text |
| row_version | integer |
| xmin_hospital_stay | xid |

    SELECT chs.pk AS pk_hospital_stay
    , (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = chs.fk_encounter)
    ) AS pk_patient
    , chs.narrative AS hospital
    , chs.clin_when AS admission
    , chs.discharge
    , chs.soap_cat
    , (
    SELECT episode.description
      FROM clin.episode
     WHERE (episode.pk = chs.fk_episode)
    ) AS episode
    , (
    SELECT health_issue.description
      FROM clin.health_issue
     WHERE (health_issue.pk =
               (
                SELECT episode.fk_health_issue
                  FROM clin.episode
                 WHERE (episode.pk = chs.fk_episode)
               )
         )
    ) AS health_issue
    , chs.fk_encounter AS pk_encounter
    , chs.fk_episode AS pk_episode
    , (
    SELECT episode.fk_health_issue
      FROM clin.episode
     WHERE (episode.pk = chs.fk_episode)
    ) AS pk_health_issue
    , chs.modified_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = chs.modified_by)
         )
         , (
               ('<'::text ||
                     (chs.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    , chs.row_version
    , chs.xmin AS xmin_hospital_stay
    FROM clin.hospital_stay chs;

Index - Schema clin

## View: clin.v_pat_hospital_stays_journal

clin.v_pat_hospital_stays_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = chs.fk_encounter)
    ) AS pk_patient
    , chs.modified_when
    , chs.clin_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = chs.modified_by)
         )
         , (
               ('<'::text ||
                     (chs.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    , chs.soap_cat
    , (
         (
               (
                     (
                           (_
                                 ('hospital stay'::text) || ': '::text
                           ) || to_char
                           (chs.clin_when
                                 ,'YYYY-MM-DD'::text
                           )
                     ) || ' - '::text
               ) || COALESCE
               (to_char
                     (chs.discharge
                           ,'YYYY-MM-DD'::text
                     )
                     ,'?'::text
               )
         ) || COALESCE
         (
               (
                     (' "'::text || chs.narrative) || '"'::text
               )
               ,''::text
         )
    ) AS narrative
    , chs.fk_encounter AS pk_encounter
    , chs.fk_episode AS pk_episode
    , (
    SELECT episode.fk_health_issue
      FROM clin.episode
     WHERE (episode.pk = chs.fk_episode)
    ) AS pk_health_issue
    , chs.pk AS src_pk
    ,'clin.hospital_stay'::text AS src_table
    , chs.row_version
    FROM clin.hospital_stay chs;

Index - Schema clin

## View: clin.v_pat_items

clin.v_pat_items Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| modified_when | timestamp with time zone |
| modified_by | name |
| clin_when | timestamp with time zone |
| is_modified | boolean |
| pk_patient | integer |
| pk_item | integer |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| soap_cat | text |
| narrative | text |
| src_table | text |

    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
--- | --- | --- | ---
| pk_patient | integer |
| pk_vaccination | integer |
| date_given | timestamp with time zone |
| vaccine | text |
| indication | text |
| l10n_indication | text |
| site | text |
| batch_no | text |
| reaction | text |
| comment | text |
| soap_cat | text |
| modified_when | timestamp with time zone |
| modified_by | name |
| row_version | integer |
| pk_vaccine | integer |
| pk_indication | integer |
| pk_provider | integer |
| pk_encounter | integer |
| pk_episode | integer |
| xmin_vaccination | xid |
| indication_count | bigint |

    SELECT cvpv4i1.pk_patient
    , cvpv4i1.pk_vaccination
    , cvpv4i1.date_given
    , cvpv4i1.vaccine
    , cvpv4i1.indication
    , cvpv4i1.l10n_indication
    , cvpv4i1.site
    , cvpv4i1.batch_no
    , cvpv4i1.reaction
    , cvpv4i1.comment
    , cvpv4i1.soap_cat
    , cvpv4i1.modified_when
    , cvpv4i1.modified_by
    , cvpv4i1.row_version
    , cvpv4i1.pk_vaccine
    , cvpv4i1.pk_indication
    , cvpv4i1.pk_provider
    , cvpv4i1.pk_encounter
    , cvpv4i1.pk_episode
    , cvpv4i1.xmin_vaccination
    , cpi.indication_count
    FROM (clin.v_pat_vaccs4indication cvpv4i1
      JOIN (
          SELECT count
               (1) AS indication_count
               , v_pat_vaccs4indication.pk_patient
               , v_pat_vaccs4indication.pk_indication
            FROM clin.v_pat_vaccs4indication
        GROUP BY v_pat_vaccs4indication.pk_patient
               , v_pat_vaccs4indication.pk_indication
         ) cpi
        ON (
               (
                     (cvpv4i1.pk_patient = cpi.pk_patient)
                   AND (cvpv4i1.pk_indication = cpi.pk_indication)
               )
         )
    )
    WHERE (cvpv4i1.date_given =
         (
          SELECT max
               (cvpv4i2.date_given) AS max
            FROM clin.v_pat_vaccs4indication cvpv4i2
           WHERE (
                     (cvpv4i1.pk_patient = cvpv4i2.pk_patient)
                   AND (cvpv4i1.pk_indication = cvpv4i2.pk_indication)
               )
         )
    );

Index - Schema clin

## View: clin.v_pat_narrative

patient narrative aggregated from all clin_root_item child tables; the narrative is unprocessed, denormalized context using v_pat_items is added

clin.v_pat_narrative Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| date | timestamp with time zone |
| provider | text |
| soap_cat | text |
| narrative | text |
| pk_item | integer |
| pk_narrative | integer |
| pk_health_issue | integer |
| pk_episode | integer |
| pk_encounter | integer |
| xmin_clin_narrative | xid |
| modified_when | timestamp with time zone |
| row_version | integer |
| pk_generic_codes | integer[] |

    SELECT cenc.fk_patient AS pk_patient
    , cn.clin_when AS date
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = cn.modified_by)
         )
         , (
               ('<'::text ||
                     (cn.modified_by)::text
               ) || '>'::text
         )
    ) AS provider
    , cn.soap_cat
    , cn.narrative
    , cn.pk_item
    , cn.pk AS pk_narrative
    , (
    SELECT episode.fk_health_issue
      FROM clin.episode
     WHERE (episode.pk = cn.fk_episode)
    ) AS pk_health_issue
    , cn.fk_episode AS pk_episode
    , cn.fk_encounter AS pk_encounter
    , cn.xmin AS xmin_clin_narrative
    , cn.modified_when
    , cn.row_version
    , COALESCE
    (
         (
          SELECT array_agg
               (c_lc2n.fk_generic_code) AS array_agg
            FROM clin.lnk_code2narrative c_lc2n
           WHERE (c_lc2n.fk_item = cn.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    FROM (clin.clin_narrative cn
      JOIN clin.encounter cenc
        ON (
               (cn.fk_encounter = cenc.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_narrative_journal

clin.v_pat_narrative_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT cenc.fk_patient AS pk_patient
    , cn.modified_when
    , CASE WHEN
    (cn.soap_cat = ANY
         (ARRAY['s'::text
               ,'o'::text]
         )
    ) THEN cenc.started WHEN
    (cn.soap_cat IS NULL) THEN cenc.last_affirmed WHEN
    (cn.soap_cat = ANY
         (ARRAY['a'::text
               ,'p'::text]
         )
    ) THEN cenc.last_affirmed ELSE NULL::timestamp with time zone END AS clin_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = cn.modified_by)
         )
         , (
               ('<'::text ||
                     (cn.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    , cn.soap_cat
    , cn.narrative
    , cn.fk_encounter AS pk_encounter
    , cn.fk_episode AS pk_episode
    , (
    SELECT episode.fk_health_issue
      FROM clin.episode
     WHERE (episode.pk = cn.fk_episode)
    ) AS pk_health_issue
    , cn.pk AS src_pk
    ,'clin.clin_narrative'::text AS src_table
    , cn.row_version
    FROM (clin.clin_narrative cn
      JOIN clin.encounter cenc
        ON (
               (cn.fk_encounter = cenc.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_procedures

clin.v_pat_procedures Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_procedure | integer |
| pk_patient | integer |
| soap_cat | text |
| clin_when | timestamp with time zone |
| clin_end | timestamp with time zone |
| is_ongoing | boolean |
| performed_procedure | text |
| clin_where | text |
| episode | text |
| health_issue | text |
| modified_when | timestamp with time zone |
| modified_by | text |
| row_version | integer |
| pk_encounter | integer |
| pk_episode | integer |
| pk_hospital_stay | integer |
| pk_health_issue | integer |
| pk_generic_codes | integer[] |
| xmin_procedure | xid |

    SELECT cpr.pk AS pk_procedure
    , cenc.fk_patient AS pk_patient
    , cpr.soap_cat
    , cpr.clin_when
    , cpr.clin_end
    , cpr.is_ongoing
    , cpr.narrative AS performed_procedure
    , CASE WHEN
    (cpr.fk_hospital_stay IS NULL) THEN cpr.clin_where ELSE chs.narrative END AS clin_where
    , cep.description AS episode
    , chi.description AS health_issue
    , cpr.modified_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = cpr.modified_by)
         )
         , (
               ('<'::text ||
                     (cpr.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    , cpr.row_version
    , cpr.fk_encounter AS pk_encounter
    , cpr.fk_episode AS pk_episode
    , cpr.fk_hospital_stay AS pk_hospital_stay
    , cep.fk_health_issue AS pk_health_issue
    , COALESCE
    (
         (
          SELECT array_agg
               (c_lc2p.fk_generic_code) AS array_agg
            FROM clin.lnk_code2procedure c_lc2p
           WHERE (c_lc2p.fk_item = cpr.pk)
         )
         , ARRAY[]::integer[]
    ) AS pk_generic_codes
    , cpr.xmin AS xmin_procedure
    FROM (
         (
               (
                     (clin.procedure cpr
                        JOIN clin.encounter cenc
                          ON (
                                 (cpr.fk_encounter = cenc.pk)
                           )
                     )
                  JOIN clin.episode cep
                    ON (
                           (cpr.fk_episode = cep.pk)
                     )
               )
       LEFT JOIN clin.health_issue chi
              ON (
                     (cep.fk_health_issue = chi.pk)
               )
         )
    LEFT JOIN clin.hospital_stay chs
        ON (
               (cpr.fk_hospital_stay = chs.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_procedures_journal

clin.v_pat_procedures_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT cenc.fk_patient AS pk_patient
    , cpr.modified_when
    , cpr.clin_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = cpr.modified_by)
         )
         , (
               ('<'::text ||
                     (cpr.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    , cpr.soap_cat
    , (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (_
                                                   ('Procedure'::text) || ' "'::text
                                             ) || cpr.narrative
                                       ) || '"'::text
                                 ) ||
                              ' ('::text) || CASE WHEN
                                 (cpr.fk_hospital_stay IS NULL) THEN cpr.clin_where ELSE chs.narrative END
                           ) || COALESCE
                           (
                                 (
                                       (
                                             (
                                                ', '::text || _
                                                   ('until'::text)
                                             ) || ' '::text
                                       ) || to_char
                                       (cpr.clin_end
                                             ,'YYYY Mon DD'::text
                                       )
                                 )
                                 , CASE WHEN
                                 (cpr.is_ongoing IS TRUE) THEN
                                 (
                                    ', '::text || _
                                       ('ongoing'::text)
                                 ) ELSE ''::text END
                           )
                     ) ||
             ')'::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 = cpr.pk)
                                 )
                                 ,'; '::text
                           )
                     ) || ';'::text
               )
               ,''::text
         )
    ) AS narrative
    , cpr.fk_encounter AS pk_encounter
    , cpr.fk_episode AS pk_episode
    , cep.fk_health_issue AS pk_health_issue
    , cpr.pk AS src_pk
    ,'clin.procedure'::text AS src_table
    , cpr.row_version
    FROM (
         (
               (clin.procedure cpr
                  JOIN clin.encounter cenc
                    ON (
                           (cpr.fk_encounter = cenc.pk)
                     )
               )
            JOIN clin.episode cep
              ON (
                     (cpr.fk_episode = cep.pk)
               )
         )
    LEFT JOIN clin.hospital_stay chs
        ON (
               (cpr.fk_hospital_stay = chs.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_substance_intake

clin.v_pat_substance_intake Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_substance_intake | integer |
| pk_patient | integer |
| soap_cat | text |
| brand | text |
| preparation | text |
| substance | text |
| amount | numeric |
| unit | text |
| atc_substance | text |
| atc_brand | text |
| external_code_brand | text |
| external_code_type_brand | text |
| started | timestamp with time zone |
| intake_is_approved_of | boolean |
| schedule | text |
| duration | interval |
| discontinued | timestamp with time zone |
| discontinue_reason | text |
| is_long_term | boolean |
| aim | text |
| episode | text |
| notes | text |
| fake_brand | boolean |
| is_currently_active | boolean |
| seems_inactive | boolean |
| pk_brand | integer |
| pk_data_source | integer |
| pk_substance | integer |
| pk_drug_component | integer |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| modified_when | timestamp with time zone |
| modified_by | name |
| row_version | integer |
| xmin_substance_intake | xid |

    SELECT c_si.pk AS pk_substance_intake
    , (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = c_si.fk_encounter)
    ) AS pk_patient
    , c_si.soap_cat
    , r_bd.description AS brand
    , r_bd.preparation
    , r_cs.description AS substance
    , r_cs.amount
    , r_cs.unit
    , r_cs.atc_code AS atc_substance
    , r_bd.atc_code AS atc_brand
    , r_bd.external_code AS external_code_brand
    , r_bd.external_code_type AS external_code_type_brand
    , c_si.clin_when AS started
    , c_si.intake_is_approved_of
    , c_si.schedule
    , c_si.duration
    , c_si.discontinued
    , c_si.discontinue_reason
    , c_si.is_long_term
    , c_si.aim
    , cep.description AS episode
    , c_si.narrative AS notes
    , r_bd.is_fake AS fake_brand
    , 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_ls2b.fk_brand AS pk_brand
    , r_bd.fk_data_source AS pk_data_source
    , r_ls2b.fk_substance AS pk_substance
    , r_ls2b.pk AS pk_drug_component
    , c_si.fk_encounter AS pk_encounter
    , c_si.fk_episode AS pk_episode
    , cep.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
                        JOIN ref.lnk_substance2brand r_ls2b
                          ON (
                                 (c_si.fk_drug_component = r_ls2b.pk)
                           )
                     )
                  JOIN ref.branded_drug r_bd
                    ON (
                           (r_ls2b.fk_brand = r_bd.pk)
                     )
               )
            JOIN ref.consumable_substance r_cs
              ON (
                     (r_ls2b.fk_substance = r_cs.pk)
               )
         )
    LEFT JOIN clin.episode cep
        ON (
               (c_si.fk_episode = cep.pk)
         )
    )
    WHERE (c_si.fk_drug_component IS NOT NULL)
    UNION ALLSELECT c_si.pk AS pk_substance_intake
    , (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = c_si.fk_encounter)
    ) AS pk_patient
    , c_si.soap_cat
    , NULL::unknown AS brand
    , c_si.preparation
    , r_cs.description AS substance
    , r_cs.amount
    , r_cs.unit
    , r_cs.atc_code AS atc_substance
    , NULL::unknown AS atc_brand
    , NULL::unknown AS external_code_brand
    , NULL::unknown AS external_code_type_brand
    , c_si.clin_when AS started
    , c_si.intake_is_approved_of
    , c_si.schedule
    , c_si.duration
    , c_si.discontinued
    , c_si.discontinue_reason
    , c_si.is_long_term
    , c_si.aim
    , cep.description AS episode
    , c_si.narrative AS notes
    , NULL::unknown AS fake_brand
    , 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
    , NULL::unknown AS pk_brand
    , NULL::unknown AS pk_data_source
    , r_cs.pk AS pk_substance
    , NULL::unknown AS pk_drug_component
    , c_si.fk_encounter AS pk_encounter
    , c_si.fk_episode AS pk_episode
    , cep.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
            JOIN ref.consumable_substance r_cs
              ON (
                     (c_si.fk_substance = r_cs.pk)
               )
         )
    LEFT JOIN clin.episode cep
        ON (
               (c_si.fk_episode = cep.pk)
         )
    )
    WHERE (c_si.fk_drug_component IS NULL);

Index - Schema clin

## View: clin.v_pat_substance_intake_journal

clin.v_pat_substance_intake_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = c_si.fk_encounter)
    ) 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
                                                                           ) || ' '::text
                                                                     ) || r_cs.description
                                                               ) || COALESCE
                                                               (
                                                                     (
                                                                           (' ['::text || r_cs.atc_code) || '] '::text
                                                                     )
                                                                     ,' '::text
                                                               )
                                                         ) ||
                                                         (r_cs.amount)::text
                                                   ) || r_cs.unit
                                             ) || ' '::text
                                       ) || r_bd.preparation
                                 ) || COALESCE
                                 (
                                       (' '::text || c_si.schedule)
                                       ,''::text
                                 )
                           ) ||
                        ', '::text
                     ) || to_char
                     (c_si.clin_when
                           ,'YYYY-MM-DD'::text
                     )
               ) || 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
    (     NULLIF
    (
         (
               (COALESCE
                     (
                           (' '::text || c_si.aim)
                           ,''::text
                     ) || COALESCE
                     (
                           (
                                 (
                                    ' ('::text || c_si.narrative) ||
                               ')'::text
                           )
                           ,''::text
                     )
               ) || '
    '::text
         )
         ,'
    '::text
    )
    ,''::text
    )
    )            || COALESCE
    (
    (
    (
         (
               (' "'::text || r_bd.description) || '"'::text
         ) || COALESCE
         (
               (
                     (' ['::text || r_bd.atc_code) || ']'::text
               )
               ,''::text
         )
    ) || COALESCE
    (
         (
               (
                     (
                           (
                              ' ('::text || r_bd.external_code_type) || ': '::text
                           ) || r_bd.external_code
                     ) ||
             ')'::text
         )
         ,''::text
    )
    )
    ,     ''::text
    )
    )                  AS narrative
    ,                  c_si.fk_encounter AS pk_encounter
    ,                  c_si.fk_episode AS pk_episode
    ,                  (
    SELECT       episode.fk_health_issue
    FROM         clin.episode
    WHERE        (episode.pk = c_si.fk_episode)
    )                  AS pk_health_issue
    ,                  c_si.pk AS src_pk
    ,                 'clin.substance_intake'::text AS src_table
    ,                  c_si.row_version
    FROM               (
    (
    (     clin.substance_intake c_si
    JOIN ref.lnk_substance2brand r_ls2b
    ON (
         (c_si.fk_drug_component = r_ls2b.pk)
    )
    )
    JOIN   ref.branded_drug r_bd
    ON     (
    (r_bd.pk = r_ls2b.fk_brand)
    )
    )
    JOIN         ref.consumable_substance r_cs
    ON           (
    (     r_cs.pk = r_ls2b.fk_substance)
    )
    )
    WHERE              (c_si.fk_drug_component IS NOT NULL)
    UNION ALL         SELECT (
    SELECT       encounter.fk_patient
    FROM         clin.encounter
    WHERE        (encounter.pk = c_si.fk_encounter)
    )                  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
                                                   ) || ' '::text
                                             ) || r_cs.description
                                       ) || COALESCE
                                       (
                                             (
                                                   (' ['::text || r_cs.atc_code) || '] '::text
                                             )
                                             ,' '::text
                                       )
                                 ) || r_cs.amount
                           ) || r_cs.unit
                     ) || ' '::text
               ) || c_si.preparation
         ) || COALESCE
         (
               (' '::text || c_si.schedule)
               ,''::text
         )
    ) ||
    ', '::text
    )      || to_char
    (     c_si.clin_when
    ,'YYYY-MM-DD'::text
    )
    )            || 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
    (                             NULLIF
    (
    (
    (           COALESCE
    (
    (' '::text || c_si.aim)
    ,''::text
    )      || COALESCE
    (
    (
         (
            ' ('::text || c_si.narrative) ||
       ')'::text
    )
    ,''::text
    )
    )            || '
    '::text
    )
    ,                 '
    '::text
    )
    ,                       ''::text
    )
    )                                    AS narrative
    ,                                    c_si.fk_encounter AS pk_encounter
    ,                                    c_si.fk_episode AS pk_episode
    ,                                    (
    SELECT                         episode.fk_health_issue
    FROM                           clin.episode
    WHERE                          (episode.pk = c_si.fk_episode)
    )                                    AS pk_health_issue
    ,                                    c_si.pk AS src_pk
    ,                                   'clin.substance_intake'::text AS src_table
    ,                                    c_si.row_version
    FROM                                 (clin.substance_intake c_si
    JOIN                           ref.consumable_substance r_cs
    ON                             (
    (                       r_cs.pk = c_si.fk_substance)
    )
    )
    WHERE                                (c_si.fk_drug_component IS NULL);

Index - Schema clin

## View: clin.v_pat_vaccinations

Lists vaccinations for patients

clin.v_pat_vaccinations Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| pk_vaccination | integer |
| date_given | timestamp with time zone |
| vaccine | text |
| indications | text[] |
| l10n_indications | text[] |
| site | text |
| batch_no | text |
| reaction | text |
| comment | text |
| soap_cat | text |
| modified_when | timestamp with time zone |
| modified_by | name |
| row_version | integer |
| pk_indications | integer[] |
| pk_vaccine | integer |
| pk_provider | integer |
| pk_encounter | integer |
| pk_episode | integer |
| xmin_vaccination | xid |

    SELECT cenc.fk_patient AS pk_patient
    , clv.pk AS pk_vaccination
    , clv.clin_when AS date_given
    , rbd.description AS vaccine
    , (
    SELECT array_agg
         (cvi.description) AS array_agg
      FROM (clin.lnk_vaccine2inds clvi
            JOIN clin.vacc_indication cvi
              ON (
                     (clvi.fk_indication = cvi.id)
               )
         )
     WHERE (clvi.fk_vaccine = clv.fk_vaccine)
    ) AS indications
    , (
    SELECT array_agg
         (_
               (cvi.description)
         ) AS array_agg
      FROM (clin.lnk_vaccine2inds clvi
            JOIN clin.vacc_indication cvi
              ON (
                     (clvi.fk_indication = cvi.id)
               )
         )
     WHERE (clvi.fk_vaccine = clv.fk_vaccine)
    ) AS l10n_indications
    , clv.site
    , clv.batch_no
    , clv.reaction
    , clv.narrative AS comment
    , clv.soap_cat
    , clv.modified_when
    , clv.modified_by
    , clv.row_version
    , (
    SELECT array_agg
         (clvi.fk_indication) AS array_agg
      FROM (clin.lnk_vaccine2inds clvi
            JOIN clin.vacc_indication cvi
              ON (
                     (clvi.fk_indication = cvi.id)
               )
         )
     WHERE (clvi.fk_vaccine = clv.pk)
    ) AS pk_indications
    , clv.fk_vaccine AS pk_vaccine
    , clv.fk_provider AS pk_provider
    , clv.fk_encounter AS pk_encounter
    , clv.fk_episode AS pk_episode
    , clv.xmin AS xmin_vaccination
    FROM (
         (
               (clin.vaccination clv
                  JOIN clin.encounter cenc
                    ON (
                           (cenc.pk = clv.fk_encounter)
                     )
               )
            JOIN clin.vaccine
              ON (
                     (vaccine.pk = clv.fk_vaccine)
               )
         )
      JOIN ref.branded_drug rbd
        ON (
               (vaccine.fk_brand = rbd.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_vaccinations_journal

Vaccination data denormalized for the EMR journal.

clin.v_pat_vaccinations_journal Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT cenc.fk_patient AS pk_patient
    , cv.modified_when
    , cv.clin_when
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = cv.modified_by)
         )
         , (
               ('<'::text ||
                     (cv.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    , cv.soap_cat
    , (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (_
                                                               ('Vaccination'::text) || ': '::text
                                                         ) || rbd.description
                                                   ) || ' '::text
                                             ) || '['::text
                                       ) || cv.batch_no
                                 ) || ']'::text
                           ) || COALESCE
                           (
                                 (
                                       (
                                          ' ('::text || cv.site) ||
                                     ')'::text
                                 )
                                 ,''::text
                           )
                     ) || COALESCE
                     (
                           (
                                 (
                                       ('
    '::text || _
                                             ('Reaction'::text)
                                       ) || ': '::text
                                 ) || cv.reaction
                           )
                           ,''::text
                     )
               ) || COALESCE
               (
                     (
                           (
                                 ('
    '::text || _
                                       ('Comment'::text)
                                 ) || ': '::text
                           ) || cv.narrative
                     )
                     ,''::text
               )
         ) || COALESCE
         (
               (
                     (
                           ('
    '::text || _
                                 ('Indications'::text)
                           ) || ': '::text
                     ) || array_to_string
                     (
                           (
                            SELECT array_agg
                                 (_
                                       (cvi.description)
                                 ) AS array_agg
                              FROM (clin.lnk_vaccine2inds clvi
                                    JOIN clin.vacc_indication cvi
                                      ON (
                                             (clvi.fk_indication = cvi.id)
                                       )
                                 )
                             WHERE (clvi.fk_vaccine = cv.fk_vaccine)
                           )
                           ,' / '::text
                     )
               )
               ,''::text
         )
    ) AS narrative
    , cv.fk_encounter AS pk_encounter
    , cv.fk_episode AS pk_episode
    , (
    SELECT episode.fk_health_issue
      FROM clin.episode
     WHERE (episode.pk = cv.fk_episode)
    ) AS pk_health_issue
    , cv.pk AS src_pk
    ,'clin.vaccination'::text AS src_table
    , cv.row_version
    FROM (
         (
               (clin.vaccination cv
                  JOIN clin.encounter cenc
                    ON (
                           (cenc.pk = cv.fk_encounter)
                     )
               )
            JOIN clin.vaccine
              ON (
                     (vaccine.pk = cv.fk_vaccine)
               )
         )
      JOIN ref.branded_drug rbd
        ON (
               (vaccine.fk_brand = rbd.pk)
         )
    );

Index - Schema clin

## View: clin.v_pat_vaccs4indication

Lists vaccinations per indication for patients

clin.v_pat_vaccs4indication Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| pk_vaccination | integer |
| date_given | timestamp with time zone |
| vaccine | text |
| indication | text |
| l10n_indication | text |
| site | text |
| batch_no | text |
| reaction | text |
| comment | text |
| soap_cat | text |
| modified_when | timestamp with time zone |
| modified_by | name |
| row_version | integer |
| pk_vaccine | integer |
| pk_indication | integer |
| pk_provider | integer |
| pk_encounter | integer |
| pk_episode | integer |
| xmin_vaccination | xid |

    SELECT cenc.fk_patient AS pk_patient
    , cv.pk AS pk_vaccination
    , cv.clin_when AS date_given
    , cvi4v.vaccine
    , cvi4v.indication
    , cvi4v.l10n_indication
    , cv.site
    , cv.batch_no
    , cv.reaction
    , cv.narrative AS comment
    , cv.soap_cat
    , cv.modified_when
    , cv.modified_by
    , cv.row_version
    , cv.fk_vaccine AS pk_vaccine
    , cvi4v.pk_indication
    , cv.fk_provider AS pk_provider
    , cv.fk_encounter AS pk_encounter
    , cv.fk_episode AS pk_episode
    , cv.xmin AS xmin_vaccination
    FROM (
         (clin.vaccination cv
            JOIN clin.encounter cenc
              ON (
                     (cenc.pk = cv.fk_encounter)
               )
         )
      JOIN clin.v_indications4vaccine cvi4v
        ON (
               (cvi4v.pk_vaccine = cv.fk_vaccine)
         )
    );

Index - Schema clin

## View: clin.v_potential_problem_list

clin.v_potential_problem_list Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_patient | integer |
| problem | text |
| summary | text |
| type | text |
| l10n_type | text |
| problem_active | boolean |
| clinically_relevant | boolean |
| pk_episode | integer |
| pk_health_issue | integer |
| diagnostic_certainty_classification | text |
| pk_encounter | integer |
| modified_when | timestamp with time zone |

    SELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = cep.fk_encounter)
    ) AS pk_patient
    , cep.description AS problem
    , cep.summary
    ,'episode' 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)
    UNIONSELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = chi.fk_encounter)
    ) AS pk_patient
    , chi.description AS problem
    , chi.summary
    ,'issue' AS type
    , _
    ('health issue'::text) AS l10n_type
    , chi.is_active AS problem_active
    , false AS clinically_relevant
    , NULL::unknown 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
--- | --- | --- | ---
| pk_patient | integer |
| problem | text |
| summary | text |
| type | text |
| l10n_type | text |
| problem_active | boolean |
| clinically_relevant | boolean |
| pk_episode | integer |
| pk_health_issue | integer |
| diagnostic_certainty_classification | text |
| pk_encounter | integer |
| modified_when | timestamp with time zone |

    SELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = cep.fk_encounter)
    ) AS pk_patient
    , cep.description AS problem
    , cep.summary
    ,'episode' 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)
    UNIONSELECT (
    SELECT encounter.fk_patient
      FROM clin.encounter
     WHERE (encounter.pk = chi.fk_encounter)
    ) AS pk_patient
    , chi.description AS problem
    , chi.summary
    ,'issue' AS type
    , _
    ('health issue'::text) AS l10n_type
    , chi.is_active AS problem_active
    , true AS clinically_relevant
    , NULL::unknown 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_reviewed_items

denormalization of parent table of reviewed items

clin.v_reviewed_items Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| src_schema | oid |
| src_table | name |
| pk_reviewed_row | integer |
| is_technically_abnormal | boolean |
| clinically_relevant | boolean |
| reviewer | text |
| comment | text |
| pk_review_root | integer |
| pk_reviewer | integer |

    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_test_orgs

clin.v_test_orgs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_test_org | integer |
| organization | text |
| unit | text |
| comment | text |
| test_org_contact | text |
| pk_adm_contact | integer |
| pk_med_contact | integer |
| pk_org | integer |
| category_org | integer |
| pk_org_unit | integer |
| category_unit | integer |
| pk_address_unit | integer |
| xmin_test_org | xid |

    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_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
--- | --- | --- | ---
| pk_patient | integer |
| pk_test_result | integer |
| clin_when | timestamp with time zone |
| unified_abbrev | text |
| unified_name | text |
| unified_loinc | text |
| unified_val | text |
| unified_target_min | numeric |
| unified_target_max | numeric |
| unified_target_range | text |
| soap_cat | text |
| comment | text |
| val_num | numeric |
| val_alpha | text |
| val_unit | text |
| conversion_unit | text |
| val_normal_min | numeric |
| val_normal_max | numeric |
| val_normal_range | text |
| val_target_min | numeric |
| val_target_max | numeric |
| val_target_range | text |
| abnormality_indicator | text |
| norm_ref_group | text |
| note_test_org | text |
| material | text |
| material_detail | text |
| abbrev_tt | text |
| name_tt | text |
| loinc_tt | text |
| code_tt | text |
| coding_system_tt | text |
| comment_tt | text |
| name_test_org | text |
| contact_test_org | text |
| abbrev_meta | text |
| name_meta | text |
| loinc_meta | text |
| comment_meta | text |
| episode | text |
| health_issue | text |
| reviewed | boolean |
| is_technically_abnormal | boolean |
| is_clinically_relevant | boolean |
| review_comment | text |
| last_reviewer | text |
| last_reviewed | timestamp with time zone |
| review_by_you | boolean |
| review_by_responsible_reviewer | boolean |
| responsible_reviewer | text |
| you_are_responsible | boolean |
| modified_by | text |
| modified_when | timestamp with time zone |
| row_version | integer |
| pk_item | integer |
| pk_encounter | integer |
| pk_episode | integer |
| pk_test_type | integer |
| pk_intended_reviewer | integer |
| pk_request | integer |
| xmin_test_result | xid |
| pk_test_org | integer |
| pk_meta_test_type | integer |
| pk_health_issue | integer |
| pk_last_reviewer | integer |

    SELECT cenc.fk_patient AS pk_patient
    , tr.pk AS pk_test_result
    , tr.clin_when
    , vutt.unified_abbrev
    , vutt.unified_name
    , vutt.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.soap_cat
    , tr.narrative AS comment
    , tr.val_num
    , tr.val_alpha
    , tr.val_unit
    , vutt.conversion_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
    , vutt.abbrev_tt
    , vutt.name_tt
    , vutt.loinc_tt
    , vutt.code_tt
    , vutt.coding_system_tt
    , vutt.comment_tt
    , d_ou.description AS name_test_org
    , cto.contact AS contact_test_org
    , vutt.abbrev_meta
    , vutt.name_meta
    , vutt.loinc_meta
    , vutt.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.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
    , vutt.pk_test_org
    , vutt.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_unified_test_types vutt
       LEFT JOIN clin.test_org cto
              ON (
                     (vutt.pk_test_org = cto.pk)
               )
         )
    LEFT JOIN dem.org_unit d_ou
        ON (
               (cto.fk_org_unit = d_ou.pk)
         )
    )
    WHERE (tr.fk_type = vutt.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
--- | --- | --- | ---
| pk_patient | integer |
| modified_when | timestamp with time zone |
| clin_when | timestamp with time zone |
| modified_by | text |
| soap_cat | text |
| narrative | text |
| pk_encounter | integer |
| pk_episode | integer |
| pk_health_issue | integer |
| src_pk | integer |
| src_table | text |
| row_version | integer |

    SELECT vtr.pk_patient
    , vtr.modified_when
    , vtr.clin_when
    , vtr.modified_by
    , vtr.soap_cat
    , COALESCE
    (
         (
               (
                     (
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (
                                                                           (
                                                                                 (
                                                                                       (
                                                                                             (
                                                                                                   (
                                                                                                         (
                                                                                                               (
                                                                                                                     (
                                                                                                                           (
                                                                                                                                 (
                                                                                                                                       (
                                                                                                                                             (vtr.unified_name ||
                                                                                                                                                ' ('::text) || vtr.unified_abbrev
                                                                                                                                             ) || COALESCE
                                                                                                                                             (
                                                                                                                                                   (
                                                                                                                                                         (' [#'::text || vtr.unified_loinc) || ']'::text
                                                                                                                                                   )
                                                                                                                                                   ,''::text
                                                                                                                                             )
                                                                                                                                       ) ||
                                                                                                                             '): '::text
                                                                                                                           ) || vtr.unified_val
                                                                                                                     ) || ' '::text
                                                                                                               ) || COALESCE
                                                                                                               (vtr.val_unit
                                                                                                                     ,''::text
                                                                                                               )
                                                                                                         ) || ' '::text
                                                                                                   ) || COALESCE
                                                                                                   (
                                                                                                         (
                                                                                                               (
                                                                                                                   '('::text || vtr.abnormality_indicator) ||
                                                                                                             ')'::text
                                                                                                         )
                                                                                                         ,''::text
                                                                                                   )
                                                                                             ) || '
    '::text
                                                                                       ) || _
                                                                                       ('Range: '::text)
                                                                                 ) || COALESCE
                                                                                 (
                                                                                       (vtr.unified_target_min)::text
                                                                                       ,''::text
                                                                                 )
                                                                           ) || ' - '::text
                                                                     ) || COALESCE
                                                                     (
                                                                           (vtr.unified_target_max)::text
                                                                           ,''::text
                                                                     )
                                                               ) || ' / '::text
                                                         ) || COALESCE
                                                         (vtr.unified_target_range
                                                               ,''::text
                                                         )
                                                   ) || COALESCE
                                                   (
                                                         (
                                                               (
                                                                  ' ('::text || vtr.norm_ref_group) ||
                                                             ')'::text
                                                         )
                                                         ,''::text
                                                   )
                                             ) || '
    '::text
                                       ) || COALESCE
                                       (
                                             (
                                                   (_
                                                         ('Assessment: '::text) || vtr.comment
                                                   ) || '
    '::text
                                             )
                                             ,''::text
                                       )
                                 ) || COALESCE
                                 (
                                       (
                                             (_
                                                   ('Context: '::text) || vtr.note_test_org
                                             ) || '
    '::text
                                       )
                                       ,''::text
                                 )
                           ) || COALESCE
                           (
                                 (
                                       (
                                             (
                                                   (
                                                         (
                                                               (
                                                                     (_
                                                                           ('Review by '::text) || vtr.last_reviewer
                                                                     ) || ' @ '::text
                                                               ) || to_char
                                                               (vtr.last_reviewed
                                                                     ,'YYYY-MM-DD HH24:MI'::text
                                                               )
                                                         ) || ': '::text
                                                   ) || CASE WHEN vtr.is_technically_abnormal THEN
                                                   (_
                                                         ('abnormal'::text) ||
                                                      ', '::text
                                                   ) ELSE ''::text END
                                             ) || CASE WHEN vtr.is_clinically_relevant THEN
                                             (_
                                                   ('relevant'::text) || ' '::text
                                             ) ELSE ''::text END
                                       ) || COALESCE
                                       (
                                             (
                                                   (
                                                       '('::text || vtr.review_comment) ||
                                                ')
    '::text
                                             )
                                             ,'
    '::text
                                       )
                                 )
                                 ,''::text
                           )
                     ) || _
                     ('Responsible clinician: '::text)
               ) || vtr.responsible_reviewer
         )
         ,'faulty clin.v_test_results_journal definition'::text
    ) AS narrative
    , vtr.pk_encounter
    , vtr.pk_episode
    , vtr.pk_health_issue
    , vtr.pk_test_result AS src_pk
    ,'clin.test_result'::text AS src_table
    , vtr.row_version
    FROM clin.v_test_results vtr;

Index - Schema clin

## View: clin.v_test_types

denormalizes test types with test orgs

clin.v_test_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_test_type | integer |
| abbrev | text |
| name | text |
| loinc | text |
| code | text |
| coding_system | text |
| conversion_unit | text |
| comment_type | text |
| name_org | text |
| comment_org | text |
| contact_org | text |
| pk_test_org | integer |
| pk_org_unit | integer |
| pk_adm_contact_org | integer |
| pk_med_contact_org | integer |
| xmin_test_type | xid |

    SELECT ctt.pk AS pk_test_type
    , ctt.abbrev
    , ctt.name
    , ctt.loinc
    , ctt.code
    , ctt.coding_system
    , ctt.conversion_unit
    , ctt.comment AS comment_type
    , d_ou.description AS name_org
    , cto.comment AS comment_org
    , cto.contact AS contact_org
    , ctt.fk_test_org AS pk_test_org
    , cto.fk_org_unit AS pk_org_unit
    , cto.fk_adm_contact AS pk_adm_contact_org
    , cto.fk_med_contact AS pk_med_contact_org
    , ctt.xmin AS xmin_test_type
    FROM (
         (clin.test_type ctt
       LEFT JOIN clin.test_org cto
              ON (
                     (cto.pk = ctt.fk_test_org)
               )
         )
    LEFT JOIN dem.org_unit d_ou
        ON (
               (cto.fk_org_unit = d_ou.pk)
         )
    );

Index - Schema clin

## View: clin.v_unified_test_types

provides a "unified" view of test types aggregated under their corresponding unified name if any; if not linked to a meta test type the original name is used

clin.v_unified_test_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_test_type | integer |
| unified_abbrev | text |
| unified_name | text |
| unified_loinc | text |
| abbrev_tt | text |
| name_tt | text |
| loinc_tt | text |
| comment_tt | text |
| code_tt | text |
| coding_system_tt | text |
| conversion_unit | text |
| abbrev_meta | text |
| name_meta | text |
| loinc_meta | text |
| comment_meta | text |
| pk_test_org | integer |
| pk_meta_test_type | integer |
| pk_lnk_ttype2meta_type | integer |
| is_fake_unified_type | boolean |

    SELECT ctt.pk AS pk_test_type
    , COALESCE
    (vmtt.abbrev_meta
         , ctt.abbrev
    ) AS unified_abbrev
    , COALESCE
    (vmtt.name_meta
         , ctt.name
    ) AS unified_name
    , COALESCE
    (vmtt.loinc_meta
         , ctt.loinc
    ) AS unified_loinc
    , ctt.abbrev AS abbrev_tt
    , ctt.name AS name_tt
    , ctt.loinc AS loinc_tt
    , ctt.comment AS comment_tt
    , ctt.code AS code_tt
    , ctt.coding_system AS coding_system_tt
    , ctt.conversion_unit
    , vmtt.abbrev_meta
    , vmtt.name_meta
    , vmtt.loinc_meta
    , vmtt.comment_meta
    , ctt.fk_test_org AS pk_test_org
    , vmtt.pk_meta_test_type
    , vmtt.pk_lnk_ttype2meta_type
    , (vmtt.pk_meta_test_type IS NULL) AS is_fake_unified_type
    FROM (clin.test_type ctt
    LEFT JOIN clin.v_meta_test_types vmtt
        ON (
               (ctt.pk = vmtt.pk_test_type)
         )
    );

Index - Schema clin

## View: clin.v_vaccination_courses_in_schedule

clin.v_vaccination_courses_in_schedule Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| vaccination_schedule | text |
| is_active | boolean |
| pk_recommended_by | integer |
| comment_course | text |
| comment_schedule | text |
| pk_vaccination_course | integer |
| pk_indication | integer |
| pk_vaccination_schedule | integer |

    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_vaccination_definitions4course

vaccination event definitions for all courses known to the system

clin.v_vaccination_definitions4course Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_course | integer |
| indication | text |
| l10n_indication | text |
| course_comment | text |
| is_active | boolean |
| pk_vaccination_definition | integer |
| is_booster | boolean |
| vacc_seq_no | integer |
| age_due_min | interval |
| age_due_max | interval |
| min_interval | interval |
| vacc_comment | text |
| pk_indication | integer |
| pk_recommended_by | integer |

    SELECT vcourse.pk AS pk_course
    , vind.description AS indication
    , _
    (vind.description) AS l10n_indication
    , COALESCE
    (vcourse.comment
         ,''::text
    ) AS course_comment
    , vcourse.is_active
    , vdef.id AS pk_vaccination_definition
    , vdef.is_booster
    , vdef.seq_no AS vacc_seq_no
    , vdef.min_age_due AS age_due_min
    , vdef.max_age_due AS age_due_max
    , vdef.min_interval
    , COALESCE
    (vdef.comment
         ,''::text
    ) AS vacc_comment
    , vind.id AS pk_indication
    , vcourse.fk_recommended_by AS pk_recommended_by
    FROM clin.vaccination_course vcourse
    , clin.vacc_indication vind
    , clin.vaccination_definition vdef
    WHERE (
         (vcourse.pk = vdef.fk_course)
       AND (vcourse.fk_indication = vind.id)
    )
    ORDER BY vind.description
    , vdef.seq_no;

Index - Schema clin

## View: clin.v_vaccines

A list of vaccines.

clin.v_vaccines Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_vaccine | integer |
| vaccine | text |
| preparation | text |
| atc_code | text |
| is_fake_vaccine | boolean |
| route_abbreviation | text |
| route_description | text |
| is_live | boolean |
| min_age | interval |
| max_age | interval |
| comment | text |
| indications | text[] |
| l10n_indications | text[] |
| external_code | text |
| external_code_type | text |
| pk_indications | integer[] |
| pk_route | integer |
| pk_brand | integer |
| pk_data_source | integer |
| xmin_vaccine | xid |

    SELECT cv.pk AS pk_vaccine
    , rbd.description AS vaccine
    , rbd.preparation
    , rbd.atc_code
    , rbd.is_fake AS is_fake_vaccine
    , cvr.abbreviation AS route_abbreviation
    , cvr.description AS route_description
    , cv.is_live
    , cv.min_age
    , cv.max_age
    , cv.comment
    , (
    SELECT array_agg
         (cvi.description) AS array_agg
      FROM (clin.lnk_vaccine2inds clvi
            JOIN clin.vacc_indication cvi
              ON (
                     (clvi.fk_indication = cvi.id)
               )
         )
     WHERE (clvi.fk_vaccine = cv.pk)
    ) AS indications
    , (
    SELECT array_agg
         (_
               (cvi.description)
         ) AS array_agg
      FROM (clin.lnk_vaccine2inds clvi
            JOIN clin.vacc_indication cvi
              ON (
                     (clvi.fk_indication = cvi.id)
               )
         )
     WHERE (clvi.fk_vaccine = cv.pk)
    ) AS l10n_indications
    , rbd.external_code
    , rbd.external_code_type
    , (
    SELECT array_agg
         (clvi.fk_indication) AS array_agg
      FROM (clin.lnk_vaccine2inds clvi
            JOIN clin.vacc_indication cvi
              ON (
                     (clvi.fk_indication = cvi.id)
               )
         )
     WHERE (clvi.fk_vaccine = cv.pk)
    ) AS pk_indications
    , cv.id_route AS pk_route
    , cv.fk_brand AS pk_brand
    , rbd.fk_data_source AS pk_data_source
    , cv.xmin AS xmin_vaccine
    FROM (
         (clin.vaccine cv
            JOIN ref.branded_drug rbd
              ON (
                     (cv.fk_brand = rbd.pk)
               )
         )
    LEFT JOIN clin.vacc_route cvr
        ON (
               (cv.id_route = cvr.id)
         )
    );

Index - Schema clin

## View: clin.v_waiting_list

clin.v_waiting_list Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| list_position | integer |
| waiting_zone | text |
| urgency | integer |
| title | text |
| firstnames | text |
| lastnames | text |
| preferred_name | text |
| dob | timestamp with time zone |
| gender | text |
| l10n_gender | text |
| registered | timestamp with time zone |
| waiting_time | interval |
| waiting_time_formatted | text |
| comment | text |
| pk_identity | integer |
| pk_name | integer |
| pupic | character(24) |
| pk_waiting_list | integer |

    SELECT wl.list_position
    , wl.area AS waiting_zone
    , wl.urgency
    , i.title
    , n.firstnames
    , n.lastnames
    , n.preferred AS preferred_name
    , i.dob
    , i.gender
    , _
    (i.gender) AS l10n_gender
    , wl.registered
    , (
    SELECT (now
               () - wl.registered
         )
    ) AS waiting_time
    , (
    SELECT to_char
         (age
               (now
                     ()
                     , wl.registered
               )
               ,'TMDD HH24:MI'::text
         ) AS to_char
    ) AS waiting_time_formatted
    , wl.comment
    , i.pk AS pk_identity
    , n.id AS pk_name
    , i.pupic
    , wl.pk AS pk_waiting_list
    FROM clin.waiting_list wl
    , dem.identity i
    , dem.names n
    WHERE (
         (
               (
                     (wl.fk_patient = i.pk)
                   AND (wl.fk_patient = n.id_identity)
               )
             AND (i.deceased IS NULL)
         )
       AND (n.active IS TRUE)
    );

Index - Schema clin

## View: clin.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.

clin.v_your_keyword_expansions Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_keyword_expansion | integer |
| pk_staff | integer |
| keyword | text |
| expansion | text |
| public_expansion | boolean |
| private_expansion | boolean |
| owner | text |

    SELECT DISTINCT
    ON (union_result.keyword) union_result.pk_keyword_expansion
    , union_result.pk_staff
    , union_result.keyword
    , union_result.expansion
    , union_result.public_expansion
    , union_result.private_expansion
    , union_result.owner
    FROM (
    SELECT cke.pk AS pk_keyword_expansion
         , cke.fk_staff AS pk_staff
         , cke.keyword
         , cke.expansion
         , false AS public_expansion
         , true AS private_expansion
         , cke.owner
      FROM clin.keyword_expansion cke
     WHERE (cke.fk_staff =
               (
                SELECT staff.pk
                  FROM dem.staff
                 WHERE (staff.db_user = "current_user"
                           ()
                     )
               )
         )
    UNION ALLSELECT cke.pk AS pk_keyword_expansion
         , cke.fk_staff AS pk_staff
         , cke.keyword
         , cke.expansion
         , true AS public_expansion
         , false AS private_expansion
         , cke.owner
      FROM clin.keyword_expansion cke
     WHERE (cke.fk_staff IS NULL)
    ORDER BY 6 DESC
    ) union_result;

Index - Schema clin

## Table: clin.vacc_indication

definition of indications for vaccinations

clin.vacc_indication Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
| description | text | UNIQUE NOT NULL description of indication, eg "Measles", note that this does not have to be a scientific diagnosis, it is simply intended to be an agreed-upon, medically-comprehensible unique identifier for the indication
| atcs_single_indication | text[] | The ATC codes for single-indication vaccines for this indication.
| atcs_combi_indication | text[] | The ATC codes for poly-indication vaccines including this indication.

Table clin.vacc_indication Inherits audit_fields,

clin.vacc_indication Constraints
Name | Constraint
--- | ---
vacc_indication_sane_combi_atcs | CHECK (((atcs_combi_indication IS NULL) OR (array_upper(atcs_combi_indication, 1) > 0)))
vacc_indication_sane_single_atcs | CHECK (((atcs_single_indication IS NULL) OR (array_upper(atcs_single_indication, 1) > 0)))

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_vaccine2inds

- clin.vaccination_course

Index - Schema clin

## Table: clin.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

clin.vacc_route Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
| abbreviation | text | UNIQUE NOT NULL
| description | text | UNIQUE NOT NULL

Table clin.vacc_route Inherits audit_fields,

Tables referencing this one via Foreign Key Constraints:

- clin.vaccine

Index - Schema clin

## Table: clin.vaccination

holds vaccinations actually given

clin.vaccination Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now()
clin.encounter.pk | fk_encounter | integer | NOT NULL
clin.episode.pk | fk_episode | integer | NOT NULL
| narrative | text | Used to record a comment on this vaccination.
| soap_cat | text | DEFAULT 'p'::text
| pk | serial | PRIMARY KEY
dem.staff.pk | fk_provider | integer | Who administered this vaccination.
clin.vaccine.pk | fk_vaccine | integer | NOT NULL
| site | text | The site of injection used in this vaccination.
| batch_no | text | NOT NULL The batch/lot number of the vaccine given.
| reaction | text | Used to record reactions to this vaccination.

Table clin.vaccination Inherits clin_root_item,

clin.vaccination 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]))))
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_vacc_encounter fk_encounter idx_vacc_episode fk_episode

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| fk_recommended_by | integer | the source/organization which defined this course, can be used to differentiate several locale-dependant courses for the same indication and yet tell them apart
clin.vacc_indication.id | fk_indication | integer | NOT NULL vaccination indication this course is targeted at
| is_active | boolean | NOT NULL DEFAULT true whether this course is active or not, if False: do not newly *start* patients on this course
| comment | text | a free-text comment on this vaccination course

Table clin.vaccination_course Inherits audit_fields,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | UNIQUE NOT NULL description/label/name of the constraint

Table clin.vaccination_course_constraint Inherits audit_fields,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
clin.vaccination_course.pk | fk_course | integer | UNIQUE#1 NOT NULL course to which this event belongs
| is_booster | boolean | NOT NULL DEFAULT false does this definition represent a booster, also set for quasi-booster courses such as Influenza
| seq_no | integer | UNIQUE#1 sequence number for this vaccination event within a particular course, NULL if (is_booster == true)
| min_age_due | interval | NOT NULL minimum age at which this shot is due
| max_age_due | interval | NOT NULL DEFAULT '01:32:35'::interval maximum age at which this shot is due, if max_age_due = "5555 years": no maximum age
| min_interval | interval | if (is_booster == true): recommended interval for boostering id (is_booster == false): minimum interval after previous vaccination, NULL if seq_no == 1
| comment | text |

Table clin.vaccination_definition Inherits audit_fields,

clin.vaccination_definition Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| name | text | UNIQUE NOT NULL name of the schedule as defined by some authority
| comment | text |

Table clin.vaccination_schedule Inherits audit_fields,

Tables referencing this one via Foreign Key Constraints:

- clin.lnk_vaccination_course2schedule

Index - Schema clin

## Table: clin.vaccine

definition of a vaccine as available on the market

clin.vaccine Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.vacc_route.id | id_route | integer | route this vaccine is given
| is_live | boolean | whether this is a live vaccine
| min_age | interval | minimum age this vaccine is licensed for according to the information by the manufacturer
| max_age | interval | maximum age this vaccine is licensed for according to the information by the manufacturer, use "5555 years" to indicate "no maximum age"
| comment | text |
ref.branded_drug.pk | fk_brand | integer | UNIQUE NOT NULL The brand of this vaccine, can be a fake entry in ref.branded_drug.

Table clin.vaccine Inherits audit_fields,

clin.vaccine Constraints
Name | Constraint
--- | ---
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.lnk_vaccine2inds

- clin.vaccination

- clin.vaccine_batches

idx_c_vaccine_id_route id_route

Index - Schema clin

## Table: clin.vaccine_batches

clin.vaccine_batches Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
clin.vaccine.pk | fk_vaccine | integer | NOT NULL
| batch_no | text | UNIQUE NOT NULL serial # of a batch of a given vaccine that is awaiting usage in the fridge

Table clin.vaccine_batches Inherits audit_fields,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.identity.pk | fk_patient | integer | NOT NULL the waiting patient
| registered | timestamp with time zone | NOT NULL DEFAULT now() when did the patient arrive (enter the waiting list, that is)
| urgency | integer | NOT NULL relative urgency, used by practices as they see fit, 0 - "standard" urgency < 0 - less urgent > 0 - more urgent
| list_position | integer | UNIQUE NOT NULL the currently assigned position of this patient on the waiting list
| comment | text | a free comment regarding this entry, NOT THE RFE !
| area | text | an arbitrary value by which filtering waiting patients into zones becomes possible

Table clin.waiting_list Inherits audit_fields,

clin.waiting_list Constraints
Name | Constraint
--- | ---
non_empty_area | CHECK ((btrim(area) <> ''::text))
waiting_list_list_position_check | CHECK ((list_position > 0))

Index - Schema clin

## 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_announce_clin_item_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	episode_id integer;
    	patient_id integer;
    begin
    	-- get episode ID
    	if TG_OP = 'DELETE' then
    		episode_id := OLD.fk_episode;
    	else
    		episode_id := NEW.fk_episode;
    	end if;
    	-- track back to patient ID
    	select into patient_id pk_patient
    		from clin.v_pat_episodes vpep
    		where vpep.pk_episode = episode_id
    		limit 1;
    	-- now, execute() the NOTIFY
    	execute 'notify "item_change_db:' || patient_id || '"';
    	return NULL;
    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.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 encountersolder 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;
    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 [%] does not exist', _pk_identity, _defined_minimum_encounter_age, _pk_identity;
    		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
    		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)
    	;
    	return true;
    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_allg_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_allg_mod(): cannot determine identity PK on table <clin.allergy>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "allg_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_allg_state_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_allg_state_mod(): cannot determine identity PK on table <clin.allergy_state>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "allg_state_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_aoe_code_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "aoe_code_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_clin_narrative_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_clin_narrative_mod(): cannot determine identity PK on table <clin.clin_narrative>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "clin_narrative_mod_db:' || _pk_identity || '"';
    	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_announce_encounter_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_patient
    	if TG_OP = 'DELETE' then
    		_pk_identity := OLD.fk_patient;
    	else
    		_pk_identity := NEW.fk_patient;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_encounter_mod(): cannot determine identity PK on table <clin.encounter>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "encounter_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_episode_code_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "episode_code_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_episode_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_episode_mod(): cannot determine identity PK on table <clin.episode>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "episode_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_family_history_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_family_history_mod(): cannot determine identity PK on table <clin.family_history>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "family_history_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_fhx_code_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "fhx_code_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_health_issue_code_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "health_issue_code_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_health_issue_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_health_issue_mod(): cannot determine identity PK on table <clin.health_issue>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "health_issue_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_hospital_stay_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_hospital_stay_mod(): cannot determine identity PK on table <clin.hospital_stay>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "hospital_stay_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_narrative_code_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "narrative_code_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_narrative_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_narrative_mod(): cannot determine identity PK on clin.clin_root_item child table';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "narrative_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_procedure_code_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "procedure_code_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_procedure_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_procedure_mod(): cannot determine identity PK on table <clin.procedure>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "procedure_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_reviewed_test_results_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "reviewed_test_results_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_rfe_code_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "rfe_code_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_substance_intake_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_substance_intake_mod(): cannot determine identity PK on table <clin.substance_intake>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "substance_intake_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_test_result_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_test_result_mod(): cannot determine identity PK on table <clin.test_result>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "test_result_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_vacc_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_encounter
    	if TG_OP = 'DELETE' then
    		select into _pk_identity fk_patient from clin.encounter where pk = OLD.fk_encounter limit 1;
    	else
    		select into _pk_identity fk_patient from clin.encounter where pk = NEW.fk_encounter limit 1;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_vacc_mod(): cannot determine identity PK on table <clin.vaccination>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "vacc_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_announce_waiting_list_generic_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "waiting_list_generic_mod_db:"';
    	return NULL;
    end;

## Function: clin.trf_announce_waiting_list_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_patient
    	if TG_OP = 'DELETE' then
    		_pk_identity := OLD.fk_patient;
    	else
    		_pk_identity := NEW.fk_patient;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'clin.trf_announce_waiting_list_mod(): cannot determine identity PK on table <clin.waiting_list>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "waiting_list_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: clin.trf_delete_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_pat_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_delete_intake_turns_other_components_into_substances()

### Returns: trigger

### Language: PLPGSQL

If a patient is stopped from a multi-component drug intake other components thereof must be turned into non-brand substance intakes.

    DECLARE
    	_pk_brand integer;
    	_component_count integer;
    	_pk_patient integer;
    BEGIN
    	-- did it at all relate to a drug (rather than substance) ?
    	if OLD.fk_drug_component is NULL then
    		return OLD;
    	end if;
    	-- which drug ?
    	select fk_brand into _pk_brand
    	from ref.lnk_substance2brand
    	where pk = OLD.fk_drug_component;
    	-- how many components therein ?
    	select count(1) into _component_count
    	from ref.lnk_substance2brand
    	where fk_brand = _pk_brand;
    	-- only one component ?
    	if _component_count = 1 then
    		return OLD;
    	end if;
    	-- which patient ?
    	select fk_patient into _pk_patient
    	from clin.encounter
    	where pk = OLD.fk_encounter;
    	-- relink all other intakes into substances
    	update clin.substance_intake set
    		fk_drug_component = null,
    		fk_substance = (
    			select fk_substance from ref.lnk_substance2brand where pk = fk_drug_component
    		),
    		preparation = (
    			select preparation from ref.branded_drug where pk = (
    				select fk_brand from ref.lnk_substance2brand where pk = fk_drug_component
    			)
    		)
    	where
    		fk_drug_component is not null
    			and
    		fk_drug_component in (
    			select pk from ref.lnk_substance2brand where fk_brand = _pk_brand
    		)
    			and
    		fk_encounter in (
    			select pk from clin.encounter where fk_patient = _pk_patient
    		)
    	;
    	return OLD;
    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_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_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_brand integer;
    	_pk_component integer;
    BEGIN
    	-- any drug at all ?
    	if NEW.fk_drug_component is NULL then
    		return NEW;
    	end if;
    	-- get the brand we are linking to
    	select fk_brand into _pk_brand
    	from ref.lnk_substance2brand
    	where pk = NEW.fk_drug_component;
    	-- how many components therein ?
    	select count(1) into _component_count
    	from ref.lnk_substance2brand
    	where fk_brand = _pk_brand;
    	-- 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_substance2brand where fk_brand = _pk_brand
    	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,
    			-- preparation,					-- drug components already have preps
    			aim,
    			discontinue_reason
    		) 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.preparation,
    			NEW.aim,
    			NEW.discontinue_reason
    		);
    	end loop;
    	return NEW;
    END;

## Function: clin.trf_insert_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
    	-- any drug at all ?
    	if NEW.fk_drug_component is NULL then
    		return NEW;
    	end if;
    	-- 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_insert_intake_prevent_duplicate_component_links]: drug component ref.lnk_substance2brand.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_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 is NULL then
    		return NEW;
    	end if;
    	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.item_inbox_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_insert()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_identity_from_encounter integer;
    	_identity_from_episode integer;
    begin
    	-- sometimes .fk_episode can actually be NULL (eg. clin.substance_intake)
    	-- in which case we do not need to run the sanity check
    	if NEW.fk_episode is NULL then
    		return NEW;
    	end if;
    	select fk_patient into _identity_from_encounter from clin.encounter where pk = NEW.fk_encounter;
    	select fk_patient into _identity_from_episode from clin.encounter where pk = (
    		select fk_encounter from clin.episode where pk = NEW.fk_episode
    	);
    	if _identity_from_encounter <> _identity_from_episode then
    		raise exception 'INSERT into %.%: Sanity check failed. Encounter % patient = %. Episode % patient = %.',
    			TG_TABLE_SCHEMA,
    			TG_TABLE_NAME,
    			NEW.fk_encounter,
    			_identity_from_encounter,
    			NEW.fk_episode,
    			_identity_from_episode
    		;
    		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_substance_episode()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_identity_from_encounter integer;
    	_identity_from_episode integer;
    begin
    	-- episode can only be NULL if intake is not approved of,
    	-- IOW, if clinician approves of intake she better know why
    	if NEW.intake_is_approved_of is True then
    		if NEW.fk_episode is NULL then
    			raise exception 'clin.trf_sanity_check_substance_episode(): substance intake is approved of but .fk_episode is NULL';
    			return NULL;
    		end if;
    	end if;
    	-- .fk_episode can be NULL (except in the above case)
    	if NEW.fk_episode 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_episode from clin.encounter where pk = (
    		select fk_encounter from clin.episode where pk = NEW.fk_episode
    	);
    	if _identity_from_encounter <> _identity_from_episode then
    		raise exception 'INSERT/UPDATE into %.%: Sanity check failed. Encounter % patient = %. Episode % patient = %.',
    			TG_TABLE_SCHEMA,
    			TG_TABLE_NAME,
    			NEW.fk_encounter,
    			_identity_from_encounter,
    			NEW.fk_episode,
    			_identity_from_episode
    		;
    		return NULL;
    	end if;
    	return NEW;
    end;

## Function: clin.trf_sanity_check_vaccine_has_indications()

### Returns: trigger

### Language: PLPGSQL

    DECLARE
    	_indication_link_pk integer;
    BEGIN
    	perform 1 from clin.lnk_vaccine2inds where fk_vaccine = NEW.pk limit 1;
    	if FOUND then
    		return NEW;
    	end if;
    	raise exception '[clin.vaccine]: INSERT/UPDATE failed: no indication linked to vaccine (clin.lnk_vaccine2inds.fk_vaccine <-(%)-> clin.vaccine.pk)', NEW.pk;
    	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_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;

## Function: clin.trf_update_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_brand integer;
    	_msg text;
    BEGIN
    	if NEW.fk_drug_component is not distinct from OLD.fk_drug_component then
    		return NEW;
    	end if;
    	select fk_patient into _pk_patient
    	from clin.encounter
    	where pk = NEW.fk_encounter;
    	-- check the OLD brand unless it is NULL
    	if OLD.fk_drug_component is not NULL then
    		-- get the brand we were linking to
    		select fk_brand into _pk_brand
    		from ref.lnk_substance2brand
    		where fk_substance = 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 fk_substance from ref.lnk_substance2brand where fk_brand = _pk_brand
    			)
    				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_substance2brand
    			where fk_brand = _pk_brand;
    			-- substance intake link count and number of components must match
    			if _component_count != _intake_count then
    				_msg := '[clin.trf_update_intake_must_link_all_drug_components]: re-linking brand must unlink all components of old brand [' || _pk_brand || '] '
    					|| '(component [' || OLD.fk_drug_component || ' -> ' || NEW.fk_drug_component || '])';
    				raise exception check_violation using message = _msg;
    			end if;
    		end if;
    	end if;
    	-- check the NEW brand unless it is NULL
    	if NEW.fk_drug_component is not NULL then
    		-- get the brand we were linking to
    		select fk_brand into _pk_brand
    		from ref.lnk_substance2brand
    		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 fk_substance from ref.lnk_substance2brand where fk_brand = _pk_brand
    			)
    				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_substance2brand
    			where fk_brand = _pk_brand;
    			-- substance intake link count and number of components must match
    			if _component_count != _intake_count then
    				_msg := '[clin.trf_update_intake_must_link_all_drug_components]: re-linking brand must link all components of new brand [' || _pk_brand || '] '
    					|| '(component [' || OLD.fk_drug_component || ' -> ' || NEW.fk_drug_component || '])';
    				raise exception check_violation using message = _msg;
    			end if;
    		end if;
    	end if;
    	return NEW;
    END;

## Function: clin.trf_update_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_brand integer;
    	_component_count integer;
    	_pk_patient integer;
    BEGIN
    	-- does it at all relate to a drug (rather than substance) ?
    	if NEW.fk_drug_component is null then
    		return NEW;
    	end if;
    	-- which drug ?
    	select fk_brand into _pk_brand
    	from ref.lnk_substance2brand
    	where pk = NEW.fk_drug_component;
    	-- how many components therein ?
    	select count(1) into _component_count
    	from ref.lnk_substance2brand
    	where fk_brand = _pk_brand;
    	-- 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 instakes ...
    	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
    	where
    		-- ... which belong to this drug ...
    		fk_drug_component in (
    			select pk from ref.lnk_substance2brand where fk_brand = _pk_brand
    		)
    			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
    		)
    	;
    	return NEW;
    END;

## Function: clin.trf_warn_on_duplicate_vaccinations()

### Returns: trigger

### Language: PLPGSQL

Sends a notification to the inbox of both current_user and clin.vaccination.fk_provider (if not NULL) in case a new or updated vaccination falls within 1 week of another vaccination with (even partially) overlapping indications.

    DECLARE
    	_NEW_pk_patient integer;
    	_NEW_vaccination record;
    	_NEW_vacc_label text;
    	_prev_vacc_loop_record record;
    	_prev_vaccination record;
    	_prev_vacc_label text;
    	_indication_collision integer;
    	msg text;
    	_pk_current_provider integer;
    BEGIN
    	-- find patient for NEW vaccination
    	select fk_patient into _NEW_pk_patient from clin.encounter where pk = NEW.fk_encounter;
    	-- load denormalized vaccination corresponding to NEW vaccination
    	select * into _NEW_vaccination from clin.v_pat_vaccinations where pk_vaccination = NEW.pk;
    	-- generate label for NEW vaccination
    	_NEW_vacc_label := to_char(_NEW_vaccination.date_given, 'YYYY-MM-DD')
    		|| ' (#' || _NEW_vaccination.pk_vaccination || '): '
    		|| _NEW_vaccination.vaccine
    		|| ' (' || array_to_string(_NEW_vaccination.l10n_indications, ', ') || ')';
    	-- loop over ...
    	for _prev_vacc_loop_record in
    		-- ... vaccinations ...
    		SELECT * FROM clin.vaccination cv
    		WHERE
    			-- ... of this patient ...
    			cv.fk_encounter in (select ce.pk from clin.encounter ce where ce.fk_patient = _NEW_pk_patient)
    				AND
    			-- ... within 7 days of the vaccination date ...
    			cv.clin_when BETWEEN (NEW.clin_when - '7 days'::interval) AND (NEW.clin_when + '7 days'::interval)
    				AND
    			-- ... not the vaccination we just INSERTed/UPDATEed
    			cv.pk != NEW.pk
    	loop
    		select * into _indication_collision from ((
    			select fk_indication from clin.lnk_vaccine2inds where fk_vaccine = NEW.fk_vaccine
    		) INTERSECT (
    			select fk_indication from clin.lnk_vaccine2inds where fk_vaccine = _prev_vacc_loop_record.fk_vaccine
    		)) as colliding_indications;
    		if FOUND then
    			-- retrieve denormalized data corresponding to that previous vaccination
    			select * into _prev_vaccination from clin.v_pat_vaccinations where pk_vaccination = _prev_vacc_loop_record.pk;
    			-- generate label for that previous vaccination
    			_prev_vacc_label := to_char(_prev_vaccination.date_given, 'YYYY-MM-DD')
    				|| ' (#' || _prev_vaccination.pk_vaccination || '): '
    				|| _prev_vaccination.vaccine
    				|| ' (' || array_to_string(_prev_vaccination.l10n_indications, ', ') || ')';
    			msg := _prev_vacc_label || E'
    ' || _NEW_vacc_label;
    			select pk into _pk_current_provider from dem.staff where db_user = session_user;
    			-- create inbox message for current user
    			insert into dem.message_inbox (
    				fk_staff,
    				fk_inbox_item_type,
    				comment,
    				data,
    				importance,
    				ufk_context,
    				fk_patient
    			) values (
    				_pk_current_provider,
    				(select pk_type from dem.v_inbox_item_type where type = 'review vaccs' and category = 'clinical'),
    				_('Two vaccinations with overlapping target conditions recorded within one week of each other !'),
    				msg,
    				1,
    				ARRAY[_NEW_vaccination.pk_vaccination,_prev_vaccination.pk_vaccination],
    				_NEW_pk_patient
    			);
    			-- create inbox message for vaccinating provider if known
    			if NEW.fk_provider is not NULL then
    				-- and not identical to session user
    				if NEW.fk_provider != _pk_current_provider then
    					insert into dem.message_inbox (
    						fk_staff,
    						fk_inbox_item_type,
    						comment,
    						data,
    						importance,
    						ufk_context,
    						fk_patient
    					) values (
    						NEW.fk_provider,
    						(select pk_type from dem.v_inbox_item_type where type = 'review vaccs' and category = 'clinical'),
    						_('Two vaccinations with overlapping target conditions recorded within one week of each other !'),
    						msg,
    						1,
    						ARRAY[_NEW_vaccination.pk_vaccination,_prev_vaccination.pk_vaccination],
    						_NEW_pk_patient
    					);
    				end if;
    			end if;
    		end if;
    	end loop;
    	return NEW;
    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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| code | text | UNIQUE NOT NULL
| kurzform | text | UNIQUE NOT NULL
| name | text | UNIQUE NOT NULL

Table de_de.beh_fall_typ Inherits audit_fields,

Tables referencing this one via Foreign Key Constraints:

- de_de.behandlungsfall

Index - Schema de_de

## Table: de_de.behandlungsfall

de_de.behandlungsfall Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
dem.identity.pk | fk_patient | integer | NOT NULL
de_de.beh_fall_typ.pk | fk_falltyp | integer | NOT NULL
| started | date | NOT NULL DEFAULT ('now'::text)::date
| must_pay_prax_geb | boolean | NOT NULL DEFAULT true

Tables referencing this one via Foreign Key Constraints:

- de_de.prax_geb_paid

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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
dem.identity.pk | fk_patient | integer | NOT NULL
| kk_name | character varying(28) | NOT NULL
| kk_nummer | character(7) | NOT NULL
| kvk_nummer | character(5) |
| mitgliedsnummer | character varying(12) | NOT NULL
| mitgliedsstatus | character varying(4) | NOT NULL
| zusatzstatus | character varying(3) |
| titel | character varying(15) |
| vorname | character varying(28) |
| namenszuatz | character varying(15) |
| familienname | character varying(28) | NOT NULL
| geburtsdatum | character(8) | NOT NULL
| strasse | character varying(28) |
| landescode | character varying(3) |
| plz | character varying(7) | NOT NULL
| ort | character varying(23) | NOT NULL
| gueltigkeit | character(4) |
| crc | character(1) | NOT NULL
| is_valid_address | boolean | DEFAULT true
| valid_since | timestamp with time zone | NOT NULL
| presented | timestamp with time zone[] | NOT NULL
| invalidated | timestamp with time zone | Kann durchaus vor Ende von "Gueltigkeit" liegen. Zeitpunkt des Austritts aus der Krankenkasse. Beim Setzen dieses Feldes muss auch die Zuzahlungsbefreiung auf NULL gesetzt werden.

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
clin.test_type.pk | id_test | integer | NOT NULL link to test in our practice

Table de_de.lab_test_gnr Inherits audit_fields,

Index - Schema de_de

## Table: de_de.payment_method

de_de.payment_method Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| description | text | UNIQUE NOT NULL

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
de_de.behandlungsfall.pk | fk_fall | integer | NOT NULL
| paid_amount | numeric | NOT NULL
| paid_when | date | NOT NULL DEFAULT ('now'::text)::date
de_de.payment_method.pk | paid_with | integer | NOT NULL

Table de_de.prax_geb_paid Inherits audit_fields,

Index - Schema de_de

## Table: de_de.zuzahlungsbefreiung

de_de.zuzahlungsbefreiung Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| id | serial | PRIMARY KEY
dem.identity.pk | id_patient | integer |
| medikamente | date |
| heilmittel | date |
| hilfsmittel | date |
| presented | timestamp with time zone | NOT NULL DEFAULT now()

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
dem.street.id | id_street | integer | UNIQUE#1 NOT NULL the street this address is at from whence the urb is to be found, it thus indirectly references dem.urb(id)
| aux_street | text | UNIQUE#1 additional street-level information which formatters would usually put on lines directly below the street line of an address, such as postal box directions in CA
| number | text | UNIQUE#1 NOT NULL number of the house
| subunit | text | UNIQUE#1 directions *below* the unit (eg.number) level, such as appartment number, room number, level, entrance or even verbal directions
| addendum | text | UNIQUE#1 any additional information that did not fit anywhere else
| lat_lon | point | the exact location of this address in latitude-longtitude

Table dem.address Inherits audit_fields,

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 | serial | PRIMARY KEY
| name | text | UNIQUE NOT NULL

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
--- | --- | --- | ---
| id | serial | PRIMARY KEY
| code | character(2) | UNIQUE NOT NULL international two character country code as per ISO 3166-1
| name | text | UNIQUE NOT NULL
| deprecated | date | date when this country ceased officially to exist (if applicable)

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.state

Index - Schema dem

## Table: dem.enum_comm_types

dem.enum_comm_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| description | text | UNIQUE NOT NULL

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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| name | text | UNIQUE#1
| issuer | text | UNIQUE#1 the authority/system issuing the number

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| tag | text | UNIQUE NOT NULL
| label | text | UNIQUE NOT NULL
| sort_weight | integer | NOT NULL
| comment | text | NOT NULL

Table dem.gender_label Inherits audit_fields,

dem.gender_label Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| deleted | boolean | NOT NULL DEFAULT false whether this identity is considered deleted
| pupic | character(24) | Portable Unique Person Identification Code as per gnumed white papers
dem.gender_label.tag | gender | text | the gender code
| karyotype | text |
| dob | timestamp with time zone | date/time of birth
dem.marital_status.pk | fk_marital_status | integer |
| cob | character(2) | country of birth as per date of birth, coded as 2 character ISO code
| deceased | timestamp with time zone | date when a person has died
| title | text | Yes, a title is an attribute of an identity, not of a name ! Also, there are some incredible rants of titles.
| tob | time without time zone |
| emergency_contact | text | Free text emergency contact information.
dem.identity.pk | fk_emergency_contact | integer | Link to another dem.identity to be used as emergency contact.
| comment | text | A free-text comment on this identity.
dem.staff.pk | fk_primary_provider | integer | The doctor within this praxis primarily responsible for this patient.

Table dem.identity Inherits audit_fields,

dem.identity Constraints
Name | Constraint
--- | ---
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

- clin.encounter

- clin.incoming_data_unmatched

- clin.lab_request

- clin.lnk_pat2vaccination_course

- clin.test_org

- clin.waiting_list

- de_de.behandlungsfall

- 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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.identity.pk | fk_identity | integer | UNIQUE#1 NOT NULL
ref.tag_image.pk | fk_tag | integer | UNIQUE#1 NOT NULL
| comment | text |

Table dem.identity_tag Inherits audit_fields,

dem.identity_tag Constraints
Name | Constraint
--- | ---
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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | UNIQUE NOT NULL "clinical" "admin" "personal" ...
| is_user | boolean | NOT NULL DEFAULT true whether this category was added locally, as to be left alone by database upgrades

Table dem.inbox_item_category Inherits audit_fields,

dem.inbox_item_category Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.inbox_item_category.pk | fk_inbox_item_category | integer | NOT NULL The category of this item type.
| description | text | UNIQUE NOT NULL the various types of inbox items
| is_user | boolean | NOT NULL DEFAULT true whether this type was added locally, as to be left alone by database upgrades

Table dem.inbox_item_type Inherits audit_fields,

dem.inbox_item_type Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
dem.identity.pk | fk_identity | integer | UNIQUE#1 NOT NULL
dem.address.id | fk_address | integer |
| url | text | UNIQUE#1 NOT NULL
dem.enum_comm_types.pk | fk_type | integer | NOT NULL
| is_confidential | boolean | NOT NULL DEFAULT false

dem.lnk_identity2comm Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
dem.identity.pk | id_identity | integer | UNIQUE#1 NOT NULL
| external_id | text | UNIQUE#1 NOT NULL textual representation of external ID which may be Social Security Number, patient ID of another EMR system, you-name-it
dem.enum_ext_id_types.pk | fk_origin | integer | UNIQUE#1 NOT NULL originating system
| comment | text |

Table dem.lnk_identity2ext_id Inherits audit_fields,

Index - Schema dem

## Table: dem.lnk_job2person

linking (possibly several) jobs to a person

dem.lnk_job2person Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.identity.pk | fk_identity | integer | UNIQUE#1 NOT NULL
dem.occupation.id | fk_occupation | integer | UNIQUE#1 NOT NULL
| activities | text | describes activities the person is usually carrying out when working at this job

Table dem.lnk_job2person Inherits audit_fields,

Index - Schema dem

## Table: dem.lnk_org_unit2comm

Comm channels per org unit.

dem.lnk_org_unit2comm Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.org_unit.pk | fk_org_unit | integer | UNIQUE#1 NOT NULL
| url | text | UNIQUE#1
dem.enum_comm_types.pk | fk_type | integer | UNIQUE#1 NOT NULL
| is_confidential | boolean | NOT NULL DEFAULT false

Table dem.lnk_org_unit2comm Inherits audit_fields,

dem.lnk_org_unit2comm Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.org.pk dem.org_unit.pk | fk_org_unit | integer | UNIQUE#1 NOT NULL
| external_id | text | UNIQUE#1
dem.enum_ext_id_types.pk | fk_type | integer | UNIQUE#1 NOT NULL
| comment | text |

Table dem.lnk_org_unit2ext_id Inherits audit_fields,

dem.lnk_org_unit2ext_id Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| id_identity | integer |
| id_address | integer |
| id_type | integer |

    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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
dem.identity.pk | id_identity | integer | NOT NULL primary identity to whom the relationship applies
dem.identity.pk | id_relative | integer | NOT NULL referred-to identity of this relationship (e.g. "child" if id_identity points to the father and id_relation_type points to "parent")
dem.relation_types.id | id_relation_type | integer | NOT NULL
| started | date | date when this relationship began
| ended | date | date when this relationship ended, biological relationships do not end !

Table dem.lnk_person2relative Inherits audit_fields,

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 | serial | PRIMARY KEY
dem.identity.pk | id_identity | integer | UNIQUE#1 identity to which the address belongs
dem.address.id | id_address | integer | UNIQUE#1 UNIQUE#2 address belonging to this identity (the branch of the organisation)
dem.address_type.id | id_type | integer | DEFAULT 1 type of this address (like home, work, parents, holidays ...)
| address_source | text |
| id_org | integer | UNIQUE#2

Index - Schema dem

## Table: dem.marital_status

dem.marital_status Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| name | text | UNIQUE NOT NULL

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.staff.pk | fk_staff | integer | the member of staff this message is addressed to
dem.inbox_item_type.pk | fk_inbox_item_type | integer | NOT NULL the item (message) type
| comment | text | a free-text comment, may be NULL but not empty
| data | text | arbitrary data an application might wish to attach to the message, like a cookie, basically
| importance | smallint | NOT NULL the relative importance of this message: -1: lower than most things already in the inbox ("low") 0: same as most things ("standard") 1: higher than most things already there ("high")
dem.identity.pk | fk_patient | integer |
| ufk_context | integer[] | a nullable array of Unchecked Foreign Keys, it is up to the application to know what this points to, it will have to make sense within the context of the combination of staff ID, item type, and comment

Table dem.message_inbox Inherits audit_fields,

dem.message_inbox Constraints
Name | Constraint
--- | ---
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)) OR (importance = 0)) OR (importance = 1)))

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
--- | --- | --- | ---
| id | serial | PRIMARY KEY
| name | text | UNIQUE NOT NULL
| gender | character(1) |

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
--- | --- | --- | ---
| id | serial | PRIMARY KEY
dem.identity.pk | id_identity | integer | UNIQUE#1 NOT NULL
| active | boolean | DEFAULT true true if the name is still in use
| lastnames | text | UNIQUE#1 NOT NULL all last names of an identity in legal order, IOW "major" name, "group identifier", eg. family, village, tribe, ...
| firstnames | text | UNIQUE#1 NOT NULL all first names of an identity in legal order, IOW "minor" name, identifier of this identity within the group defined by <lastnames>
| preferred | text | preferred first name, the name a person is usually called (nickname, warrior name)
| comment | text | a comment regarding this name, useful in things like "this was the name before marriage" etc

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
| name | text | NOT NULL

Table dem.occupation Inherits audit_fields,

dem.occupation Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | High-level, conceptual description (= name) of organization, such as "University of Manchester".
dem.org_category.pk | fk_category | integer |
ref.data_source.pk | fk_data_source | integer | Source of the organization data.

Table dem.org Inherits audit_fields,

dem.org Constraints
Name | Constraint
--- | ---
org_sane_description | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- dem.lnk_org_unit2ext_id

- dem.org_unit

Index - Schema dem

## Table: dem.org_category

dem.org_category Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| description | text | NOT NULL

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | UNIQUE#1 Description (= name) of branch of organization, such as "Elms Street office of Jim Busser Praxis".
dem.org.pk | fk_org | integer | UNIQUE#1 NOT NULL
dem.address.id | fk_address | integer |
dem.org_category.pk | fk_category | integer |

Table dem.org_unit Inherits audit_fields,

dem.org_unit Constraints
Name | Constraint
--- | ---
org_unit_sane_description | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- clin.test_org

- dem.lnk_org_unit2comm

- dem.lnk_org_unit2ext_id

Index - Schema dem

## Table: dem.relation_types

types of biological/social relationships between identities

dem.relation_types Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
dem.relation_types.id | inverse | integer |
| biological | boolean | NOT NULL true if relationship is biological (proven or reasonable assumption), else false
| biol_verified | boolean | DEFAULT false ONLY true if there is genetic proof for this relationship
| description | text | plain text description of relationship

Table dem.relation_types Inherits audit_fields,

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
dem.identity.pk | fk_identity | integer | UNIQUE#2 NOT NULL
dem.staff_role.pk | fk_role | integer | UNIQUE#2 UNIQUE#1 NOT NULL
| db_user | name | UNIQUE UNIQUE#1 NOT NULL DEFAULT "current_user"()
| short_alias | text | UNIQUE NOT NULL a short signature unique to this staff member to be used in the GUI, actually this is somewhat redundant with ext_person_id...
| comment | text |
| is_active | boolean | NOT NULL DEFAULT true

Table dem.staff Inherits audit_fields,

Tables referencing this one via Foreign Key Constraints:

- bill.bill_item

- blobs.doc_obj

- clin.incoming_data_unmatched

- clin.keyword_expansion

- clin.review_root

- clin.reviewed_test_results

- clin.test_result

- clin.vaccination

- dem.identity

- dem.message_inbox

Index - Schema dem

## Table: dem.staff_role

work roles a staff member can have

dem.staff_role Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| name | text | UNIQUE NOT NULL
| comment | text |

Table dem.staff_role Inherits audit_fields,

Tables referencing this one via Foreign Key Constraints:

- dem.staff

Index - Schema dem

## Table: dem.state

state codes (country specific); Richard agreed we should require pre-existence, allow user to mail details for adding a state to developers

dem.state Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
| code | text | UNIQUE#1 NOT NULL state code
dem.country.code | country | character(2) | UNIQUE#1 NOT NULL 2 character ISO 3166-1 country code
| name | text | NOT NULL

Table dem.state Inherits audit_fields,

dem.state Constraints
Name | Constraint
--- | ---
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.street

street names, specific for distinct "urbs"

dem.street Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
dem.urb.id | id_urb | integer | UNIQUE#1 NOT NULL reference to information postcode, city, country and state
| name | text | UNIQUE#1 NOT NULL name of this street
| postcode | text | UNIQUE#1 postcode for systems (such as UK Royal Mail) which specify the street
| suburb | text | the suburb this street is in (if any)
| lat_lon | point | the approximate location of the street, as lat/long co-ordinates

Table dem.street Inherits audit_fields,

dem.street Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| id | serial | PRIMARY KEY
dem.state.id | id_state | integer | UNIQUE#1 NOT NULL reference to information about country and state
| postcode | text | UNIQUE#1 NOT NULL default postcode for urb.name, useful for all the smaller urbs that only have one postcode, also useful as a default when adding new streets to an urb
| lat_lon | point | the location of the urb, as lat/long co-ordinates. Ideally this would be NOT NULL
| name | text | UNIQUE#1 NOT NULL the name of the city/town/dwelling

Table dem.urb Inherits audit_fields,

dem.urb Constraints
Name | Constraint
--- | ---
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 id_state idx_urb_names name idx_urb_zips postcode

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
--- | --- | --- | ---
| pk_address | integer |
| street | text |
| postcode | text |
| notes_street | text |
| number | text |
| subunit | text |
| notes_subunit | text |
| lat_lon_address | point |
| postcode_street | text |
| lat_lon_street | point |
| suburb | text |
| urb | text |
| postcode_urb | text |
| lat_lon_urb | point |
| code_state | text |
| state | text |
| l10n_state | text |
| code_country | character(2) |
| country | text |
| l10n_country | text |
| country_deprecated | date |
| pk_street | integer |
| pk_urb | integer |
| pk_state | integer |
| xmin_address | xid |

    SELECT adr.id AS pk_address
    , str.name AS street
    , COALESCE
    (str.postcode
         , u.postcode
    ) AS postcode
    , adr.aux_street AS notes_street
    , adr.number
    , adr.subunit
    , adr.addendum AS notes_subunit
    , adr.lat_lon AS lat_lon_address
    , str.postcode AS postcode_street
    , str.lat_lon AS lat_lon_street
    , str.suburb
    , u.name AS urb
    , u.postcode AS postcode_urb
    , u.lat_lon AS lat_lon_urb
    , dst.code AS code_state
    , dst.name AS state
    , _
    (dst.name) AS l10n_state
    , dst.country AS code_country
    , c.name AS country
    , _
    (c.name) AS l10n_country
    , c.deprecated AS country_deprecated
    , adr.id_street AS pk_street
    , u.id AS pk_urb
    , dst.id AS pk_state
    , adr.xmin AS xmin_address
    FROM (
         (
               (
                     (dem.address adr
                   LEFT JOIN dem.street str
                          ON (
                                 (adr.id_street = str.id)
                           )
                     )
             LEFT JOIN dem.urb u
                    ON (
                           (str.id_urb = u.id)
                     )
               )
       LEFT JOIN dem.state dst
              ON (
                     (u.id_state = dst.id)
               )
         )
    LEFT JOIN dem.country c
        ON (
               (c.code = dst.country)
         )
    );

Index - Schema dem

## View: dem.v_basic_address

dem.v_basic_address Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| id | integer |
| country_code | character(2) |
| state_code | text |
| state | text |
| country | text |
| postcode | text |
| urb | text |
| number | text |
| street | text |
| addendum | text |
| lat_lon | point |

    SELECT adr.id
    , s.country AS country_code
    , s.code AS state_code
    , s.name AS state
    , c.name AS country
    , COALESCE
    (str.postcode
         , urb.postcode
    ) AS postcode
    , urb.name AS urb
    , adr.number
    , str.name AS street
    , adr.addendum
    , COALESCE
    (adr.lat_lon
         , str.lat_lon
         , urb.lat_lon
    ) AS lat_lon
    FROM dem.address adr
    , dem.state s
    , dem.country c
    , dem.urb
    , dem.street str
    WHERE (
         (
               (
                     (s.country = c.code)
                   AND (adr.id_street = str.id)
               )
             AND (str.id_urb = urb.id)
         )
       AND (urb.id_state = s.id)
    );

Index - Schema dem

## View: dem.v_basic_person

This view denormalizes non-deleted persons with their active name.

dem.v_basic_person Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_identity | integer |
| title | text |
| firstnames | text |
| preferred | text |
| lastnames | text |
| gender | text |
| l10n_gender | text |
| dob_only | timestamp with time zone |
| dob | timestamp with time zone |
| tob | time without time zone |
| deceased | timestamp with time zone |
| cob | character(2) |
| karyotype | text |
| pupic | character(24) |
| marital_status | text |
| l10n_marital_status | text |
| emergency_contact | text |
| comment | text |
| pk_marital_status | integer |
| pk_active_name | integer |
| pk_emergency_contact | integer |
| pk_primary_provider | integer |
| xmin_identity | xid |

    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
    , i.cob
    , i.karyotype
    , i.pupic
    , 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.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
    FROM dem.identity i
    , dem.names n
    WHERE (
         (
               (i.deleted IS FALSE)
             AND (n.active IS TRUE)
         )
       AND (n.id_identity = i.pk)
    );

Index - Schema dem

## View: dem.v_external_ids4identity

dem.v_external_ids4identity Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_identity | integer |
| pk_id | integer |
| name | text |
| value | text |
| issuer | text |
| comment | text |
| pk_type | integer |

    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_gender_labels

dem.v_gender_labels Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| tag | text |
| l10n_tag | text |
| label | text |
| l10n_label | text |
| comment | text |
| sort_weight | integer |
| pk_gender_label | integer |

    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
--- | --- | --- | ---
| pk_identity | integer |
| description | text |
| l10n_description | text |
| comment | text |
| filename | text |
| image_size | integer |
| pk_identity_tag | integer |
| pk_tag_image | integer |
| xmin_identity_tag | xid |

    SELECT dit.fk_identity AS pk_identity
    , rti.description
    , _
    (rti.description) AS l10n_description
    , dit.comment
    , rti.filename
    , octet_length
    (COALESCE
         (rti.image
               ,''::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
--- | --- | --- | ---
| type | text |
| l10n_type | text |
| category | text |
| l10n_category | text |
| is_user_type | boolean |
| is_user_category | boolean |
| pk_type | integer |
| pk_category | integer |

    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
--- | --- | --- | ---
| received_when | timestamp with time zone |
| modified_by | text |
| provider | text |
| importance | integer |
| category | text |
| l10n_category | text |
| type | text |
| l10n_type | text |
| comment | text |
| pk_context | integer[] |
| data | text |
| pk_inbox_message | integer |
| pk_staff | integer |
| pk_category | integer |
| pk_type | integer |
| pk_patient | integer |
| is_virtual | boolean |
| xmin_message_inbox | integer |

    (
         (
          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
               , 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)
           UNIONSELECT now
               () AS received_when
               ,'<system>' AS modified_by
               , (
                SELECT staff.short_alias
                  FROM dem.staff
                 WHERE (staff.pk = vo4dnd.pk_intended_reviewer)
               ) AS provider
               , 0 AS importance
               ,'clinical' AS category
               , _
               ('clinical'::text) AS l10n_category
               ,'review docs' AS type
               , _
               ('review docs'::text) AS l10n_type
               , (
                SELECT (
                           (
                                 (
                                       (
                                             (_
                                                   ('unreviewed documents for patient'::text) || ' ['::text
                                             ) || dn.lastnames
                                       ) ||
                                    ', '::text
                                 ) || dn.firstnames
                           ) || ']'::text
                     )
                  FROM dem.names dn
                 WHERE (
                           (dn.id_identity = vo4dnd.pk_patient)
                         AND (dn.active IS TRUE)
                     )
               ) AS comment
               , NULL::integer[] AS pk_context
               , NULL::text AS data
               , NULL::integer AS pk_inbox_message
               , vo4dnd.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 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
               , vo4dnd.pk_patient
               , true AS is_virtual
               , NULL::integer AS xmin_message_inbox
            FROM blobs.v_obj4doc_no_data vo4dnd
           WHERE (vo4dnd.reviewed IS FALSE)
         )
     UNIONSELECT 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' AS category
         , _
         ('clinical'::text) AS l10n_category
         ,'review results' 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
    , 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)
               )
         )
    )
    )
    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
    ,      1 AS importance
    ,     'clinical' AS category
    ,      _
    (     'clinical'::text) AS l10n_category
    ,     'review results' 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
    ,            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)
    )
    )
    )           ;

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
--- | --- | --- | ---
| pk_org_unit | integer |
| comm_type | text |
| l10n_comm_type | text |
| url | text |
| is_confidential | boolean |
| pk_lnk_org_unit2comm | integer |
| pk_type | integer |
| xmin_lnk_org_unit2comm | xid |

    SELECT lo2c.fk_org_unit AS pk_org_unit
    , ect.description AS comm_type
    , _
    (ect.description) AS l10n_comm_type
    , lo2c.url
    , lo2c.is_confidential
    , lo2c.pk AS pk_lnk_org_unit2comm
    , lo2c.fk_type AS pk_type
    , lo2c.xmin AS xmin_lnk_org_unit2comm
    FROM (dem.lnk_org_unit2comm lo2c
      JOIN dem.enum_comm_types ect
        ON (
               (lo2c.fk_type = ect.pk)
         )
    );

Index - Schema dem

## View: dem.v_org_units

dem.v_org_units Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_org_unit | integer |
| organization | text |
| unit | text |
| organization_category | text |
| l10n_organization_category | text |
| unit_category | text |
| l10n_unit_category | text |
| pk_org | integer |
| pk_category_org | integer |
| pk_category_unit | integer |
| pk_address | integer |
| xmin_org_unit | xid |

    SELECT dou.pk AS pk_org_unit
    , dvo.organization
    , dou.description AS unit
    , dvo.category AS organization_category
    , _
    (dvo.category) AS l10n_organization_category
    , doc.description AS unit_category
    , _
    (doc.description) AS l10n_unit_category
    , dvo.pk_org
    , dvo.pk_category_org
    , dou.fk_category AS pk_category_unit
    , dou.fk_address AS pk_address
    , dou.xmin AS xmin_org_unit
    FROM (
         (dem.org_unit dou
       LEFT JOIN dem.v_orgs dvo
              ON (
                     (dou.fk_org = dvo.pk_org)
               )
         )
    LEFT JOIN dem.org_category doc
        ON (
               (dou.fk_category = doc.pk)
         )
    );

Index - Schema dem

## View: dem.v_orgs

dem.v_orgs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_org | integer |
| organization | text |
| category | text |
| l10n_category | text |
| pk_category_org | integer |
| xmin_org | xid |

    SELECT org.pk AS pk_org
    , org.description AS organization
    , doc.description AS category
    , _
    (doc.description) AS l10n_category
    , org.fk_category AS pk_category_org
    , org.xmin AS xmin_org
    FROM (dem.org org
    LEFT JOIN dem.org_category doc
        ON (
               (org.fk_category = doc.pk)
         )
    );

Index - Schema dem

## View: dem.v_pat_addresses

denormalized addresses per patient

dem.v_pat_addresses Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_identity | integer |
| pk_address | integer |
| address_type | text |
| l10n_address_type | text |
| title | text |
| firstnames | text |
| lastnames | text |
| dob | timestamp with time zone |
| cob | character(2) |
| gender | text |
| l10n_gender | text |
| preferred | text |
| street | text |
| postcode | text |
| notes_street | text |
| number | text |
| subunit | text |
| notes_subunit | text |
| lat_lon_address | point |
| postcode_street | text |
| lat_lon_street | point |
| suburb | text |
| urb | text |
| postcode_urb | text |
| lat_lon_urb | point |
| code_state | text |
| state | text |
| l10n_state | text |
| code_country | character(2) |
| country | text |
| l10n_country | text |
| country_deprecated | date |
| pk_street | integer |
| pk_urb | integer |
| pk_state | integer |
| pk_lnk_person_org_address | integer |
| pk_address_type | integer |
| xmin_lnk_person_org_address | xid |

    SELECT vbp.pk_identity
    , va.pk_address
    , at.name AS address_type
    , _
    (at.name) AS l10n_address_type
    , vbp.title
    , vbp.firstnames
    , vbp.lastnames
    , vbp.dob
    , vbp.cob
    , vbp.gender
    , vbp.l10n_gender
    , vbp.preferred
    , va.street
    , va.postcode
    , va.notes_street
    , va.number
    , va.subunit
    , va.notes_subunit
    , va.lat_lon_address
    , va.postcode_street
    , va.lat_lon_street
    , va.suburb
    , va.urb
    , va.postcode_urb
    , va.lat_lon_urb
    , va.code_state
    , va.state
    , va.l10n_state
    , va.code_country
    , va.country
    , va.l10n_country
    , va.country_deprecated
    , va.pk_street
    , va.pk_urb
    , va.pk_state
    , lpoa.id AS pk_lnk_person_org_address
    , lpoa.id_type AS pk_address_type
    , lpoa.xmin AS xmin_lnk_person_org_address
    FROM dem.v_address va
    , dem.lnk_person_org_address lpoa
    , dem.v_basic_person vbp
    , dem.address_type at
    WHERE (
         (
               (lpoa.id_identity = vbp.pk_identity)
             AND (lpoa.id_address = va.pk_address)
         )
       AND (lpoa.id_type = at.id)
    );

Index - Schema dem

## View: dem.v_person_comms

denormalizes persons to communications channels

dem.v_person_comms Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_identity | integer |
| comm_type | text |
| l10n_comm_type | text |
| url | text |
| is_confidential | boolean |
| pk_lnk_identity2comm | integer |
| pk_address | integer |
| pk_type | integer |
| xmin_lnk_identity2comm | xid |

    SELECT li2c.fk_identity AS pk_identity
    , ect.description AS comm_type
    , _
    (ect.description) AS l10n_comm_type
    , li2c.url
    , li2c.is_confidential
    , 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
--- | --- | --- | ---
| pk_identity | integer |
| occupation | text |
| l10n_occupation | text |
| activities | text |
| modified_when | timestamp with time zone |
| pk_occupation | integer |
| pk_lnk_job2person | integer |
| xmin_lnk_job2person | xid |

    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
--- | --- | --- | ---
| pk_identity | integer |
| active_name | boolean |
| title | text |
| firstnames | text |
| lastnames | text |
| preferred | text |
| comment | text |
| gender | text |
| dob | timestamp with time zone |
| tob | time without time zone |
| dod | timestamp with time zone |
| identity_deleted | boolean |
| deceased | boolean |
| pk_name | integer |
| xmin_name | xid |

    SELECT dn.id_identity AS pk_identity
    , dn.active AS active_name
    , di.title
    , dn.firstnames
    , dn.lastnames
    , dn.preferred
    , dn.comment
    , di.gender
    , di.dob
    , di.tob
    , di.deceased AS dod
    , di.deleted AS identity_deleted
    , (di.deceased IS NOT NULL) AS deceased
    , dn.id AS pk_name
    , dn.xmin AS xmin_name
    FROM dem.names dn
    , dem.identity di
    WHERE (di.pk = dn.id_identity);

Index - Schema dem

## View: dem.v_staff

Denormalized staff data.

dem.v_staff Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_identity | integer |
| pk_staff | integer |
| title | text |
| firstnames | text |
| lastnames | text |
| short_alias | text |
| role | text |
| l10n_role | text |
| dob | timestamp with time zone |
| gender | text |
| db_user | name |
| comment | text |
| is_active | boolean |
| can_login | boolean |
| xmin_staff | xid |
| pk_role | integer |

    SELECT vbp.pk_identity
    , s.pk AS pk_staff
    , vbp.title
    , vbp.firstnames
    , vbp.lastnames
    , s.short_alias
    , sr.name AS role
    , _
    (sr.name) AS l10n_role
    , vbp.dob
    , vbp.gender
    , s.db_user
    , s.comment
    , s.is_active
    , (
    SELECT (
               (
                SELECT (EXISTS
                           (
                            SELECT 1
                              FROM pg_group
                             WHERE (
                                       (
                                             (
                                              SELECT pg_user.usesysid
                                                FROM pg_user
                                               WHERE (pg_user.usename = s.db_user)
                                             ) = ANY
                                             (pg_group.grolist)
                                       )
                                     AND (pg_group.groname = current_database
                                             ()
                                       )
                                 )
                           )
                     )
               )
             AND (
                SELECT (EXISTS
                           (
                            SELECT 1
                              FROM pg_group
                             WHERE (
                                       (
                                             (
                                              SELECT pg_user.usesysid
                                                FROM pg_user
                                               WHERE (pg_user.usename = s.db_user)
                                             ) = ANY
                                             (pg_group.grolist)
                                       )
                                     AND (pg_group.groname = 'gm-logins'::name)
                                 )
                           )
                     )
               )
         )
    ) AS can_login
    , s.xmin AS xmin_staff
    , s.fk_role AS pk_role
    FROM (
         (dem.staff s
            JOIN dem.staff_role sr
              ON (
                     (s.fk_role = sr.pk)
               )
         )
      JOIN dem.v_basic_person vbp
        ON (
               (s.fk_identity = vbp.pk_identity)
         )
    );

Index - Schema dem

## View: dem.v_state

denormalizes state information

dem.v_state Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_state | integer |
| code_state | text |
| state | text |
| l10n_state | text |
| code_country | character(2) |
| country | text |
| l10n_country | text |
| country_deprecated | date |
| xmin_state | xid |

    SELECT s.id AS pk_state
    , s.code AS code_state
    , s.name AS state
    , _
    (s.name) AS l10n_state
    , s.country AS code_country
    , c.name AS country
    , _
    (c.name) AS l10n_country
    , c.deprecated AS country_deprecated
    , s.xmin AS xmin_state
    FROM (dem.state s
    LEFT JOIN dem.country c
        ON (
               (s.country = c.code)
         )
    );

Index - Schema dem

## View: dem.v_street

denormalizes street data

dem.v_street Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_street | integer |
| street | text |
| postcode | text |
| postcode_street | text |
| lat_lon_street | point |
| suburb | text |
| urb | text |
| postcode_urb | text |
| lat_lon_urb | point |
| code_state | text |
| state | text |
| l10n_state | text |
| code_country | character(2) |
| country | text |
| l10n_country | text |
| country_deprecated | date |
| pk_urb | integer |
| pk_state | integer |
| xmin_street | xid |

    SELECT st.id AS pk_street
    , st.name AS street
    , COALESCE
    (st.postcode
         , vu.postcode_urb
    ) AS postcode
    , st.postcode AS postcode_street
    , st.lat_lon AS lat_lon_street
    , st.suburb
    , vu.urb
    , vu.postcode_urb
    , vu.lat_lon_urb
    , vu.code_state
    , vu.state
    , vu.l10n_state
    , vu.code_country
    , vu.country
    , vu.l10n_country
    , vu.country_deprecated
    , st.id_urb AS pk_urb
    , vu.pk_state
    , st.xmin AS xmin_street
    FROM (dem.street st
    LEFT JOIN dem.v_urb vu
        ON (
               (st.id_urb = 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
--- | --- | --- | ---
| postcode | text |
| name | text |
| state | text |
| code_state | text |
| country | text |
| l10n_country | text |
| code_country | character(2) |

    SELECT urb.postcode
    , urb.name
    , stt.name AS state
    , stt.code AS code_state
    , c.name AS country
    , _
    (c.name) AS l10n_country
    , stt.country AS code_country
    FROM dem.urb
    , dem.state stt
    , dem.country c
    WHERE (
         (
               (
                     (urb.postcode IS NOT NULL)
                   AND (NOT
                           (EXISTS
                                 (
                                  SELECT 1
                                    FROM dem.v_zip2street vz2str
                                       , dem.urb
                                   WHERE (
                                             (vz2str.postcode = urb.postcode)
                                           AND (vz2str.urb = urb.name)
                                       )
                                 )
                           )
                     )
               )
             AND (urb.id_state = stt.id)
         )
       AND (stt.country = c.code)
    );

Index - Schema dem

## View: dem.v_urb

denormalizes urb data

dem.v_urb Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_urb | integer |
| urb | text |
| postcode_urb | text |
| lat_lon_urb | point |
| code_state | text |
| state | text |
| l10n_state | text |
| code_country | character(2) |
| country | text |
| l10n_country | text |
| country_deprecated | date |
| pk_state | integer |
| xmin_urb | xid |

    SELECT u.id AS pk_urb
    , u.name AS urb
    , u.postcode AS postcode_urb
    , u.lat_lon AS lat_lon_urb
    , vs.code_state
    , vs.state
    , vs.l10n_state
    , vs.code_country
    , vs.country
    , vs.l10n_country
    , vs.country_deprecated
    , u.id_state AS pk_state
    , u.xmin AS xmin_urb
    FROM (dem.urb u
    LEFT JOIN dem.v_state vs
        ON (
               (vs.pk_state = u.id_state)
         )
    );

Index - Schema dem

## View: dem.v_zip2data

aggregates nearly all known data per zip code

dem.v_zip2data Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| zip | text |
| street | text |
| suburb | text |
| urb | text |
| state | text |
| code_state | text |
| country | text |
| l10n_country | text |
| code_country | character(2) |

    SELECT vz2s.postcode AS zip
    , vz2s.street
    , vz2s.suburb
    , vz2s.urb
    , vz2s.state
    , vz2s.code_state
    , vz2s.country
    , vz2s.l10n_country
    , vz2s.code_country
    FROM dem.v_zip2street vz2s
    UNIONSELECT vuzu.postcode AS zip
    , NULL::unknown AS street
    , NULL::unknown AS suburb
    , vuzu.name AS urb
    , vuzu.state
    , vuzu.code_state
    , vuzu.country
    , vuzu.l10n_country
    , vuzu.code_country
    FROM dem.v_uniq_zipped_urbs 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
--- | --- | --- | ---
| postcode | text |
| street | text |
| suburb | text |
| state | text |
| code_state | text |
| urb | text |
| country | text |
| l10n_country | text |
| code_country | character(2) |

    SELECT COALESCE
    (str.postcode
         , urb.postcode
    ) AS postcode
    , str.name AS street
    , str.suburb
    , stt.name AS state
    , stt.code AS code_state
    , urb.name AS urb
    , c.name AS country
    , _
    (c.name) AS l10n_country
    , stt.country AS code_country
    FROM dem.street str
    , dem.urb
    , dem.state stt
    , dem.country c
    WHERE (
         (
               (
                     (str.postcode IS NOT NULL)
                   AND (str.id_urb = urb.id)
               )
             AND (urb.id_state = stt.id)
         )
       AND (stt.country = 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
--- | --- | --- | ---
| postcode | text |
| urb | text |
| state | text |
| code_state | text |
| country | text |
| code_country | character(2) |

    SELECT urb.postcode
    , urb.name AS urb
    , stt.name AS state
    , stt.code AS code_state
    , _
    (c.name) AS country
    , stt.country AS code_country
    FROM dem.urb
    , dem.state stt
    , dem.country c
    WHERE (
         (
               (urb.postcode IS NOT NULL)
             AND (urb.id_state = stt.id)
         )
       AND (stt.country = 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, state code, urb (location), postcode, street, number, subunit (can be NULL)

    DECLARE
    	_code_country alias for $1;
    	_code_state 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_state || _urb || _postcode || _street || _number) is NULL then
    		msg := '[dem.address_exists]: insufficient or invalid address definition: '
    			|| 'country code <' || coalesce(_code_country, 'NULL') || '>, '
    			|| 'state code <' || coalesce(_code_state, '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_state = trim(_code_state)
    				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_state = trim(_code_state)
    				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.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), state code, country code, subunit (can be NULL) If the country or the state 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;
    	_state_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,
    		_state_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 state and/or country do not exist)
    	select into _street_id dem.create_street(_street, _postcode, _urb, _state_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, the postcode of the urb, the name of the state and the name of the country. If the country or the state does not exists in the tables, the function fails. At first, the urb is tried to be retrieved according to the supplied information. If the fields do not match exactly an existing row, a new urb is created and returned.

    DECLARE
    	_urb ALIAS FOR $1;
    	_urb_postcode ALIAS FOR $2;
    	_state_code ALIAS FOR $3;
    	_country_code ALIAS FOR $4;
     	_state_id integer;
    	_urb_id integer;
    	msg text;
    BEGIN
     	-- get state
     	SELECT INTO _state_id s.id from dem.state s WHERE s.code = _state_code and s.country = _country_code;
     	IF NOT FOUND THEN
    		msg := 'Cannot set address [' || coalesce(_country_code, 'country_code:NULL') || ', ' || coalesce(_state_code, 'state_code:NULL') || ', ' || coalesce(_urb, 'urb:NULL') || ', ' || coalesce(_urb_postcode, '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.id_state = _state_id;
    	IF FOUND THEN
    		RETURN _urb_id;
    	END IF;
    	INSERT INTO dem.urb (name, postcode, id_state) VALUES (_urb, _urb_postcode, _state_id);
    	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_states()

### Returns: boolean

### Language: PLPGSQL

    declare
    	_state_code text;
    	_state_name text;
    	_country_row record;
    begin
    	_state_code := '??';
    	_state_name := 'state/territory/province/region not available';
    	-- add default state to countries needing one
    	for _country_row in
    		select distinct code from dem.country
    		where code not in (
    			select country from dem.state where code = _state_code
    		)
    	loop
    		raise notice 'adding default state for [%]', _country_row.code;
    		execute 'insert into dem.state (code, country, name) values ('
    				|| quote_literal(_state_code) || ', '
    				|| quote_literal(_country_row.code) || ', '
    				|| quote_literal(_state_name) || ');';
    	end loop;
    	return true;
    end;

## Function: dem.new_pupic()

### Returns: bpchar

### Language: PLPGSQL

    DECLARE
    BEGIN
       -- how does this work? How do we get new 'unique' numbers?
       RETURN '0000000000';
    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_announce_comm_channel_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_identity
    	if TG_OP = 'DELETE' then
    		_pk_identity := OLD.fk_identity;
    	else
    		_pk_identity := NEW.fk_identity;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'dem.trf_announce_comm_channel_mod(): cannot determine identity PK on table <dem.lnk_identity2comm>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "comm_channel_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: dem.trf_announce_identity_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via pk
    	if TG_OP = 'DELETE' then
    		_pk_identity := OLD.pk;
    	else
    		_pk_identity := NEW.pk;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'dem.trf_announce_identity_mod(): cannot determine identity PK on table <dem.identity>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "identity_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: dem.trf_announce_identity_tag_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_identity
    	if TG_OP = 'DELETE' then
    		_pk_identity := OLD.fk_identity;
    	else
    		_pk_identity := NEW.fk_identity;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'dem.trf_announce_identity_tag_mod(): cannot determine identity PK on table <dem.identity_tag>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "identity_tag_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: dem.trf_announce_message_inbox_generic_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "message_inbox_generic_mod_db:"';
    	return NULL;
    end;

## Function: dem.trf_announce_message_inbox_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via fk_patient
    	if TG_OP = 'DELETE' then
    		_pk_identity := OLD.fk_patient;
    	else
    		_pk_identity := NEW.fk_patient;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'dem.trf_announce_message_inbox_mod(): cannot determine identity PK on table <dem.message_inbox>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "message_inbox_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: dem.trf_announce_name_mod()

### Returns: trigger

### Language: PLPGSQL

    declare
    	_pk_identity integer;
    begin
    	_pk_identity := NULL;
    	-- retrieve identity PK via id_identity
    	if TG_OP = 'DELETE' then
    		_pk_identity := OLD.id_identity;
    	else
    		_pk_identity := NEW.id_identity;
    	end if;
    	-- soft error out if not found
    	if _pk_identity is NULL then
    		raise notice 'dem.trf_announce_name_mod(): cannot determine identity PK on table <dem.names>';
    		return NULL;
    	end if;
    	-- now, execute() the NOTIFY
    	execute 'notify "name_mod_db:' || _pk_identity || '"';
    	return NULL;
    end;

## Function: dem.trf_announce_org_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "org_mod_db:"';
    	return NULL;
    end;

## Function: dem.trf_announce_org_unit_comm_channel_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "org_unit_comm_channel_mod_db:"';
    	return NULL;
    end;

## Function: dem.trf_announce_org_unit_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "org_unit_mod_db:"';
    	return NULL;
    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;

# 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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| user_action | text | NOT NULL

Table gm.access_log Inherits audit_fields,

gm.access_log Constraints
Name | Constraint
--- | ---
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 | serial | PRIMARY KEY
| schema_name | name | UNIQUE#1 NOT NULL DEFAULT 'public'::name
| table_name | name | UNIQUE#1 NOT NULL
| signal | name | UNIQUE#1 The name of the signal to send via NOTIFY. The actual name of the signal will be "<signal>_mod_db:<identity_pk>" where the :<identity_pk> is only added if the notify trigger knows how.
| carries_identity_pk | boolean | DEFAULT false Whether or not the signal delivers the PK of the related identity. Set during bootstrapping.

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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| filename | text | UNIQUE#1 NOT NULL the name of the script, handled most easily by CVS via "RCSfile"
| version | text | UNIQUE#1 NOT NULL the version of the script, handled most easily by CVS via "Revision"
| imported | timestamp with time zone | NOT NULL DEFAULT now() when this script was imported, mainly for debugging

Index - Schema gm

## 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.add_table_for_notifies($1, $2, $2);

## Function: gm.add_table_for_notifies(name, name, name)

### Returns: boolean

### Language: SQL

Mark given table for notification trigger generator. Parameters are: (schema, table, signal name)

    select gm.register_notifying_table($1, $2, $3);

## 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_v16_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;
    	select into _struct gm.concat_table_structure_v16_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_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_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_generic_combi_vaccines()

### Returns: boolean

### Language: SQL

    select gm.create_generic_combi_vaccine (
    	'Td'::text,
    	ARRAY['tetanus'::text,'diphtheria'::text],
    	'J07AM51',
    	False
    );
    select gm.create_generic_combi_vaccine (
    	'DT'::text,
    	ARRAY['tetanus'::text,'diphtheria'::text],
    	'J07AM51',
    	False
    );
    select gm.create_generic_combi_vaccine (
    	'TdaP'::text,
    	ARRAY['tetanus'::text,'diphtheria'::text,'pertussis'::text],
    	'J07CA01',
    	False
    );
    select gm.create_generic_combi_vaccine (
    	'TDaP'::text,
    	ARRAY['tetanus'::text,'diphtheria'::text,'pertussis'::text],
    	'J07CA01',
    	False
    );
    select gm.create_generic_combi_vaccine (
    	'TdaP-Pol'::text,
    	ARRAY['tetanus'::text,'diphtheria'::text,'pertussis'::text,'poliomyelitis'::text],
    	'J07CA02',
    	False
    );
    select gm.create_generic_combi_vaccine (
    	'TDaP-Pol'::text,
    	ARRAY['tetanus'::text,'diphtheria'::text,'pertussis'::text,'poliomyelitis'::text],
    	'J07CA02',
    	False
    );
    select gm.create_generic_combi_vaccine (
    	'TDaP-Pol-HiB'::text,
    	ARRAY['tetanus'::text,'diphtheria'::text,'pertussis'::text,'poliomyelitis'::text,'haemophilus influenzae b'::text],
    	'J07CA06',
    	False
    );
    select gm.create_generic_combi_vaccine (
    	'TDaP-Pol-HiB-HepB'::text,
    	ARRAY['tetanus'::text,'diphtheria'::text,'pertussis'::text,'poliomyelitis'::text,'haemophilus influenzae b'::text,'hepatitis B'::text],
    	'J07CA09',
    	False
    );
    select gm.create_generic_combi_vaccine (
    	'MMR'::text,
    	ARRAY['measles'::text,'mumps'::text,'rubella'::text],
    	'J07BD52',
    	True
    );
    select gm.create_generic_combi_vaccine (
    	'MMRV'::text,
    	ARRAY['measles'::text,'mumps'::text,'rubella'::text,'varicella (chickenpox, shingles)'::text],
    	'J07BD54',
    	True
    );
    select gm.create_generic_combi_vaccine (
    	'HepAB'::text,
    	ARRAY['hepatitis A'::text,'hepatitis B'::text],
    	'J07BC20',
    	False
    );
    select True;

## Function: gm.create_generic_monovalent_vaccines()

### Returns: boolean

### Language: PLPGSQL

    DECLARE
    	_row record;
    	_generic_name text;
    	_pk_brand integer;
    	_pk_vaccine integer;
    BEGIN
    	for _row in select * from clin.vacc_indication loop
    		_generic_name := _row.description || ' - generic vaccine';
    		raise notice 're-creating [%]', _generic_name;
    		-- 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(_row.atcs_single_indication[1], '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 (
    				false,
    				_pk_brand
    			)
    			returning pk
    			into _pk_vaccine;
    		end if;
    		-- link indication to vaccine
    		delete from clin.lnk_vaccine2inds
    		where
    			fk_vaccine = _pk_vaccine;
    		insert into clin.lnk_vaccine2inds (
    			fk_vaccine,
    			fk_indication
    		) values (
    			_pk_vaccine,
    			_row.id
    		);
    	end loop;
    	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.

    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-doctors" add user ' || quote_ident(_username) || ';';
    	execute _query;
    	_query := 'alter group "gm-public" add user ' || quote_ident(_username) || ';';
    	execute _query;
    	-- satisfy "database = samegroup" 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

    DECLARE
    	_db alias for $1;
    	_gm_users text[];
    	_user text;
    BEGIN
    	_gm_users := ARRAY['gm-logins', 'gm-public', 'gm-doctors', _db];
    	-- add 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 *.modified_by entries
    	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 dem.staff.db_user entries
    	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.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: $RCSfile: v12-gm-log_script_insertion.sql,v $ ($Revision: 1.1 $)'
    	);
    	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: SQL

Mark given table for notification trigger generator. Parameters are: (schema, table). Defaults signal to table name.

    select gm.register_notifying_table($1, $2, $2);

## Function: gm.register_notifying_table(name, name, name)

### Returns: boolean

### Language: PLPGSQL

Register given table for notification trigger generator. Parameters are: (schema, table, signal name)

    DECLARE
    	_namespace alias for $1;
    	_table alias for $2;
    	_signal alias for $3;
    	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
    		and signal = _signal;
    	insert into gm.notifying_tables (
    		schema_name,
    		table_name,
    		signal
    	) values (
    		_namespace,
    		_table,
    		_signal
    	);
    	return true;
    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.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 | serial | PRIMARY KEY
| db_user | name | UNIQUE NOT NULL DEFAULT "current_user"() The database account this language setting applies to.
| lang | text | NOT NULL

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 | serial | PRIMARY KEY
| orig | text | UNIQUE NOT NULL

Index - Schema i18n

## Table: i18n.translations

this table holds all the translated strings

i18n.translations Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| lang | text | UNIQUE#1 NOT NULL the language (corresponding to i18n.curr_lang for a given user) that this translation belongs to
| orig | text | UNIQUE#1 NOT NULL the original, untranslated string, used as the search key.
| trans | text | NOT NULL the translation of <orig> into <lang>

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
--- | --- | --- | ---
| lang | text |
| orig | text |

    SELECT icl.lang
    , ik.orig
    FROM (
    SELECT DISTINCT
        ON (curr_lang.lang) curr_lang.lang
      FROM i18n.curr_lang
    ) icl
    , i18n.keys ik
    WHERE (NOT
         (ik.orig IN
               (
                SELECT translations.orig
                  FROM i18n.translations
               )
         )
    );

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 <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;
    	end if;
    	return trans_str;
    END;

## Function: i18n.force_curr_lang(text)

### Returns: unknown

### Language: PLPGSQL

force preferred language to some language for "current user"

    DECLARE
        _lang ALIAS FOR $1;
    	_status boolean;
    BEGIN
    	select into _status i18n.force_curr_lang(_lang, CURRENT_USER);
    	return _status;
    END;

## Function: i18n.force_curr_lang(text, name)

### Returns: unknown

### Language: PLPGSQL

force preferred language to some language for a user

    DECLARE
    	_lang ALIAS FOR $1;
    	_db_user ALIAS FOR $2;
    BEGIN
        raise notice 'Forcing current language for [%] to [%] without checking for translations...', _db_user, _lang;
        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.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 user" - only if translations for this language are available

    DECLARE
    	_lang ALIAS FOR $1;
    	_status boolean;
    BEGIN
    	select into _status i18n.set_curr_lang(_lang, CURRENT_USER);
    	return _status;
    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.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 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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| name_short | text | UNIQUE NOT NULL
| name_long | text | 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 | text | UNIQUE
| pk | serial | 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 | serial | PRIMARY KEY
ref.paperwork_templates.pk | fk_form | integer | UNIQUE#1 UNIQUE#2 NOT NULL
| long_name | text | UNIQUE#1 NOT NULL The full name of the form field as presented to the user
| template_placeholder | text | UNIQUE#2 NOT NULL The name of the field as exposed to the form template. In other words, the placeholder in form_defs.template where the value entered into this field ist to be substituted. Must be a valid identifier in the form template's script language (viz. Python)
| help | text | longer help text
public.form_field_types.pk | fk_type | integer | NOT NULL the field type
| param | text | a parameter for the field's behaviour, meaning is type-dependent
| display_order | integer | used to *suggest* display order, but client may ignore

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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
clin.form_instances.pk | fk_form_instance | integer | NOT NULL points to the unrendered source instance of the form, useful for recalling submitted jobs for changing
| form | bytea | NOT NULL the rendered form, IOW binary data such as a PDF file
public.form_job_targets.pk | fk_job_target | integer | NOT NULL points to the job target
| submitted_when | timestamp with time zone | NOT NULL DEFAULT now() when was this form job submitted
| fk_submitted_by | integer | NOT NULL who of the staff submitted this form job
| submitted_from | text | NOT NULL the workplace this form job was submitted from
| status | text | NOT NULL DEFAULT 'submitted'::text status of the form job: - submitted: ready for processing - in progress: being processed - removable: fit for removal (either cancelled, timed out or done) - halted: do not process

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 | serial | PRIMARY KEY
| target | text | UNIQUE NOT NULL

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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| fk_form | integer | UNIQUE NOT NULL
ref.papersizes.pk | fk_papersize | integer | NOT NULL
| offset_top | integer | NOT NULL in mm - and yes, they do change even within one type of form, but we do not want to change the offset for all the fields in that case
| offset_left | integer | NOT NULL
| pages | integer | NOT NULL DEFAULT 1
| printer | text | NOT NULL
| tray | text | NOT NULL
| manual_feed | boolean | NOT NULL DEFAULT false
| papertype | text | NOT NULL type of paper such as "watermarked rose", mainly for user interaction on manual_feed==true
| eject_direction | character(1) | NOT NULL
| orientation | character(1) | NOT NULL

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 | serial | PRIMARY KEY
| client_type | text | UNIQUE#1 NOT NULL the type of client this row refers to
| client_version | text | UNIQUE#1 NOT NULL the version of the client this row refers to
| db_identity_hash | text | UNIQUE#1 NOT NULL the identity_hash of a database revision that the client version can work with

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 | serial | PRIMARY KEY
| reported_when | timestamp with time zone | NOT NULL DEFAULT now()
| reported_by | text | NOT NULL DEFAULT "current_user"() who or what reported this condition, may be a user or software
| reported_to | text | NOT NULL DEFAULT 'admin'::text who is this condition reported to, user or admin, used for filtering
| problem | text | NOT NULL a description of the reported condition
| solution | text | a proposed solution to the problem
| context | text | specific context for this condition that would make the problem field unnecessary complex and bulky
| category | text | NOT NULL a category for the condition, this is used for filtering, too
| cookie | text | stores arbitrary information related to the condition, mostly used for semantic duplicates detection, eg. do not report on a single problem more than once in subsequent runs of, say, an import script

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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| fk_ref_src | integer | UNIQUE#1 NOT NULL source this reference data set was taken from
| data | text | UNIQUE#1 NOT NULL the actual reference data in some format, say, XML or like in a *.conf file
| comment | text |

Index - Schema public

## Table: public.unit

units as used in real life

public.unit Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
public.basic_unit.pk | fk_basic_unit | integer | what is the SI-Standard unit for this, e.g. for the unit mg it is kg
| name_short | text | NOT NULL
| name_long | text |
| factor | double precision | NOT NULL DEFAULT 1.0 what factor the value with this unit has to be multiplied with to get values in the basic_unit
| shift | double precision | NOT NULL DEFAULT 0.0 what has to be added (after multiplying by factor) to a value with this unit to get values in the 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
--- | --- | --- | ---
| pk_coding_system | integer | NOT NULL DEFAULT nextval('ref.coding_system_root_pk_coding_system_seq'::regclass)
| code | text | NOT NULL holds the ATC code
| term | text | NOT NULL the name of the drug component
ref.data_source.pk | fk_data_source | integer | NOT NULL
| comment | text | a comment on this ATC
| pk | serial | PRIMARY KEY
| ddd | numeric | the Defined Daily Dosage
| unit | text | the unit on the DDD
| administration_route | text | by what route this drug is to be given

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
--- | --- | --- | ---
| atc | text |
| name | text |
| ddd | text |
| unit | text |
| adro | text |
| comment | text |

Index - Schema ref

## Table: ref.branded_drug

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.branded_drug Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | NOT NULL the name of this drug it is marketed under by the manufacturer
| preparation | text | NOT NULL the preparation the drug is delivered in, eg liquid, cream, tablet, etc.
| atc_code | text | the Anatomic Therapeutic Chemical code for this drug, used to compute possible substitutes
| is_fake | boolean | NOT NULL DEFAULT false Whether this truly is an actual brand of an actual drug rather than a fake brand created for documenting a, say, lifestyle nutrient or simply a component as opposed to a particular actual brand.
ref.data_source.pk | fk_data_source | integer | the data source this entry came from
| external_code | text | an opaque code from an external data source, such as "PZN" in Germany
| external_code_type | text | an opaque code type from an external data source, such as "PZN" in Germany

Table ref.branded_drug Inherits audit_fields,

ref.branded_drug Constraints
Name | Constraint
--- | ---
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:

- clin.vaccine

- ref.lnk_substance2brand

idx_drug_data_source fk_data_source idx_drug_description description idx_drug_ext_code external_code

Index - Schema ref

## Table: ref.code_thesaurus_root

Synonyms for coded terms.

ref.code_thesaurus_root Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_thesaurus | serial | PRIMARY KEY
| fk_code | integer | NOT NULL
| synonym | text |

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
--- | --- | --- | ---
| pk_coding_system | serial | PRIMARY KEY
| code | text | UNIQUE#1 NOT NULL
| term | text | UNIQUE#2 NOT NULL
ref.data_source.pk | fk_data_source | integer | UNIQUE#1 UNIQUE#2 NOT NULL links to the data source for the external reference data set
| comment | text | an arbitrary comment on the code and/or term, child tables will use this in different ways

Index - Schema ref

## Table: ref.consumable_substance

lists substances that are consumable by patients, whether or not linked to a branded drug

ref.consumable_substance Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | UNIQUE#1 The substance name.
| atc_code | text | (One) Anatomic Therapeutic Chemical code for this substance. Note that substances can have *several* ATC codes assigned to it by the WHO denoting different therapeutic uses and/or local application formulations. This code can *only* be used to *identify* the substance, not the use/application formulation thereof.
| amount | numeric | UNIQUE#1 NOT NULL The amount of substance.
| unit | text | UNIQUE#1 The unit of the amount of substance.

Table ref.consumable_substance Inherits audit_fields,

ref.consumable_substance Constraints
Name | Constraint
--- | ---
ref_consumable_sane_amount | CHECK ((amount >= (0)::numeric))
ref_consumable_sane_unit | CHECK ((gm.is_null_or_blank_string(unit) IS FALSE))
ref_subst_sane_atc | CHECK ((gm.is_null_or_non_empty_string(atc_code) IS TRUE))
ref_subst_sane_desc | CHECK ((gm.is_null_or_blank_string(description) IS FALSE))

Tables referencing this one via Foreign Key Constraints:

- clin.substance_intake

- ref.lnk_substance2brand

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| name_long | text | UNIQUE#1 NOT NULL long, complete (, ?official) name for this reference entry
| name_short | text | UNIQUE#2 NOT NULL shorthand for referring to this reference entry
| version | text | UNIQUE#1 UNIQUE#2 NOT NULL the exact and non-ambigous version for this entry
| description | text | optional arbitrary description, should include external license
| source | text | NOT NULL non-ambigous description of source; with this info in hand it must be possible to locate a copy of the external data set
| lang | text |

Table ref.data_source Inherits audit_fields,

Tables referencing this one via Foreign Key Constraints:

- dem.org

- ref.atc

- ref.branded_drug

- ref.coding_system_root

- 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 | serial | PRIMARY KEY
| scope | text | can be used to group document types according to applicability, say, per country
| description | text | NOT NULL

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 | text | UNIQUE NOT NULL
| pk | serial | 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_coding_system | integer | NOT NULL DEFAULT nextval('ref.coding_system_root_pk_coding_system_seq'::regclass)
| code | text | NOT NULL
| term | text | NOT NULL
ref.data_source.pk | fk_data_source | integer | NOT NULL
| comment | text |
| pk | serial | PRIMARY KEY
| star_code | text | The star code which needs to be combined with the primary code to define the term.
| aux_code | text | The auxiliary code which needs to be combined with the primary code to define the term.

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_coding_system | integer | NOT NULL DEFAULT nextval('ref.coding_system_root_pk_coding_system_seq'::regclass)
| code | text | NOT NULL
| term | text | NOT NULL
ref.data_source.pk | fk_data_source | integer | NOT NULL
| comment | text |
| pk | serial | PRIMARY KEY

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
--- | --- | --- | ---
| pk_coding_system | integer | NOT NULL DEFAULT nextval('ref.coding_system_root_pk_coding_system_seq'::regclass)
| code | text | UNIQUE#1 NOT NULL
| term | text | NOT NULL
ref.data_source.pk | fk_data_source | integer | NOT NULL
| comment | text |
| pk | serial | PRIMARY KEY
| code_extension | text | UNIQUE#1 An extension to the bare code as defined in, say, the Netherlands or Australia.
| short_description | text | A shorter term for this item
| icd10 | text[] | Array of corresponding ICD-10 codes.
| criteria | text | Criteria to guide in selection of the appropriate code.
| inclusions | text | Items included under this code.
| exclusions | text[] | Items NOT included under this code because there is another code for them.
| see_also | text[] | See also under these items.
ref.icpc_component.component | fk_component | smallint | NOT NULL
ref.icpc_chapter.chapter | fk_chapter | character(1) | NOT NULL

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 | serial | PRIMARY KEY
| chapter | character(1) | UNIQUE NOT NULL
| description | text | 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
--- | --- | --- | ---
| pk | serial | PRIMARY KEY
| component | smallint | UNIQUE NOT NULL
| description | text | UNIQUE
| typical_soap_cat | text[] | An array of SOAP categories which codes from this component are typically used for.

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_thesaurus | integer | NOT NULL DEFAULT nextval('ref.code_thesaurus_root_pk_thesaurus_seq'::regclass)
ref.icpc.pk_coding_system | fk_code | integer | NOT NULL
| synonym | text |
| pk | serial | PRIMARY KEY

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.lnk_substance2brand

This table links substances (INNs, mostly) as components into drugs.

ref.lnk_substance2brand Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
ref.branded_drug.pk | fk_brand | integer | UNIQUE#1 NOT NULL
ref.consumable_substance.pk | fk_substance | integer | UNIQUE#1 NOT NULL

Table ref.lnk_substance2brand Inherits audit_fields,

Tables referencing this one via Foreign Key Constraints:

- clin.substance_intake

idx_lnk_s2b_fk_brand fk_brand idx_lnk_s2b_fk_substance fk_substance

Index - Schema ref

## Table: ref.loinc

holds LOINC codes

ref.loinc Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_coding_system | integer | NOT NULL DEFAULT nextval('ref.coding_system_root_pk_coding_system_seq'::regclass)
| code | text | NOT NULL holds LOINC_NUM
| term | text | NOT NULL holds either long_common_name or a ":".join of .component to .method_type
ref.data_source.pk | fk_data_source | integer | NOT NULL points to a particular data source which in turn holds the version
| comment | text |
| pk | serial | PRIMARY KEY
| component | text |
| property | text |
| time_aspect | text |
| system | text |
| scale_type | text |
| method_type | text |
| related_names_1_old | text |
| grouping_class | text |
| loinc_internal_source | text |
| dt_last_change | text |
| change_type | text |
| answer_list | text |
| code_status | text |
| maps_to | text |
| scope | text |
| normal_range | text |
| ipcc_units | text |
| reference | text |
| exact_component_synonym | text |
| molar_mass | text |
| grouping_class_type | smallint |
| formula | text |
| species | text |
| example_answers | text |
| acs_synonyms | text |
| base_name | text |
| final | text |
| naa_ccr_id | text |
| code_table | text |
| is_set_root | boolean |
| panel_elements | text |
| survey_question_text | text |
| survey_question_source | text |
| units_required | text |
| submitted_units | text |
| related_names_2 | text |
| short_name | text |
| order_obs | text |
| cdisc_common_tests | text |
| hl7_field_subfield_id | text |
| external_copyright_notice | text |
| example_units | text |
| inpc_percentage | text |
| long_common_name | text |

Table ref.loinc Inherits coding_system_root,

idx_ref_loinc_fk_data_src fk_data_source

Index - Schema ref

## Table: ref.loinc_staging

used for importing LOINC data, columns correspond 1:1 with the LOINC CSV file fields

ref.loinc_staging Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| loinc_num | text |
| component | text |
| property | text |
| time_aspect | text |
| system | text |
| scale_type | text |
| method_type | text |
| related_names_1_old | text |
| class | text |
| source | text |
| dt_last_change | text |
| change_type | text |
| comments | text |
| answer_list | text |
| status | text |
| map_to | text |
| scope | text |
| normal_range | text |
| ipcc_units | text |
| reference | text |
| exact_component_synonym | text |
| molar_mass | text |
| class_type | text |
| formula | text |
| species | text |
| example_answers | text |
| acs_synonyms | text |
| base_name | text |
| final | text |
| naa_ccr_id | text |
| code_table | text |
| is_set_root | text |
| panel_elements | text |
| survey_question_text | text |
| survey_question_source | text |
| units_required | text |
| submitted_units | text |
| related_names_2 | text |
| short_name | text |
| order_obs | text |
| cdisc_common_tests | text |
| hl7_field_subfield_id | text |
| external_copyright_notice | text |
| example_units | text |
| inpc_percentage | text |
| long_common_name | text |

Index - Schema ref

## Table: ref.ops

Holds OPS (German ICPM-CM) codes.

ref.ops Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_coding_system | integer | NOT NULL DEFAULT nextval('ref.coding_system_root_pk_coding_system_seq'::regclass)
| code | text | NOT NULL
| term | text | NOT NULL
ref.data_source.pk | fk_data_source | integer | NOT NULL
| comment | text |
| pk | serial | PRIMARY KEY
| second_code | text |
| requires_laterality | boolean |

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
--- | --- | --- | ---
| pk_coding_system | integer | NOT NULL DEFAULT nextval('ref.coding_system_root_pk_coding_system_seq'::regclass)
| code | text | NOT NULL
| term | text | NOT NULL
ref.data_source.pk | fk_data_source | integer | NOT NULL
| comment | text |
| pk | serial | 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 | serial | PRIMARY KEY
| name | text | UNIQUE NOT NULL
| size | point | NOT NULL (cm, cm)

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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
ref.form_types.pk | fk_template_type | integer | NOT NULL
| instance_type | text | default document type to store documents generated from this form under, note that this may generate rows in blobs.doc_type if set to a non-existant document type
| name_short | text | UNIQUE#2 NOT NULL a short name for use in a GUI or some such
| name_long | text | UNIQUE#1 UNIQUE#2 NOT NULL a long name unambigously describing the form
| external_version | text | UNIQUE#1 NOT NULL
| gnumed_revision | double precision | UNIQUE#1 GnuMed internal form def version, may occur if we rolled out a faulty form def
| engine | text | NOT NULL DEFAULT 'O'::text the business layer forms engine used to process this form, currently: - T: plain text - L: LaTeX - H: Health Layer 7 - O: OpenOffice - I: image editor (visual progress notes) - G: gnuplot scripts (test results graphing) - P: PDF form (FDF based)
| in_use | boolean | NOT NULL DEFAULT true whether this template is currently actively used in a given practice
| filename | text | the filename from when the template data was imported if applicable, used by some engines (such as OOo) to differentiate what to do with certain files, such as *.ott vs. *.ods, GNUmed uses it to derive a file extension when exporting the template data
| data | bytea | the template complete with placeholders in the format accepted by the engine defined in ref.paperwork_templates.engine

Table ref.paperwork_templates Inherits audit_fields,

ref.paperwork_templates Constraints
Name | Constraint
--- | ---
engine_range | CHECK ((engine = ANY (ARRAY['T'::text, 'L'::text, 'H'::text, 'O'::text, 'I'::text, 'G'::text, 'P'::text])))

Tables referencing this one via Foreign Key Constraints:

- clin.form_instances

- public.form_fields

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_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk | serial | PRIMARY KEY
| description | text | UNIQUE A textual description of the meaning of the tag. Keep this reasonably short.
| filename | text | An example filename, mainly for preserving the file suffix. Set during import, suffix used during export.
| image | bytea | NOT NULL An image showing the meaning of the tag.

Table ref.tag_image Inherits audit_fields,

ref.tag_image Constraints
Name | Constraint
--- | ---
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
--- | --- | --- | ---
| pk_atc | integer |
| atc | text |
| term | text |
| ddd | numeric |
| unit | text |
| administration_route | text |
| comment | text |
| is_group_code | boolean |
| atc_level | integer |
| name_long | text |
| name_short | text |
| version | text |
| lang | text |
| pk_coding_system | integer |
| pk_data_source | integer |

    SELECT a.pk AS pk_atc
    , a.code AS atc
    , a.term
    , a.ddd
    , a.unit
    , 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_branded_drugs

ref.v_branded_drugs Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_brand | integer |
| brand | text |
| preparation | text |
| atc | text |
| external_code | text |
| external_code_type | text |
| is_fake_brand | boolean |
| components | text[] |
| pk_components | integer[] |
| pk_substances | integer[] |
| pk_data_source | integer |
| xmin_branded_drug | xid |

    SELECT r_bd.pk AS pk_brand
    , r_bd.description AS brand
    , r_bd.preparation
    , r_bd.atc_code AS atc
    , r_bd.external_code
    , r_bd.external_code_type
    , r_bd.is_fake AS is_fake_brand
    , (
    SELECT array_agg
         (
               (
                     (
                           (
                                 (
                                       (
                                             (r_cs.description || '::'::text) || r_cs.amount
                                       ) || '::'::text
                                 ) || r_cs.unit
                           ) || '::'::text
                     ) || COALESCE
                     (r_cs.atc_code
                           ,''::text
                     )
               )
         ) AS array_agg
      FROM (ref.lnk_substance2brand r_ls2b
            JOIN ref.consumable_substance r_cs
              ON (
                     (r_ls2b.fk_substance = r_cs.pk)
               )
         )
     WHERE (r_ls2b.fk_brand = r_bd.pk)
    ) AS components
    , (
    SELECT array_agg
         (r_ls2b.pk) AS array_agg
      FROM ref.lnk_substance2brand r_ls2b
     WHERE (r_ls2b.fk_brand = r_bd.pk)
    ) AS pk_components
    , (
    SELECT array_agg
         (r_ls2b.fk_substance) AS array_agg
      FROM ref.lnk_substance2brand r_ls2b
     WHERE (r_ls2b.fk_brand = r_bd.pk)
    ) AS pk_substances
    , r_bd.fk_data_source AS pk_data_source
    , r_bd.xmin AS xmin_branded_drug
    FROM ref.branded_drug r_bd;

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
--- | --- | --- | ---
| code | text |
| term | text |
| coding_system | text |
| coding_system_long | text |
| version | text |
| lang | text |
| pk_generic_code | integer |

    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)
         )
    )
    UNIONSELECT 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
--- | --- | --- | ---
| pk_component | integer |
| brand | text |
| substance | text |
| amount | numeric |
| unit | text |
| preparation | text |
| atc_substance | text |
| atc_brand | text |
| external_code_brand | text |
| external_code_type_brand | text |
| is_fake_brand | boolean |
| is_in_use | boolean |
| pk_brand | integer |
| pk_consumable_substance | integer |
| pk_data_source | integer |
| xmin_lnk_substance2brand | xid |

    SELECT r_ls2b.pk AS pk_component
    , r_bd.description AS brand
    , r_cs.description AS substance
    , r_cs.amount
    , r_cs.unit
    , r_bd.preparation
    , r_cs.atc_code AS atc_substance
    , r_bd.atc_code AS atc_brand
    , r_bd.external_code AS external_code_brand
    , r_bd.external_code_type AS external_code_type_brand
    , r_bd.is_fake AS is_fake_brand
    , (EXISTS
         (
          SELECT 1
            FROM clin.substance_intake c_si
           WHERE (c_si.fk_drug_component = r_ls2b.pk) LIMIT 1
         )
    ) AS is_in_use
    , r_ls2b.fk_brand AS pk_brand
    , r_cs.pk AS pk_consumable_substance
    , r_bd.fk_data_source AS pk_data_source
    , r_ls2b.xmin AS xmin_lnk_substance2brand
    FROM (
         (ref.consumable_substance r_cs
            JOIN ref.lnk_substance2brand r_ls2b
              ON (
                     (r_cs.pk = r_ls2b.fk_substance)
               )
         )
    LEFT JOIN ref.branded_drug r_bd
        ON (
               (r_ls2b.fk_brand = r_bd.pk)
         )
    );

Index - Schema ref

## View: ref.v_generic_codes

Denormalized generic codes.

ref.v_generic_codes Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_generic_code | integer |
| code | text |
| term | text |
| name_long | text |
| name_short | text |
| version | text |
| lang | text |
| code_table | regclass |
| pk_data_source | integer |

    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
--- | --- | --- | ---
| code | text |
| code_extension | text |
| extended_code | text |
| term | text |
| short_description | text |
| code_chapter | character(1) |
| chapter | text |
| l10n_chapter | text |
| code_component | smallint |
| component | text |
| l10n_component | text |
| typical_soap_cat | text[] |
| icd10 | text[] |
| criteria | text |
| inclusions | text |
| exclusions | text[] |
| see_also | text[] |
| comment | text |
| name_short | text |
| name_long | text |
| version | text |
| lang | text |
| pk_icpc | integer |
| pk_data_source | integer |

    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
--- | --- | --- | ---
| pk_icpc_thesaurus | integer |
| code | text |
| term | text |
| synonym | text |
| pk_thesaurus | integer |
| pk_coding_system | integer |
| pk_icpc | integer |

    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_paperwork_templates

ref.v_paperwork_templates Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_paperwork_template | integer |
| name_short | text |
| name_long | text |
| external_version | text |
| template_type | text |
| l10n_template_type | text |
| instance_type | text |
| l10n_instance_type | text |
| engine | text |
| in_use | boolean |
| filename | text |
| has_template_data | boolean |
| has_instances | boolean |
| last_modified | timestamp with time zone |
| modified_by | text |
| pk_template_type | integer |
| xmin_paperwork_template | xid |

    SELECT rpt.pk AS pk_paperwork_template
    , rpt.name_short
    , rpt.name_long
    , rpt.external_version
    , (
    SELECT form_types.name
      FROM ref.form_types
     WHERE (form_types.pk = rpt.fk_template_type)
    ) AS template_type
    , (
    SELECT _
         (form_types.name) AS _
      FROM ref.form_types
     WHERE (form_types.pk = rpt.fk_template_type)
    ) AS l10n_template_type
    , COALESCE
    (rpt.instance_type
         , (
          SELECT form_types.name
            FROM ref.form_types
           WHERE (form_types.pk = rpt.fk_template_type)
         )
    ) AS instance_type
    , COALESCE
    (_
         (rpt.instance_type)
         , (
          SELECT _
               (form_types.name) AS _
            FROM ref.form_types
           WHERE (form_types.pk = rpt.fk_template_type)
         )
    ) AS l10n_instance_type
    , rpt.engine
    , rpt.in_use
    , rpt.filename
    , CASE WHEN
    (rpt.data IS NOT NULL) THEN true ELSE false END AS has_template_data
    , (
    SELECT (EXISTS
               (
                SELECT 1
                  FROM form_fields
                 WHERE (form_fields.fk_form = rpt.pk) LIMIT 1
               )
         )
    ) AS has_instances
    , rpt.modified_when AS last_modified
    , COALESCE
    (
         (
          SELECT staff.short_alias
            FROM dem.staff
           WHERE (staff.db_user = rpt.modified_by)
         )
         , (
               ('<'::text ||
                     (rpt.modified_by)::text
               ) || '>'::text
         )
    ) AS modified_by
    , rpt.fk_template_type AS pk_template_type
    , rpt.xmin AS xmin_paperwork_template
    FROM ref.paperwork_templates rpt;

Index - Schema ref

## View: ref.v_tag_images_no_data

ref.v_tag_images_no_data Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_tag_image | integer |
| description | text |
| l10n_description | text |
| filename | text |
| size | integer |
| is_in_use | boolean |
| xmin_tag_image | xid |

    SELECT rti.pk AS pk_tag_image
    , rti.description
    , _
    (rti.description) AS l10n_description
    , rti.filename
    , octet_length
    (COALESCE
         (rti.image
               ,''::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

## Function: ref.trf_announce_branded_drug_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "branded_drug_mod_db:"';
    	return NULL;
    end;

## Function: ref.trf_announce_consumable_substance_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "consumable_substance_mod_db:"';
    	return NULL;
    end;

## Function: ref.trf_announce_lnk_substance2brand_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "lnk_substance2brand_mod_db:"';
    	return NULL;
    end;

## 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_announce_tag_image_mod_no_pk()

### Returns: trigger

### Language: PLPGSQL

    begin
    	execute 'notify "tag_image_mod_db:"';
    	return NULL;
    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_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_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
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now()
| fk_episode | integer | NOT NULL
| narrative | text |
| soap_cat | text | DEFAULT 'p'::text
| pk | integer | PRIMARY KEY DEFAULT nextval('clin.lab_request_pk_seq'::regclass)
clin.test_org.pk | fk_test_org | integer | UNIQUE#1 NOT NULL
| request_id | text | UNIQUE#1 NOT NULL
| fk_requestor | integer |
| lab_request_id | text |
| lab_rxd_when | timestamp with time zone |
| results_reported_when | timestamp with time zone |
| request_status | text | NOT NULL
| is_pending | boolean | NOT NULL DEFAULT true
| diagnostic_service_section | text |
| ordered_service | text |
| fk_incoming_data_unmatched | integer | NOT NULL

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.test_result

Used to stage test results (from hl7 files, currently).

staging.test_result Structure
F-Key | Name | Type | Description
--- | --- | --- | ---
| pk_audit | integer | NOT NULL DEFAULT nextval('audit.audit_fields_pk_audit_seq'::regclass)
| row_version | integer | NOT NULL
| modified_when | timestamp with time zone | NOT NULL DEFAULT now()
| modified_by | name | NOT NULL DEFAULT "current_user"()
| pk_item | integer | NOT NULL DEFAULT nextval('clin.clin_root_item_pk_item_seq'::regclass)
| clin_when | timestamp with time zone | NOT NULL DEFAULT now()
| fk_episode | integer | NOT NULL
| narrative | text |
| soap_cat | text | DEFAULT 'p'::text
| pk | integer | PRIMARY KEY DEFAULT nextval('clin.test_result_pk_seq'::regclass)
| fk_type | integer | NOT NULL
| val_num | numeric |
| val_alpha | text |
| val_unit | text |
| val_normal_min | numeric |
| val_normal_max | numeric |
| val_normal_range | text |
| val_target_min | numeric |
| val_target_max | numeric |
| val_target_range | text |
| abnormality_indicator | text |
| norm_ref_group | text |
| note_test_org | text |
| material | text |
| material_detail | text |
| fk_intended_reviewer | integer | NOT NULL
staging.lab_request.pk | fk_request | integer | NOT NULL
| orig_intended_reviewer | text |

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