Kulcare Docs
General

Schema Architecture Overview

Purpose: Visual architecture and relationships between database schemas

Schema Landscape

+-----------------------------------------------------------------------------+
|                            KULCARE DATABASE                                 |
+-----------------------------------------------------------------------------+
|                                                                             |
|  +-----------------------------------------------------------------------+  |
|  |  REFERENCE SCHEMA                                                    |  |
|  |  (Global - No tenant_id)                                             |  |
|  |                                                                       |  |
|  |  +-------------+  +-------------+  +-------------+  +-------------+  |  |
|  |  | specialties |  | drugs       |  | lab_tests   |  | procedures  |  |  |
|  |  +-------------+  +-------------+  +-------------+  +-------------+  |  |
|  |  +-------------+  +-------------+  +-------------+  +-------------+  |  |
|  |  | drug_       |  | drug_       |  | drug_       |  | drug_cond_  |  |  |
|  |  | manufacturers| | interactions|  | alternatives|  | associations|  |  |
|  |  +-------------+  +-------------+  +-------------+  +-------------+  |  |
|  |  +-------------+  +-------------+  +-------------+  +-------------+  |  |
|  |  | icd_codes   |  | snomed_     |  | countries   |  | facility_   |  |  |
|  |  |             |  | concepts    |  | states      |  | types       |  |  |
|  |  +-------------+  +-------------+  +-------------+  +-------------+  |  |
|  +-----------------------------------------------------------------------+  |
|                                      |                                      |
|                                      v                                      |
|  +-----------------------------------------------------------------------+  |
|  |  IDENTITY SCHEMA                                                     |  |
|  |  (Who provides what, where)                                         |  |
|  |                                                                       |  |
|  |  +-------------+       +----------------+       +---------------+    |  |
|  |  |   tenants   |------>| organizations  |------>|  facilities   |    |  |
|  |  +-------------+       +----------------+       +---------------+    |  |
|  |         |                      |                       |             |  |
|  |         v                      v                       v             |  |
|  |  +-------------+       +----------------+       +---------------+    |  |
|  |  |    users    |------>| practitioners  |------>| practitioner_ |    |  |
|  |  +-------------+       +----------------+       | roles         |    |  |
|  |                                                 +---------------+    |  |
|  |  +----------------+    +----------------+       +---------------+    |  |
|  |  | vendors        |    | healthcare_    |       | service_      |    |  |
|  |  | (unlicensed)   |    | services       |       | packages      |    |  |
|  |  +----------------+    +----------------+       +---------------+    |  |
|  +-----------------------------------------------------------------------+  |
|           |                       |                       |                 |
|           |                       |                       |                 |
|           v                       v                       v                 |
|  +---------------+  +---------------+  +---------------+  +---------------+ |
|  |   CLINICAL    |  |    BILLING    |  |    GROWTH     |  |    CONNECT    | |
|  |    SCHEMA     |  |    SCHEMA     |  |    SCHEMA     |  |    SCHEMA     | |
|  +---------------+  +---------------+  +---------------+  +---------------+ |
|  | patients      |  | invoices      |  | campaigns     |  | professional_ | |
|  | encounters    |  | invoice_items |  | leads         |  | profiles      | |
|  | episodes_of_  |  | payments      |  | communications|  | connections   | |
|  | care          |  | subscriptions |  |               |  | job_postings  | |
|  | conditions    |  | insurance_    |  |               |  | applications  | |
|  | observations  |  | payers        |  |               |  | messages      | |
|  | medication_   |  | patient_      |  |               |  | posts         | |
|  | requests      |  | policies      |  |               |  |               | |
|  | care_plans    |  | insurance_    |  |               |  |               | |
|  | goals         |  | claims        |  |               |  |               | |
|  | transcription_|  |               |  |               |  |               | |
|  | sessions      |  |               |  |               |  |               | |
|  | ai_suggestions|  |               |  |               |  |               | |
|  +---------------+  +---------------+  +---------------+  +---------------+ |
|           |                       |                       |                 |
|           +-------------------------------------------+   |                 |
|                                   |                   |   |                 |
|                                   v                   v   v                 |
|  +-----------------------------------------------------------------------+  |
|  |  ENTERPRISE SCHEMA (Cross-tenant)   |  INTEGRATION  |  AUDIT SCHEMA  |  |
|  +-------------------------------------+---------------+----------------+  |
|  | employers                           | abdm_records  | activity_logs  |  |
|  | employer_employees                  | webhook_      | phi_access_    |  |
|  | benefit_plans                       | events        | logs           |  |
|  | employee_enrollments                | api_logs      | llm_call_logs  |  |
|  | empaneled_providers                 |               | document_audit |  |
|  | wellness_programs                   |               | _logs          |  |
|  +-------------------------------------+---------------+----------------+  |
|                                                                             |
+-----------------------------------------------------------------------------+

+-----------------------------------------------------------------------------+
|                       PHARMA DATABASE (Separate)                            |
+-----------------------------------------------------------------------------+
|                                                                             |
|  +-----------------------------------------------------------------------+  |
|  |  PHARMA SCHEMA                |  TRIALS SCHEMA    |  COMPLIANCE       |  |
|  +-------------------------------+-------------------+-------------------+  |
|  | pharma_companies              | clinical_trials   | disclosure_       |  |
|  | pharma_users                  | trial_sites       | records           |  |
|  | medical_reps                  | trial_            | gift_tracking     |  |
|  | campaigns                     | investigators     | pharma_audit_     |  |
|  | campaign_targets              | trial_            | logs              |  |
|  | drug_promotions               | enrollments       |                   |  |
|  | doctor_engagements            |                   |                   |  |
|  +-------------------------------+-------------------+-------------------+  |
|                                                                             |
|  Integration: API-based sync with Kulcare DB (practitioners, drugs)         |
|                                                                             |
+-----------------------------------------------------------------------------+

Schema Purposes and Boundaries

Reference Schema

Purpose: Global lookup tables shared across all tenants

CharacteristicValue
Tenant ScopedNo
RLS EnabledNo
Data SourcePlatform-managed, external standards
Update FrequencyRare (catalog updates, code updates)

Contains:

  • Medical coding (ICD, SNOMED, LOINC)
  • Drug system (comprehensive):
    • Drug catalog with multi-country support (IN, US, AE)
    • DrugManufacturer (manufacturer registry)
    • DrugInteraction (drug-drug interaction database)
    • DrugAlternative (therapeutic substitutes)
    • DrugConditionAssociation (AI: drug-condition mapping)
    • DrugAllergyGroup (AI: cross-reactivity patterns)
  • Procedure catalog
  • Specialty hierarchy
  • Geographic data
  • Facility type definitions

Identity Schema

Purpose: Who provides what, where -- organizational foundation for tenants, providers, facilities, and their service offerings

CharacteristicValue
Tenant ScopedPartial (some global like users)
RLS EnabledYes (for tenant-scoped tables)
Core EntityFacility (replaces Clinic)
Domain ModelMaps to FHIR Administration module

Contains:

  • Who: Users, Practitioners (licensed providers), Vendors (unlicensed providers)
  • Where: Tenants, Organizations, Facilities, Facility Locations
  • What: Healthcare Services, Service Packages, Package Components
  • Relationships: Practitioner Roles, Facility-Vendor contracts, User Memberships
  • Configuration: AI Settings (facility and practitioner level)

Key Relationships:

Tenant
  |
  +-- Organizations (1:N)
        |
        +-- Facilities (1:N)
              |
              +-- Locations (1:N)
              +-- Practitioner Roles (N:M with Practitioners)
              +-- Healthcare Services (1:N)

Clinical Schema

Purpose: Patient care, clinical documentation, AI-assisted care

CharacteristicValue
Tenant ScopedYes (all tables)
RLS EnabledYes
FHIR AlignedYes (core resources)

Contains:

  • Patients
  • Patient-Facility links
  • Episodes of Care
  • Encounters
  • Encounter Participants
  • Conditions
  • Observations
  • Medication Requests
  • Care Plans
  • Goals
  • Service Requests
  • Diagnostic Reports
  • Appointments
  • Transcription Sessions
  • AI Suggestions

Key Relationships:

Patient
  |
  +-- Episodes of Care (1:N)
  |     |
  |     +-- Encounters (1:N)
  |           |
  |           +-- Participants (N:M with Practitioners)
  |           +-- Observations (1:N)
  |           +-- Medication Requests (1:N)
  |           +-- AI Suggestions (1:N)
  |
  +-- Conditions (1:N)
  +-- Care Plans (1:N)
  +-- Goals (1:N)

Billing Schema

Purpose: Financial transactions, subscriptions, insurance, drug formularies

CharacteristicValue
Tenant ScopedYes
RLS EnabledYes
Currency SupportMulti-currency (INR, USD, AED)

Contains:

  • Invoices
  • Invoice Items
  • Payments
  • Subscriptions
  • Insurance Payers
  • Patient Policies
  • Insurance Claims
  • Claim Line Items
  • Prior Authorizations
  • Drug Formularies (tenant-scoped insurance coverage for drugs)

Growth Schema

Purpose: Marketing, lead management, communications

CharacteristicValue
Tenant ScopedYes
RLS EnabledYes

Contains:

  • Campaigns
  • Leads
  • Communications (email, SMS, WhatsApp)

Connect Schema

Purpose: Professional networking, job board

CharacteristicValue
Tenant ScopedNo (cross-tenant by design)
RLS EnabledNo
VisibilityProfile-level permissions

Contains:

  • Professional Profiles
  • Experiences, Education, Certifications
  • Skills, Publications, Awards
  • Connections, Follows
  • Recommendations, Endorsements
  • Job Postings, Applications
  • Conversations, Messages
  • Posts, Comments

Key Relationships:

Practitioner (identity schema)
  |
  +-- Professional Profile (1:1)
        |
        +-- Experiences (1:N)
        +-- Connections (N:M)
        +-- Job Applications (1:N)
        +-- Posts (1:N)

Integration Schema

Purpose: External service integrations

CharacteristicValue
Tenant ScopedYes
RLS EnabledYes

Contains:

  • ABDM Records (India health data exchange)
  • Webhook Events
  • API Logs

Audit Schema

Purpose: Compliance, activity tracking, AI audit

CharacteristicValue
Tenant ScopedYes
RLS EnabledYes
RetentionLong-term (regulatory requirements)

Contains:

  • Activity Logs (general actions)
  • PHI Access Logs (HIPAA compliance)
  • LLM Call Logs (AI audit trail)
  • Document Audit Logs (clinical document changes)

Enterprise Schema

Purpose: Employer healthcare benefits, ICHRA plans, empanelment

CharacteristicValue
Tenant ScopedNo (cross-tenant by design)
RLS EnabledNo
VisibilityEmployer-level permissions

Enterprises are B2B customers of healthcare facilities. They provide benefits to employees who are patients at those facilities. This schema operates cross-tenant, similar to Connect.

Contains:

  • Employers (company entities)
  • Employer Employees (links to clinical.patients)
  • Employer Facilities (contracted facilities)
  • Benefit Plans (ICHRA-style plans)
  • Employee Enrollments
  • Empaneled Providers (negotiated rates)
  • Wellness Programs
  • Program Registrations

Key Relationships:

Employer (cross-tenant)
  |
  +-- Employer Facilities (N:M with identity.facilities)
  |
  +-- Employer Employees (1:N)
  |     |
  |     +-- Patient Link (1:1 with clinical.patients, cross-tenant)
  |     +-- Enrollments (1:N with Benefit Plans)
  |
  +-- Benefit Plans (1:N)
  |
  +-- Empaneled Providers (N:M with identity.practitioners)
  |
  +-- Wellness Programs (1:N)

Pharma Database (Separate)

Purpose: Pharmaceutical company relations, campaigns, clinical trials

CharacteristicValue
DatabaseSeparate PostgreSQL database
Multi-TenancyPharma company as tenant
IntegrationAPI-based sync with Kulcare DB

The Pharma database is intentionally separate due to:

  • Different tenant model (pharma companies, not facilities)
  • B2B marketing focus vs patient care
  • Clinical trial isolation (FDA/DCGI compliance)
  • Conflict of interest tracking (Sunshine Act)

Contains:

  • Pharma Schema: Companies, users, medical reps, campaigns, drug promotions
  • Trials Schema: Clinical trials, sites, investigators, enrollments (anonymized)
  • Compliance Schema: Disclosure records, gift tracking, audit logs

Integration Points:

Kulcare DB                    Pharma DB
-----------                   ---------
identity.practitioners -----> practitioners_sync (read-only)
reference.drugs -----------> drugs_sync (read-only)

See Pharma Database for detailed documentation.


Cross-Schema Relationships

Identity to Clinical

identity.practitioners ----> clinical.encounter_participants
identity.facilities -------> clinical.patients (via patient_facilities)
identity.healthcare_services -> clinical.appointments

Clinical to Billing

clinical.patients ---------> billing.invoices
clinical.encounters -------> billing.invoice_items

Identity to Connect

identity.practitioners ----> connect.professional_profiles (1:1)
identity.facilities -------> connect.job_postings

Clinical to Audit

clinical.encounters -------> audit.activity_logs
clinical.patients ---------> audit.phi_access_logs
clinical.ai_suggestions ---> audit.llm_call_logs

Enterprise to Clinical/Identity

enterprise.employer_employees ----> clinical.patients (cross-tenant link)
enterprise.employer_facilities ---> identity.facilities (N:M)
enterprise.empaneled_providers ---> identity.practitioners (N:M)

Billing to Enterprise

billing.insurance_claims ------> enterprise.employee_enrollments
billing.patient_policies ------> enterprise.benefit_plans

Row-Level Security (RLS) Implementation

See docs/guides/developer/row-level-security.md for the full RLS model, including the GUC lifecycle, the RlsContext API, the table-classification rule, and case studies.

Tenant Context Pattern

-- Set tenant context on each request (session-scoped: local=false)
SELECT set_config('app.current_tenant_id', 'tenant-uuid', false);

-- RLS policy on tenant-scoped tables — safe form
CREATE POLICY tenant_isolation ON clinical.patients
  FOR ALL
  USING (
    tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid
  )
  WITH CHECK (
    tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid
  );

The , true second arg to current_setting makes the lookup missing-OK; the NULLIF(..., '') turns the empty-string default into NULL so tenant_id = NULL evaluates to NULL (not true), filtering all rows safely. Without these, an unset GUC raises unrecognized configuration parameter and a missing-context read becomes a 500 instead of a zero-row result. Every tenant policy in this codebase should use this exact shape.

Migrations enabling RLS should always pair ENABLE with FORCE:

ALTER TABLE identity.example ENABLE ROW LEVEL SECURITY;
ALTER TABLE identity.example FORCE ROW LEVEL SECURITY;

ENABLE alone leaves the table owner bypassing RLS, which is invisible until table ownership shifts. See row-level-security.md §2.5.

RLS Coverage

Schema / TableRLS EnabledPosture
referenceNoGlobal lookup data
identity.tenantsNoIS the tenant
identity.usersNoCross-tenant entity
identity.practitionersNoCross-tenant entity
identity.user_memberships, sessions, profile_switches, refresh_tokens, devicesNoUser↔tenant bridges — see row-level-security.md §2.4
identity.organizations, facilities, facility_locations, practitioner_rolesYes (forced)Tenant resources
identity.facility_settings, facility_ai_settings, practitioner_ai_settingsYes (forced)Tenant resources
clinical.*YesTenant isolation
billing.*YesTenant isolation
growth.*YesTenant isolation
connect.*NoCross-tenant by design — app-layer Pundit
enterprise.*NoEmployer-based access
integration.*YesTenant isolation
audit.*YesTenant isolation
federation.*NoFacility-based access
notifications.*NoCross-tenant user inbox — app-layer scope by recipient_user_id

Entity Count by Schema

SchemaEstimated TablesNotes
reference17+5 for expanded drug system (DrugManufacturer, DrugInteraction, DrugAlternative, DrugConditionAssociation, DrugAllergyGroup)
identity14+1 for FacilityOfflineSettings
clinical22+2 for OfflinePrescription, OfflineEncounter
billing11+1 for DrugFormulary (tenant-scoped insurance formularies)
growth4
connect15
enterprise10
integration4
audit7+3 for OfflineSyncLog, OfflineDevice, SyncBatch
federation12Master Patient Index, sync tracking, feature config
Kulcare DB Total~116
Pharma DB~20

Compare to current: ~501 tables

Offline mode adds 6 tables for sync tracking and device management. See Offline Mode.

Federation schema adds 12 tables for on-premise sync and patient identity. See Federated Deployment.


Schema Dependencies

reference (independent)
    |
    v
identity (depends on reference)
    |
    +---> clinical (depends on identity, reference)
    |
    +---> billing (depends on identity, clinical, enterprise)
    |
    +---> growth (depends on identity)
    |
    +---> connect (depends on identity)
    |
    +---> enterprise (depends on identity, clinical - cross-tenant)
    |
    +---> integration (depends on identity, clinical)
    |
    +---> audit (depends on all schemas - logging)

pharma_db (separate database)
    |
    +---> API sync from identity.practitioners
    +---> API sync from reference.drugs

Migration Sequence

If migrating from current to new schema:

  1. reference - Create first (no dependencies)
  2. identity - Create second (foundation)
  3. clinical - Core clinical data
  4. billing - Financial data
  5. growth - Marketing data
  6. connect - Professional networking
  7. enterprise - Employer benefits (after clinical for patient linkage)
  8. integration - External integrations
  9. audit - Logging (can be parallel with others)
  10. pharma_db - Separate database (can be parallel)

On this page