File size: 30,188 Bytes
32f12c3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 | -- ==========================================
-- 1. GLOBAL INFRASTRUCTURE & DIMENSION TABLES
-- ==========================================
CREATE TABLE
jurisdictions (
jurisdiction_id SERIAL PRIMARY KEY,
jurisdiction_code VARCHAR(10) NOT NULL UNIQUE,
-- 'US-NY', 'GB-ENG', 'JP'
region_name VARCHAR(100) NOT NULL
);
CREATE TABLE
facilities (
facility_id SERIAL PRIMARY KEY,
facility_code VARCHAR(50) NOT NULL UNIQUE,
-- 'HOSPITAL_A', 'CLINIC_B'
facility_name VARCHAR(150) NOT NULL
);
CREATE TABLE
specialties (
specialty_id SERIAL PRIMARY KEY,
specialty_name VARCHAR(100) NOT NULL UNIQUE
-- 'Cardiology', 'Ophthalmology'
);
CREATE TABLE
personnel (
personnel_id SERIAL PRIMARY KEY,
personnel_description TEXT,
auth_provider_uid VARCHAR(100) NOT NULL UNIQUE
-- Links to system OAuth/IAM ID
);
-- ==========================================
-- 2. CANONCIAL CORE CONCEPTS
-- ==========================================
CREATE TABLE
concept_namespaces (
namespace_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
standard_type VARCHAR(50) NOT NULL,
-- 'SNOMED', 'ICD-10', 'LOINC', 'FHIR', 'CUSTOM'
public_standard BOOLEAN DEFAULT TRUE,
-- True = Public, False = Private/Internal
is_external_private BOOLEAN DEFAULT FALSE,
-- Isolates imported external custom schemas
external_private_source VARCHAR(100),
-- Identifies the originating tenant (e.g., 'HOSPITAL_A')
about TEXT,
link VARCHAR(500),
-- API ENDPOINT: Production ready API to return the concept display string or metadata given a code
-- Ex: example.com/resolve?code={code}
api_url VARCHAR(8192),
-- Supports dynamic query construction with parameter placeholders (e.g., '{code}') for flexible API integrations
api_url_params JSONB,
-- A payload of data being sent the API for processing
api_request_body JSONB,
-- Captures the specific path within the API response body where the display string can be found (e.g. 'abc.results[0].text')
api_response_display_path VARCHAR(500),
created_at TIMESTAMP
WITH
TIME ZONE DEFAULT NOW(),
-- Constraint ensures a specific vocabulary authority vector is logged exactly once
CONSTRAINT uq_namespace_authority UNIQUE (
standard_type, is_external_private,
external_private_source
)
);
CREATE TABLE
canonical_concepts (
concept_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
namespace_id UUID NOT NULL REFERENCES concept_namespaces(namespace_id) ON DELETE RESTRICT,
standard_code VARCHAR(100) NOT NULL,
-- The unchanging numeric code coordinate (e.g., 'R06.02')
display VARCHAR(150) NOT NULL,
-- Official fallback string definition at this timestamp
concept_date_designation TIMESTAMP
WITH
TIME ZONE DEFAULT NOW(),
-- Captures semantic mapping adjustments
-- Composite unique key tracks semantic code drift dynamically over time within its authority space
CONSTRAINT uq_versioned_concept UNIQUE (
namespace_id, standard_code, concept_date_designation
)
);
CREATE INDEX
idx_concepts_traversal_speed ON canonical_concepts (
namespace_id, standard_code, concept_date_designation DESC
); CREATE TYPE concept_translator_relation ENUM (
'EQUIVALENT', 'NARROWER_THAN', 'WIDER_THAN'
);
CREATE TABLE
concept_translator (
link_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
concept_id UUID NOT NULL REFERENCES canonical_concepts(concept_id) ON DELETE CASCADE,
linked_id UUID NOT NULL REFERENCES canonical_concepts(concept_id) ON DELETE CASCADE,
-- 'EQUIVALENT', 'NARROWER_THAN', 'WIDER_THAN'
relationship_type concept_translator_relation NOT NULL DEFAULT 'EQUIVALENT',
active BOOLEAN DEFAULT TRUE,
-- Track exactly when this mapping consensus became valid
mapping_date_designation TIMESTAMP
WITH
TIME ZONE DEFAULT NOW(),
CONSTRAINT chk_prevent_self_loop CHECK (concept_id <> linked_id),
-- Prevent exact duplicate mapping assertions within the same point in time
UNIQUE(
concept_id, linked_id, relationship_type,
mapping_date_designation
)
);
CREATE INDEX
idx_concept_translator_temporal ON concept_translator (
concept_id, mapping_date_designation,
active
);
CREATE TABLE
concept_translator_cache (
cache_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- The starting anchor node (e.g., Your proprietary custom code)
ancestor_concept_id UUID NOT NULL REFERENCES canonical_concepts(concept_id) ON DELETE CASCADE,
-- The terminal reachable node (e.g., A global SNOMED or ICD-10 standard code)
descendant_concept_id UUID NOT NULL REFERENCES canonical_concepts(concept_id) ON DELETE CASCADE,
-- 1 = Direct link, 2 = Parent-to-Grandchild link, 3 = Great-Grandchild, etc.
link_depth INTEGER NOT NULL CHECK (link_depth >= 1),
-- Inherited structural logic path tracking from the path chain
-- e.g., If any link in the path is 'NARROWER_THAN', the global traversal classification updates
inferred_relationship_type concept_translator_relation NOT NULL DEFAULT 'EQUIVALENT',
-- Mirroring the point in time this entire computed track matrix matches validation rules
mapping_date_designation TIMESTAMP
WITH
TIME ZONE NOT NULL,
active BOOLEAN DEFAULT TRUE,
-- Enforce uniqueness of a specific path vector instance at a single coordinate in time
UNIQUE(
ancestor_concept_id, descendant_concept_id,
inferred_relationship_type, mapping_date_designation
)
);
-- Compound index optimized for immediate inheritance evaluation during a backward ledger step
CREATE INDEX
idx_concept_cache_traversal ON concept_translator_cache (
ancestor_concept_id, mapping_date_designation,
active
) INCLUDE (
descendant_concept_id, link_depth,
inferred_relationship_type
);
CREATE TABLE
concept_display_registry (
display_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
concept_id UUID NOT NULL REFERENCES canonical_concepts(concept_id) ON DELETE CASCADE,
-- ISO 639-1 or RFC 5646 codes (e.g., 'en', 'en-US', 'ja', 'es-MX')
language_code VARCHAR(10) NOT NULL DEFAULT 'en',
-- The target human-readable string projection
display_string TEXT NOT NULL,
-- Toggle True/False during usage instead of hardcoding inside display string
reference_standard BOOLEAN DEFAULT FALSE,
reference_code BOOLEAN DEFAULT FALSE,
-- Architecture Layering: Allows for system defaults vs custom localized variants
scope_tier VARCHAR(30) NOT NULL DEFAULT 'GLOBAL',
-- 'GLOBAL', 'CUSTOM_1', 'FACILITY', etc
-- Priority weighting for localized string lookups when multiple matches exist
preference_weight INTEGER DEFAULT 1,
active BOOLEAN DEFAULT TRUE
);
-- ==========================================
-- 3. JURISDICTIONAL INTERSECTION
-- ==========================================
CREATE TABLE
concept_jurisdictional_displays (
display_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
concept_id UUID REFERENCES canonical_concepts(concept_id) ON DELETE CASCADE,
jurisdiction_id INTEGER REFERENCES jurisdictions(jurisdiction_id),
preferred_display TEXT NOT NULL,
fully_specified_name TEXT NOT NULL,
UNIQUE(concept_id, jurisdiction_id)
);
-- ==========================================
-- 4. CDSL EXPRESSIONS & PARSER CONFIG
-- ==========================================
CREATE TYPE expression_target_assignment AS ENUM (
'MAIN_TERM', 'ATTRIBUTE_MODIFIER',
'BOTH'
);
CREATE TABLE
custom_expressions (
expression_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
personnel_id INTEGER REFERENCES personnel(personnel_id),
expression_name VARCHAR(100) NOT NULL,
-- 'SOB', 'usual air problem', 'progressive'
regex_pattern TEXT NOT NULL,
-- Engine regex pattern. Should not encode numerical values
is_case_insensitive BOOLEAN DEFAULT TRUE,
-- Crucial Split: Tells the parser exactly where to route this token in the schema
-- 'MAIN_TERM': maps to observation/vitals concept node
-- 'ATTRIBUTE_MODIFIER': maps to trajectory, qualifiers, etc
-- 'BOTH': is a MAIN_TERM only when no other MAIN_TERMS exist, else it is an ATTRIBUTE
target_assignment expression_target_assignment NOT NULL DEFAULT 'MAIN_TERM',
concept_id UUID REFERENCES canonical_concepts(concept_id),
facility_id INTEGER REFERENCES facilities(facility_id),
specialty_id INTEGER REFERENCES specialties(specialty_id),
priority_weight INTEGER DEFAULT 1,
active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP
WITH
TIME ZONE DEFAULT NOW()
);
CREATE INDEX
idx_expressions_parser_route ON custom_expressions (
expression_name, target_assignment,
active
);
-- ==========================================
-- 5. THE SYSTEM TAGGING MATRIX
-- ==========================================
CREATE TABLE
expression_tags (
tag_id VARCHAR(50) PRIMARY KEY,
-- 'anatomy', 'symptom', 'drug'
description TEXT
);
CREATE TABLE
expression_tag_matrix (
expression_id UUID REFERENCES custom_expressions(expression_id) ON DELETE CASCADE,
tag_id VARCHAR(50) REFERENCES expression_tags(tag_id),
PRIMARY KEY (expression_id, tag_id)
);
-- ==========================================
-- 6. HISTORY TRACKING
-- ==========================================
CREATE TABLE
expression_resolution_counters (
counter_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
expression_id UUID NOT NULL REFERENCES custom_expressions(expression_id) ON DELETE CASCADE,
concept_id UUID NOT NULL REFERENCES canonical_concepts(concept_id) ON DELETE CASCADE,
-- Hierarchical Context Routing Tiers (Nullable to allow fallback resolution profiling)
facility_id INTEGER REFERENCES facilities(facility_id) ON DELETE
SET
NULL,
specialty_id INTEGER REFERENCES specialties(specialty_id) ON DELETE
SET
NULL,
personnel_id INTEGER REFERENCES personnel(personnel_id) ON DELETE
SET
NULL,
-- The Atomic Accumulator
usage_count BIGINT NOT NULL DEFAULT 0 CHECK (usage_count >= 0),
-- Tracking the lifecycle of the expression trend
last_resolved_at TIMESTAMP
WITH
TIME ZONE DEFAULT NOW(),
-- Unique composite coordinate matrix ensures one tracking row per unique context intersection
CONSTRAINT uq_resolution_context_metric UNIQUE(
expression_id, concept_id, facility_id,
specialty_id, personnel_id
)
);
-- Indexing optimized for the context-autocomplete engine to grab the top-weighted suggestions instantly
CREATE INDEX
idx_resolution_weights_speed ON expression_resolution_counters (
expression_id, specialty_id, facility_id,
usage_count DESC
) INCLUDE (concept_id);
-- LEVEL 1: Root Ledger Channels (Top-level polymorphic JSONB columns)
CREATE TYPE ledger_level1_channel AS ENUM (
'assessment', 'vitals_measurement',
'observation', 'exposure_profile',
'device_diagnostic_report', 'clinical_evaluation_report',
'procedure_order', 'medication_order',
'insurance_cost_evaluation', 'clinical_location_followup',
'patient_refusal', 'static_context',
'temporal_context'
);
-- LEVEL 2: Macro Context Containers
CREATE TYPE ledger_level2_context AS ENUM (
-- Core Situational Frameworks (Nests inside temporal_context)
'temporal_location',
-- Maps to temporal_context.location (spatial_type, jurisdiction, setting)
'environmental_weather',
-- Maps to temporal_context.weather (meteo stats, AQI, severe phenomena)
-- Core Material Frameworks (Nests inside static_context)
'protective_equipment',
-- Maps to static_context.ppe_gear (gear category, post-event integrity)
-- Clinical Context Sub-Profiles / Complex Bundles
'subject_of_record',
-- Maps to state_metadata.subject_of_record (primary patient vs proxy relative switches)
'session_variables_log',
-- Maps to state_metadata.session_variables (CDSL runtime tracking block instances)
'merge_resolution_topology',
-- Maps to state_metadata.merge_resolution (graph reconciliation paths)
'algorithmic_evaluation',
-- Maps to assessment.algorithmic_results (input concept array + raw/scalar/boolean output payloads)
-- Exposure Profile Target Profiles
'nutritional_exposure',
-- Maps to exposure_profile.nutritional_profile (dietary substance allergens + quantities)
'biological_exposure',
-- Maps to exposure_profile.biological_exposure_profile (vectors, taxonomy species, toxicity markers)
'mechanical_injury',
-- Maps to exposure_profile.mechanical_injury_profile (blunt, penetrating, avulsion mechanism switches)
'ballistic_profile',
-- Maps to exposure_profile.mechanical_injury_profile.ballistic_profile (weapon platform, caliber, deformation keys)
'injury_fall_details',
-- Maps to exposure_profile.mechanical_injury_profile.fall_details (height vectors, freefall flags)
-- Administrative Evaluation Triggers
'clinical_rule_conflict',
-- Maps to clinical_evaluation_report (drug conflicts, threshold violations, overrides)
'insurance_financial_breakdown',
-- Maps to insurance_cost_evaluation.financial_breakdown (allowables, copays, OOP responsibility)
'insurance_accumulator'
-- Maps to insurance_cost_evaluation.accumulator_impact (deductible and max-out balances)
);
-- LEVEL 3: Standard Object Components (Global reusable $defs structures)
CREATE TYPE ledger_level3_def AS ENUM (
'source_type', 'certainty', 'status',
'associated_agent', 'temporal_boundary',
'time', 'date_range', 'single_measurement',
'measurement', 'product_identifiers',
'anatomy_locations', 'vehicle',
'pharmaceutical'
); CREATE TYPE expression_tier_level AS ENUM (
'LEVEL_1', 'LEVEL_2', 'LEVEL_3', 'LEVEL_4',
'LEVEL_5'
);
CREATE TABLE
expression_hierarchical_routes (
route_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
expression_id UUID NOT NULL REFERENCES custom_expressions(expression_id) ON DELETE CASCADE,
-- The runtime operational level definition
tier_level expression_tier_level NOT NULL,
-- Level targets (Mutually exclusive or strictly cascaded based on constraints)
target_level1 ledger_level1_channel,
target_level2 ledger_level2_context,
target_level3 ledger_level3_def,
-- Targets a subfield within the JSONB structure defined by the level 1-3 targets (e.g., 'ballistic_profile.firearm_or_ordnance')
target_level4 VARCHAR(512),
target_level5 VARCHAR(512),
active BOOLEAN DEFAULT TRUE,
);
-- Create a composite execution index optimized to instantly pull the routing path definition
-- Highly optimized for query engine execution plans
CREATE INDEX
idx_expression_compiler_path ON expression_hierarchical_routes (
expression_id, active, tier_level
) INCLUDE (
target_level1, target_level2, target_level3,
target_level4, target_level5
);
-- ==========================================
-- SCALED CASCADING CONTEXT REGISTRY
-- ==========================================
CREATE TYPE configuration_data_type AS ENUM (
'int', 'float', 'string', 'bool', 'json', 'uuid'
);
CREATE TABLE hierarchical_configuration_registry (
config_key VARCHAR(100) NOT NULL, -- 'DEFAULT_SEVERITY_SCALE', 'DEFAULT_TEMP_UNIT'
config_type configuration_data_type NOT NULL,-- 'int', 'float', 'string', 'bool', 'json'
config_value TEXT NOT NULL, -- The raw string value to pass to the type caster
-- Cascading Scoping Matrix Tiers (All nullable to allow fallback routing execution)
jurisdiction_id INTEGER REFERENCES jurisdictions(jurisdiction_id) ON DELETE CASCADE,
facility_id INTEGER REFERENCES facilities(facility_id) ON DELETE CASCADE,
specialty_id INTEGER REFERENCES specialties(specialty_id) ON DELETE CASCADE,
description TEXT,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
-- Prevents duplicate rules at the exact same architectural resolution layer
CONSTRAINT uq_scoped_config_coordinate UNIQUE (
config_key, jurisdiction_id, facility_id, specialty_id
)
);
-- Index optimized for the cascading compiler fallback matching engine
CREATE INDEX idx_config_inheritance_speed ON hierarchical_configuration_registry (
config_key, specialty_id, facility_id, jurisdiction_id
);
-- ==========================================
-- 1. TEMPLATE REGISTRY (Metadata Wrappers)
-- ==========================================
CREATE TABLE
note_templates (
template_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
template_code VARCHAR(100) NOT NULL UNIQUE,
-- 'T-CARDIO-SOAP-01', 'T-PEDS-HPI-02'
description TEXT,
specialty_id INTEGER REFERENCES specialties(specialty_id),
-- Optional domain restriction
created_at TIMESTAMP
WITH
TIME ZONE DEFAULT NOW()
);
-- ==========================================
-- 2. TEMPLATE VERSIONS (Timeline Control)
-- ==========================================
CREATE TABLE
template_versions (
version_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
template_id UUID REFERENCES note_templates(template_id) ON DELETE CASCADE,
semantic_version VARCHAR(20) NOT NULL,
-- '1.0.0', '1.1.0'
is_active BOOLEAN DEFAULT FALSE,
-- Controls runtime loading
created_at TIMESTAMP
WITH
TIME ZONE DEFAULT NOW(),
UNIQUE(template_id, semantic_version)
);
-- ==========================================
-- 3. TEMPLATE SLOTS (The Jinja Render Blocks)
-- ==========================================
CREATE TABLE
template_slots (
slot_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
language_id VARCHAR(5) DEFAULT 'en',
version_id UUID REFERENCES template_versions(version_id) ON DELETE CASCADE,
document_location VARCHAR(50) NOT NULL,
-- 'subjective', 'objective', 'assessment', 'plan', 'full_document', etc
slot_key VARCHAR(50) NOT NULL,
-- 'opening', 'continuing', 'closing', 'full_paragraph'
jinja_template_text TEXT NOT NULL,
-- The actual string rendering syntax
UNIQUE(version_id, slot_key)
);
CREATE TABLE
template_expression_matrix (
version_id UUID REFERENCES template_versions(version_id) ON DELETE CASCADE,
expression_id UUID REFERENCES custom_expressions(expression_id) ON DELETE CASCADE,
PRIMARY KEY (version_id, expression_id)
);
-- ==========================================
-- 1. MACRO REGISTRY
-- ==========================================
CREATE TABLE
macro_registry (
macro_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
personnel_id INTEGER REFERENCES personnel(personnel_id),
macro_name VARCHAR(100) NOT NULL,
-- 'severe_shortness_of_breath', 'high_fever', etc
macro_template TEXT NOT NULL,
-- The template string with variable placeholders, and variable delimiters, independent of parser syntax
created_at TIMESTAMP
WITH
TIME ZONE DEFAULT NOW(),
UNIQUE(macro_name)
);
-- ==========================================
-- 1. PARSER PROFILES
-- ==========================================
CREATE TABLE
parser_syntax_profiles (
profile_id UUID PRIMARY KEY,
personnel_id INTEGER REFERENCES personnel(personnel_id),
-- [TAGTOKEN]: Delimiter to identify the start of a tagged expression (e.g., '#drug', '#anatomy')
tag_token VARCHAR(5) DEFAULT '#'
-- [STATE_DELIMITER]: Delimiter identity a new state
state_delimiter VARCHAR(5) DEFAULT '||',
-- 1. [STATE_START] Outer Delimiter (e.g. '|' or '<' or '##')
state_start_delimiter VARCHAR(5) DEFAULT '|',
-- [STATE_END] Closing Delimiter (e.g. '|' or '>' or '##')
state_end_delimiter VARCHAR(5) DEFAULT '|',
-- '|' or '>' or '##', etc
-- 2. [COMMENT]: Comment tokens
comment_start_token VARCHAR(5) DEFAULT '//',
comment_end_token VARCHAR(5) DEFAULT ';',
-- 3. Macro Tokens (ex: ^macro($1, $2) -> @term; severity of $1, /set custom_vars{x=$2})
macro_start_token VARCHAR(5) DEFAULT '^',
-- [MACRO_PLACEHOLDER]: 'Triggers a macro to prefill text string and inputs'
macro_placeholder VARCHAR(5) DEFAULT '[__]',
-- 'Opens a variable fill block within the evaluated macro string if not defined'
-- 4. [VAR_START]: Variable Assignment tokens. Opens a variable evaluation block
variable_start_token VARCHAR(5) DEFAULT '{',
-- [VAR_END]: Closes a variable evaluation block
variable_end_token VARCHAR(5) DEFAULT '}',
-- [VAR_DELIMITER]: Delimiter between multiple variable assignments within the block
variable_delimiter VARCHAR(5) DEFAULT ',',
-- Delimiter between multiple variable assignments within the block
-- (name{x=10,y=True,z>5,a->{1,2,3, @SOB}, c={e,f,g}})
-- Ex: test{x=10,y=True} -> eval test{x=5} -> error; eval a=5 -> error
-- Does not need to be Turing Complete; does not perform mathematical operations on the RHS, meant for clincian expectations
---
---
-- Term Tokens (custom expressions or display names)
-- 5. [TERM_CODE]: '@@ICD-10#R06.02'
start_term_code_delimiter VARCHAR(5) DEFAULT '@@',
-- [TERM_DISPLAY]: '@#R06.02
start_term_display_delimiter VARCHAR(5) DEFAULT '@#',
-- [TERM_CODE_SEPARATOR]: Delimiter between the code system and the code in the inline specification (e.g., '@@SNOMED#123456')
start_term_code_separator VARCHAR(5) DEFAULT '#',
-- [TERM]: '~', '@' etc (@SOB, @Shortness of Breath, etc)
start_term_delimiter VARCHAR(5) DEFAULT '@',
-- [TERM_END]: Delimiter to signify the end of a term token (e.g., ';' or ',', ';;' etc)
end_term_delimiter VARCHAR(5) DEFAULT ';',
--
-- 6. [ATTRIBUTE]: Attribute Tokens (e.g. ',' or ';' )
attribute_delimiter VARCHAR(5) DEFAULT ',',
--
-- Checks if the profile is active
is_active BOOLEAN DEFAULT TRUE,
-- Constraint to prevent delimiter collisions that would break the parsing logic
CONSTRAINT chk_bulletproof_lexer_boundaries CHECK (
-- Protect global line blocks from colliding with inline node tags
state_delimiter <> state_start_delimiter
AND state_delimiter <> state_end_delimiter
-- Protect elements from matching core syntax tags
AND state_start_delimiter <> start_term_delimiter
AND variable_start_token <> state_start_delimiter
AND start_term_code_delimiter <> start_term_delimiter
AND start_term_display_delimiter <> start_term_delimiter
AND start_term_code_delimiter <> start_term_display_delimiter
-- Ensure variable assignment blocks do not collide with state blocks or term tags
AND variable_start_token <> state_start_delimiter
AND variable_end_token <> state_end_delimiter
-- Prevent comment wrappers from matching macro tags
AND comment_start_token <> macro_start_token
)
);
-- ==========================================================
-- 2. PARSER STOP WORDS
-- ==========================================================
CREATE TABLE
parser_stop_words (
stop_word_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- The literal token to strip during lexing (e.g., 'patient', 'reports', 'with')
word_token VARCHAR(100) NOT NULL,
-- Hierarchical Scoping Tiers (Cascading Nullable Foreign Keys)
jurisdiction_id INTEGER REFERENCES jurisdictions(jurisdiction_id) ON DELETE CASCADE,
facility_id INTEGER REFERENCES facilities(facility_id) ON DELETE CASCADE,
specialty_id INTEGER REFERENCES specialties(specialty_id) ON DELETE CASCADE,
personnel_id INTEGER REFERENCES personnel(personnel_id) ON DELETE CASCADE,
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP
WITH
TIME ZONE DEFAULT NOW(),
-- Enforce uniqueness of a stop word within a specific contextual silo
CONSTRAINT uq_stop_word_context UNIQUE (
word_token, jurisdiction_id, facility_id,
specialty_id, personnel_id
)
);
-- Indexing optimized for instant hash-table loading during IDE session initialization
CREATE INDEX
idx_stop_words_session_load ON parser_stop_words (
personnel_id, specialty_id, facility_id,
jurisdiction_id
)
WHERE
is_active = TRUE;
-- ==========================================================
-- 1. THE IDENTITY MATRIX
-- ==========================================================
CREATE TYPE organism_domain AS ENUM ('human', 'animal', 'plant'); CREATE TYPE agent_lifecycle_status AS ENUM (
'active', 'deceased', 'inactive_archived'
); CREATE TYPE gender_classification AS ENUM (
'male', 'female', 'undetermined',
'not_applicable'
); CREATE TYPE date_precision_tier AS ENUM (
'exact_timestamp', 'day', 'month',
'year', 'estimated_epoch'
); CREATE TYPE ledger_mutation_operation AS ENUM (
'add', 'update', 'remove', 'merge',
'branch', 'archive'
); CREATE TYPE clinical_doc_section AS ENUM (
'initial_context', 'subjective',
'objective', 'assessment', 'plan',
'other'
); CREATE TYPE clinical_workflow_stage AS ENUM (
'history_taking', 'observation_gathering',
'measurement_recording', 'assessment_reasoning',
'plan_formulation', 'intervention_ordering',
'disposition_planning', 'other'
);
CREATE TABLE
registry_agents (
agent_id VARCHAR(2048) PRIMARY KEY,
initial_state_id VARCHAR(2048) DEFAULT NULL,
organism_type organism_domain NOT NULL,
status agent_lifecycle_status NOT NULL DEFAULT 'active',
registration_timestamp TIMESTAMP
WITH
TIME ZONE NOT NULL DEFAULT NOW(),
created_at TIMESTAMP
WITH
TIME ZONE DEFAULT NOW()
);
CREATE INDEX
idx_agents_cohort_lookup ON registry_agents (organism_type, status);
CREATE TABLE
agent_demographics (
agent_id VARCHAR(2048) PRIMARY KEY REFERENCES registry_agents(agent_id) ON DELETE CASCADE,
administrative_gender gender_classification NOT NULL DEFAULT 'undetermined',
origination_date TIMESTAMP
WITH
TIME ZONE NOT NULL,
origination_precision date_precision_tier NOT NULL DEFAULT 'exact_timestamp',
is_origination_date_estimated BOOLEAN NOT NULL DEFAULT FALSE,
legal_name_json JSONB NOT NULL,
organism_attributes JSONB NOT NULL,
organism_type organism_domain NOT NULL,
FOREIGN KEY (agent_id, organism_type) REFERENCES registry_agents(agent_id, organism_type) ON DELETE CASCADE,
CONSTRAINT chk_strict_organism_payloads CHECK (
(
organism_type = 'plant'
AND organism_attributes ? 'taxonomy'
AND organism_attributes ? 'propagation_method'
)
OR (
organism_type IN ('human', 'animal')
AND administrative_gender IS NOT NULL
)
)
);
-- ==========================================================
-- 6. THE CENTRAL EVENT LEDGER LAYER
-- ==========================================================
CREATE TABLE
medical_event_ledger (
state_id VARCHAR(2048) PRIMARY KEY,
previous_state_id VARCHAR(2048) REFERENCES medical_event_ledger(state_id),
mutation_parent_ids VARCHAR(2048) [] DEFAULT '{}',
-- Tracks multi-parent histories (Merges)
operation ledger_mutation_operation NOT NULL,
-- Transaction Provenance
state_context TEXT,
state_timestamp_utc TIMESTAMP
WITH
TIME ZONE NOT NULL DEFAULT NOW(),
agent_id VARCHAR(2048) NOT NULL REFERENCES registry_agents(agent_id),
personnel_id INTEGER REFERENCES personnel(personnel_id),
facility_id INTEGER REFERENCES facilities(facility_id),
clinical_document_location clinical_doc_section NOT NULL DEFAULT 'other',
clinical_workflow_phase clinical_workflow_stage NOT NULL DEFAULT 'other',
state_metadata_session_variables JSONB DEFAULT NULL,
merge_resolution JSONB DEFAULT NULL,
static_context JSONB DEFAULT NULL,
temporal_context JSONB DEFAULT NULL,
-- Clinical Streams
assessment JSONB DEFAULT NULL,
vitals_measurement JSONB DEFAULT NULL,
observation JSONB DEFAULT NULL,
exposure_profile JSONB DEFAULT NULL,
device_diagnostic_report JSONB DEFAULT NULL,
clinical_evaluation_report JSONB DEFAULT NULL,
procedure_order JSONB DEFAULT NULL,
medication_order JSONB DEFAULT NULL,
insurance_cost_evaluation JSONB DEFAULT NULL,
clinical_location_followup JSONB DEFAULT NULL,
patient_refusal JSONB DEFAULT NULL,
-- ==========================================================
-- CONSTRAINT ENFORCEMENT AT THE DATABASE PORTAL
-- ==========================================================
-- Enforce that merge details exist if and only if the operation type is a merge
CONSTRAINT chk_merge_data_integrity CHECK (
(
operation = 'merge'
AND merge_resolution IS NOT NULL
)
OR (
operation <> 'merge'
AND merge_resolution IS NULL
)
),
-- Enforce that if the operation is an update, the previous_state_id must exist, mutation_parent_ids must not be empty
CONSTRAINT chk_update_requires_previous CHECK (
(
operation = 'update'
AND previous_state_id IS NOT NULL
AND array_length(mutation_parent_ids, 1) > 0
)
OR (operation <> 'update')
),
-- Enforce that if the operation is a remove, the previous_state_id must exist, mutation_parent_ids must not be empty
CONSTRAINT chk_remove_requires_previous_and_null_context CHECK (
(
operation = 'remove'
AND previous_state_id IS NOT NULL
AND array_length(mutation_parent_ids, 1) > 0
)
OR (operation <> 'remove')
)
);
CREATE INDEX
idx_ledger_agent_timeline ON medical_event_ledger (
agent_id, state_timestamp_utc DESC
);
ALTER TABLE
registry_agents
ADD
CONSTRAINT fk_initial_state_ledger FOREIGN KEY (initial_state_id) REFERENCES medical_event_ledger(state_id);
|