Skip to content

fix: add facility id column to i_ben_flow_outreach table#129

Merged
paras-dba merged 6 commits into
mainfrom
vb/db
May 27, 2026
Merged

fix: add facility id column to i_ben_flow_outreach table#129
paras-dba merged 6 commits into
mainfrom
vb/db

Conversation

@vishwab1

@vishwab1 vishwab1 commented May 27, 2026

Copy link
Copy Markdown
Member

📋 Description

JIRA ID: AMM-2206

Please provide a summary of the change and the motivation behind it. Include relevant context and details.


✅ Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • New feature (non-breaking change which adds functionality)
  • 🔥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 🛠 Refactor (change that is neither a fix nor a new feature)
  • ⚙️ Config change (configuration file or build script updates)
  • 📚 Documentation (updates to docs or readme)
  • 🧪 Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • 🚀 Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • Chores
    • Enhanced facility hierarchy structure to support multi-level organization across states, districts, blocks, and villages
    • Implemented facility-village mapping for improved geographic data management
    • Added supervisor-to-ASHA worker relationship tracking capabilities
    • Extended outreach records with facility identification for better data organization

Review Change Stack

vishwab1 and others added 5 commits March 30, 2026 13:01
…lter

Changed isoutbound filter from "is false" to "IS NOT TRUE" in
Pr_104BeneficiaryReport stored procedure to include NULL records.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented May 27, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds database migrations to establish a facility hierarchy schema. The first migration introduces a hierarchy level reference table, extends facility and facility-type tables with state/district/block/village hierarchy columns, creates facility-to-location and ASHA-to-supervisor mapping tables, and scopes user service roles to facilities and locations. The second migration adds facility tracking to the outreach flow table.

Changes

Facility Hierarchy Schema and Integration

Layer / File(s) Summary
Facility Hierarchy Reference Table
src/main/resources/db/migration/dbiemr/V64_Facility_Hierarchy.sql
Creates m_facility_level table with level metadata, audit columns, soft-delete flag, and unique constraint on LevelValue.
Facility Type and Facility Hierarchy Extensions
src/main/resources/db/migration/dbiemr/V64_Facility_Hierarchy.sql
Extends m_facilitytype with RuralUrban, LevelValue, and StateID columns and foreign keys to m_facility_level and m_state. Extends m_facility with StateID, DistrictID, BlockID, MainVillageID, RuralUrban, and ParentFacilityID columns with corresponding foreign key constraints for hierarchical and location relationships.
Facility Association Tables
src/main/resources/db/migration/dbiemr/V64_Facility_Hierarchy.sql
Creates facility_village_mapping table to link facilities to district branches. Creates asha_supervisor_mapping table to map ASHA users to supervisor users at specific facilities, both with audit and soft-delete support.
User Service Role Location Scoping
src/main/resources/db/migration/dbiemr/V64_Facility_Hierarchy.sql
Extends m_UserServiceRoleMapping with nullable FacilityID, StateID, and DistrictID columns and foreign keys to enable scoping user service roles to specific facilities and locations.
Outreach Flow Facility Tracking
src/main/resources/db/migration/dbiemr/V81__i_ben_flow_outreach_facilityID.sql
Conditionally adds nullable facilityID column to i_ben_flow_outreach table using information_schema inspection for idempotent deployment.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 A rabbit hops through schemas grand,
Where facilities now understand
Their place within a hierarchy,
With states and districts, nary a fret to see—
From ASHA supervisors to outreach flows,
The facility threads through all that grows! 🌳✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'fix: add facility id column to i_ben_flow_outreach table' directly matches the primary change in the changeset, which is the V81__i_ben_flow_outreach_facilityID.sql migration script adding facilityID column.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch vb/db

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

…as V64__Facility_Hierarchy.sql

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/main/resources/db/migration/dbiemr/V81__i_ben_flow_outreach_facilityID.sql (1)

15-15: ⚡ Quick win

Consider indexing facilityID for common filter/join paths.

If outreach reports will query by facility, indexing facilityID will prevent full scans as data grows.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/resources/db/migration/dbiemr/V81__i_ben_flow_outreach_facilityID.sql`
at line 15, The migration adds facilityID to table i_ben_flow_outreach but
doesn’t create an index; update V81__i_ben_flow_outreach_facilityID.sql to
create an index on column facilityID (e.g., add a CREATE INDEX / ALTER TABLE ...
ADD INDEX statement named something like idx_i_ben_flow_outreach_facilityID)
immediately after the ALTER TABLE so common filter/join paths on
i_ben_flow_outreach.facilityID avoid full table scans.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/main/resources/db/migration/dbiemr/V64_Facility_Hierarchy.sql`:
- Around line 136-139: Change the mapping FK columns to be non-nullable: update
the column definitions for supervisorUserID, ashaUserID, and facilityID in this
migration (V64_Facility_Hierarchy.sql) from INT to INT NOT NULL so relationship
rows cannot be created with NULL keys; ensure any existing seed data in this
migration satisfies the NOT NULL constraint before applying (or add appropriate
DEFAULT/cleanup steps) and keep the deleted BOOLEAN DEFAULT FALSE line as-is.

In
`@src/main/resources/db/migration/dbiemr/V81__i_ben_flow_outreach_facilityID.sql`:
- Around line 1-3: Remove the hardcoded "USE db_iemr;" and make the migration
schema-agnostic by relying on the dynamic database name already captured by "SET
`@dbname` = DATABASE();" (or a migration parameter), then update any subsequent
object references in this script to use the `@dbname` variable or unqualified
names so the migration runs against the current connection's schema instead of
forcing db_iemr.
- Around line 13-21: The migration adds facilityID to i_ben_flow_outreach but
does not add a foreign key; modify the IF branch that runs when `@col_exists` = 0
so the generated SQL both adds the column and adds a foreign key constraint
referencing m_facility(FacilityID) (e.g., ALTER TABLE i_ben_flow_outreach ADD
COLUMN facilityID INT NULL, ADD CONSTRAINT fk_i_ben_flow_outreach_facilityID
FOREIGN KEY (facilityID) REFERENCES m_facility(FacilityID)); ensure the prepared
statement uses that combined ALTER and choose a clear constraint name
(fk_i_ben_flow_outreach_facilityID) and keep the existing behavior when the
column already exists.

---

Nitpick comments:
In
`@src/main/resources/db/migration/dbiemr/V81__i_ben_flow_outreach_facilityID.sql`:
- Line 15: The migration adds facilityID to table i_ben_flow_outreach but
doesn’t create an index; update V81__i_ben_flow_outreach_facilityID.sql to
create an index on column facilityID (e.g., add a CREATE INDEX / ALTER TABLE ...
ADD INDEX statement named something like idx_i_ben_flow_outreach_facilityID)
immediately after the ALTER TABLE so common filter/join paths on
i_ben_flow_outreach.facilityID avoid full table scans.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: adf09e23-725c-4317-9234-11b42458b4bf

📥 Commits

Reviewing files that changed from the base of the PR and between dfe9363 and f8ce7a7.

📒 Files selected for processing (2)
  • src/main/resources/db/migration/dbiemr/V64_Facility_Hierarchy.sql
  • src/main/resources/db/migration/dbiemr/V81__i_ben_flow_outreach_facilityID.sql

Comment on lines +136 to +139
supervisorUserID INT,
ashaUserID INT,
facilityID INT,
deleted BOOLEAN DEFAULT FALSE,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make mapping foreign-key columns non-nullable.

Line 136-139 allows supervisorUserID, ashaUserID, and facilityID to be NULL, which permits relationship rows that are not valid mappings.

Suggested fix
 CREATE TABLE IF NOT EXISTS asha_supervisor_mapping (
   id BIGINT AUTO_INCREMENT PRIMARY KEY,
-  supervisorUserID INT,
-  ashaUserID INT,
-  facilityID INT,
+  supervisorUserID INT NOT NULL,
+  ashaUserID INT NOT NULL,
+  facilityID INT NOT NULL,
   deleted BOOLEAN DEFAULT FALSE,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/resources/db/migration/dbiemr/V64_Facility_Hierarchy.sql` around
lines 136 - 139, Change the mapping FK columns to be non-nullable: update the
column definitions for supervisorUserID, ashaUserID, and facilityID in this
migration (V64_Facility_Hierarchy.sql) from INT to INT NOT NULL so relationship
rows cannot be created with NULL keys; ensure any existing seed data in this
migration satisfies the NOT NULL constraint before applying (or add appropriate
DEFAULT/cleanup steps) and keep the deleted BOOLEAN DEFAULT FALSE line as-is.

Comment on lines +13 to +21
SET @sql = IF(
@col_exists = 0,
'ALTER TABLE i_ben_flow_outreach ADD COLUMN facilityID INT NULL',
'SELECT "Column facilityID already exists"'
);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add a foreign key for facilityID to preserve referential integrity.

Line 15 adds facilityID but no FK to m_facility(FacilityID), so invalid facility references can be inserted.

Suggested fix
 SET `@sql` = IF(
     `@col_exists` = 0,
     'ALTER TABLE i_ben_flow_outreach ADD COLUMN facilityID INT NULL',
     'SELECT "Column facilityID already exists"'
 );
 
 PREPARE stmt FROM `@sql`;
 EXECUTE stmt;
 DEALLOCATE PREPARE stmt;
+
+SET `@fk_exists` = (
+    SELECT COUNT(*)
+    FROM information_schema.TABLE_CONSTRAINTS
+    WHERE TABLE_SCHEMA = `@dbname`
+      AND TABLE_NAME = 'i_ben_flow_outreach'
+      AND CONSTRAINT_NAME = 'fk_ibfo_facility'
+);
+
+SET `@sql` = IF(
+    `@fk_exists` = 0,
+    'ALTER TABLE i_ben_flow_outreach ADD CONSTRAINT fk_ibfo_facility FOREIGN KEY (facilityID) REFERENCES m_facility(FacilityID)',
+    'SELECT "FK fk_ibfo_facility already exists"'
+);
+
+PREPARE stmt FROM `@sql`;
+EXECUTE stmt;
+DEALLOCATE PREPARE stmt;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
SET @sql = IF(
@col_exists = 0,
'ALTER TABLE i_ben_flow_outreach ADD COLUMN facilityID INT NULL',
'SELECT "Column facilityID already exists"'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET `@sql` = IF(
`@col_exists` = 0,
'ALTER TABLE i_ben_flow_outreach ADD COLUMN facilityID INT NULL',
'SELECT "Column facilityID already exists"'
);
PREPARE stmt FROM `@sql`;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET `@fk_exists` = (
SELECT COUNT(*)
FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = `@dbname`
AND TABLE_NAME = 'i_ben_flow_outreach'
AND CONSTRAINT_NAME = 'fk_ibfo_facility'
);
SET `@sql` = IF(
`@fk_exists` = 0,
'ALTER TABLE i_ben_flow_outreach ADD CONSTRAINT fk_ibfo_facility FOREIGN KEY (facilityID) REFERENCES m_facility(FacilityID)',
'SELECT "FK fk_ibfo_facility already exists"'
);
PREPARE stmt FROM `@sql`;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/resources/db/migration/dbiemr/V81__i_ben_flow_outreach_facilityID.sql`
around lines 13 - 21, The migration adds facilityID to i_ben_flow_outreach but
does not add a foreign key; modify the IF branch that runs when `@col_exists` = 0
so the generated SQL both adds the column and adds a foreign key constraint
referencing m_facility(FacilityID) (e.g., ALTER TABLE i_ben_flow_outreach ADD
COLUMN facilityID INT NULL, ADD CONSTRAINT fk_i_ben_flow_outreach_facilityID
FOREIGN KEY (facilityID) REFERENCES m_facility(FacilityID)); ensure the prepared
statement uses that combined ALTER and choose a clear constraint name
(fk_i_ben_flow_outreach_facilityID) and keep the existing behavior when the
column already exists.

@paras-dba paras-dba merged commit 5ac862a into main May 27, 2026
8 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants