-
Notifications
You must be signed in to change notification settings - Fork 116
Fix/missing profile foreign keys #142
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Fix/missing profile foreign keys #142
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. 📝 WalkthroughWalkthroughAdds a /health endpoint, introduces a Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: defaults Review profile: CHILL Plan: Pro 📒 Files selected for processing (5)
✅ Files skipped from review due to trivial changes (1)
🧰 Additional context used🪛 Ruff (0.14.10)Backend/app.py192-192: Possible binding to all interfaces (S104) 🔇 Additional comments (7)
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. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
Backend/schema.sql (1)
50-61: Moveprofiletable creation before dependent tables.The
profiletable is created afterappointments,tasks, and other tables that will reference it. For the foreign key relationships to work correctly (especially withNOT NULLconstraints),profileshould be created first.🔎 Suggested reordering
Move the
DROP TABLE IF EXISTS profileandCREATE TABLE IF NOT EXISTS profileblock to the top of the file, before any tables that reference it.Frontend/ios/BabyNest/PrivacyInfo.xcprivacy (1)
1-45: Major inconsistency: Frontend privacy changes in a backend-only PR.The PR objectives explicitly state this is a backend/database change to add
profile_idforeign keys with "No frontend or visual changes", yet this iOS privacy configuration file is completely unrelated to database schema modifications. This file belongs in a separate PR focused on iOS privacy compliance.Either:
- This file was included by mistake, or
- The PR has undocumented scope creep
Please confirm whether these iOS privacy declarations should be part of this PR or moved to a separate frontend-focused PR.
🧹 Nitpick comments (1)
Backend/app.py (1)
189-190: Avoid hardcodeddebug=Trueand consider environment-based configuration.As flagged by static analysis,
debug=Trueexposes the Werkzeug debugger which can leak sensitive information and allow arbitrary code execution. While acceptable for local development, this should be disabled in production.Consider using environment variables for configuration:
🔎 Proposed fix
+import os + if __name__ == '__main__': - app.run(host='0.0.0.0', port=5001, debug=True) + debug_mode = os.environ.get('FLASK_DEBUG', 'false').lower() == 'true' + port = int(os.environ.get('PORT', 5001)) + app.run(host='0.0.0.0', port=port, debug=debug_mode)
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (3)
.DS_Storeis excluded by!**/.DS_StoreFrontend/ios/Podfile.lockis excluded by!**/*.lockFrontend/package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (9)
.gitignoreBackend/app.pyBackend/cache/context_default.jsonBackend/db/chromadb/chroma.sqlite3Backend/schema.sqlFrontend/.envFrontend/android/gradlewFrontend/ios/BabyNest/PrivacyInfo.xcprivacyFrontend/src/Screens/SettingsScreen.jsx
🧰 Additional context used
🪛 ast-grep (0.40.3)
Backend/app.py
[warning] 189-189: Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.
Context: app.run(host='0.0.0.0', port=5001, debug=True)
Note: [CWE-489] Active Debug Code. [REFERENCES]
- https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/
(debug-enabled-python)
🪛 Ruff (0.14.10)
Backend/app.py
190-190: Possible binding to all interfaces
(S104)
190-190: Use of debug=True in Flask app detected
(S201)
🔇 Additional comments (3)
Frontend/.env (1)
1-1:localhostwon't work for physical device testing.Using
localhostin a React Native app means the app can only communicate with the backend when running on a simulator/emulator on the same machine. Physical devices cannot resolvelocalhostto the development machine's IP.Consider using an environment variable or the machine's local IP address (e.g.,
192.168.x.x) for device testing, or document that this configuration is simulator-only.Backend/app.py (1)
185-188: LGTM!Simple health check endpoint that returns a JSON status - useful for container orchestration and monitoring.
Frontend/ios/BabyNest/PrivacyInfo.xcprivacy (1)
9-9: All privacy reason codes in the manifest are valid and current per Apple's official Privacy Manifest documentation (TN3183):
- 35F9.1 (SystemBootTime) ✓
- CA92.1 (UserDefaults) ✓
- C617.1 (FileTimestamp) ✓
- 85F4.1 (DiskSpace) ✓
The codebase complies with Apple's latest privacy manifest requirements. No updates needed.
Backend/schema.sql
Outdated
| ALTER TABLE appointments | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE tasks | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE blood_pressure_logs | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE discharge_logs | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_weight | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_medicine | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_symptoms | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
profile_id columns are nullable, but Issue #141 requires NOT NULL.
The linked issue explicitly states the expected behavior: profile_id INTEGER NOT NULL. The current ALTER TABLE statements add nullable columns, which still allows orphan records.
SQLite's ALTER TABLE ADD COLUMN cannot add a NOT NULL constraint without a default value. For a fresh schema, consider defining profile_id directly in the CREATE TABLE statements instead of using ALTER TABLE:
🔎 Proposed approach - define profile_id in CREATE TABLE
CREATE TABLE IF NOT EXISTS appointments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT,
appointment_date TEXT NOT NULL,
appointment_time TEXT NOT NULL,
appointment_location TEXT NOT NULL,
- appointment_status TEXT CHECK(appointment_status IN ('pending', 'completed')) DEFAULT 'pending'
+ appointment_status TEXT CHECK(appointment_status IN ('pending', 'completed')) DEFAULT 'pending',
+ profile_id INTEGER NOT NULL REFERENCES profile(id) ON DELETE CASCADE
);Apply the same pattern to tasks, blood_pressure_logs, discharge_logs, weekly_weight, weekly_medicine, and weekly_symptoms. Then remove the ALTER TABLE statements.
Note: This requires the profile table to be created before the tables that reference it. Reorder the statements so the profile table creation comes first.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In Backend/schema.sql around lines 99 to 118, the ALTER TABLE statements add
nullable profile_id columns but Issue #141 requires profile_id INTEGER NOT NULL;
because SQLite cannot add a NOT NULL column via ALTER TABLE without a default,
update the schema by removing these ALTER TABLEs and instead add profile_id
INTEGER NOT NULL REFERENCES profile(id) ON DELETE CASCADE directly into the
CREATE TABLE definitions for appointments, tasks, blood_pressure_logs,
discharge_logs, weekly_weight, weekly_medicine, and weekly_symptoms; ensure the
profile table CREATE statement appears before these tables so the foreign key
resolves, or if migrating existing data choose an explicit migration path (add
column with default, backfill, then alter schema) — but for a fresh schema
implement the NOT NULL columns in the CREATE TABLEs and delete the ALTER TABLE
block.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This PR adds profile_id foreign key relationships to seven tables (appointments, tasks, blood_pressure_logs, discharge_logs, weekly_weight, weekly_medicine, weekly_symptoms) to establish proper relational integrity between user profiles and their associated data. However, the implementation is incomplete and contains critical issues that will cause the application to fail.
Key Changes:
- Added
profile_idforeign key columns to seven tables withON DELETE CASCADEconstraints - Updated all sample INSERT statements to include
profile_id = 1 - Changed backend server port from 5000 to 5001
- Added health check endpoint
- Code formatting updates in SettingsScreen.jsx
Reviewed changes
Copilot reviewed 6 out of 12 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| Backend/schema.sql | Adds ALTER TABLE statements for profile_id foreign keys and updates seed data with profile_id references |
| Backend/app.py | Changes server port to 5001 and adds /health endpoint |
| Frontend/.env | Updates BASE_URL to localhost:5001 to match backend port change |
| Frontend/src/Screens/SettingsScreen.jsx | Code formatting changes and a debug console.log statement |
| .gitignore | Adds "Backend" to gitignore (likely an error) |
| Frontend/package-lock.json | Dependency lock file updates |
| Frontend/ios/Podfile.lock | iOS dependency updates |
| Frontend/ios/BabyNest/PrivacyInfo.xcprivacy | iOS privacy manifest updates |
| Frontend/android/gradlew | New Gradle wrapper script |
| Backend/db/chromadb/chroma.sqlite3 | Binary database file |
Files not reviewed (1)
- Frontend/package-lock.json: Language not supported
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Backend/schema.sql
Outdated
| ALTER TABLE appointments | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE tasks | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE blood_pressure_logs | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE discharge_logs | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_weight | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_medicine | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_symptoms | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; |
Copilot
AI
Dec 28, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using ALTER TABLE to add foreign key columns will fail on existing databases that already have data in these tables without profile_id values. SQLite does not support adding NOT NULL columns with foreign key constraints to tables with existing data in a single ALTER TABLE statement. When the constraint is evaluated, existing rows will have NULL profile_id values, violating the foreign key constraint. Consider providing a migration script that:
- Backs up existing data
- Adds the column (which will be NULL for existing rows)
- Updates existing rows with a valid profile_id
- Then adds the constraint
Alternatively, document that this schema is only for fresh installations and existing databases need a separate migration path.
| INSERT INTO weekly_weight (week_number, weight, note, profile_id) VALUES | ||
| (8, 60.5, 'Slight nausea, but overall feeling okay', 1), | ||
| (9, 60.9, 'Appetite increasing slightly', 1), | ||
| (10, 61.3, 'Started prenatal yoga, feeling good', 1); | ||
|
|
||
|
|
||
| INSERT INTO weekly_medicine (week_number, name, dose, time, taken, note, profile_id) VALUES | ||
| (8, 'Prenatal Vitamin', '1 tablet', '08:00', 1, 'Daily multivitamin with folic acid', 1), | ||
| (9, 'Iron Supplement', '30mg', '13:00', 1, 'Taking to help with mild anemia', 1), | ||
| (10, 'Prenatal Vitamin', '1 tablet', '08:00', 1, 'No side effects, continuing as normal', 1); | ||
|
|
||
|
|
||
| INSERT INTO weekly_symptoms (week_number, symptom, note, profile_id) VALUES | ||
| (8, 'Morning Sickness', 'Worse after waking up', 1), | ||
| (9, 'Breast Tenderness', 'More sensitive than last week', 1), | ||
| (10, 'Frequent Urination', 'Especially during the night', 1); | ||
|
|
Copilot
AI
Dec 28, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The sample INSERT statements for weekly_weight, weekly_medicine, weekly_symptoms, appointments, and tasks all reference profile_id = 1. However, looking at the full schema (lines 63-66 visible in context), three profiles are inserted with auto-incrementing IDs. This means profiles with id = 2 and 3 will exist but have no associated data, creating orphaned profiles. Consider either removing the extra sample profiles or creating sample data for all profiles to maintain consistency.
Backend/schema.sql
Outdated
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE blood_pressure_logs | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE discharge_logs | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_weight | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_medicine | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_symptoms | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; |
Copilot
AI
Dec 28, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The ALTER TABLE statements add profile_id foreign keys to the tables, but none of the existing API endpoints have been updated to handle profile_id. All INSERT, UPDATE, and SELECT queries in the route files (appointments.py, tasks.py, weight.py, medicine.py, blood_pressure.py, discharge.py, symptoms.py) need to be updated to:
- Include profile_id in INSERT statements
- Filter by profile_id in SELECT queries to ensure users only see their own data
- Validate that the profile_id exists before inserting/updating records
Without these changes, the application will fail when trying to insert new records because profile_id will be NULL and violate the foreign key constraint, or it will return all records across all profiles instead of filtering by user.
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE blood_pressure_logs | |
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE discharge_logs | |
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE weekly_weight | |
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE weekly_medicine | |
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE weekly_symptoms | |
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | |
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE blood_pressure_logs | |
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE discharge_logs | |
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE weekly_weight | |
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE weekly_medicine | |
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | |
| ALTER TABLE weekly_symptoms | |
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; |
Backend/schema.sql
Outdated
| ALTER TABLE weekly_symptoms | ||
| ADD COLUMN profile_id INTEGER REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| -- inset dummy data |
Copilot
AI
Dec 28, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The comment says "inset dummy data" but should be "insert dummy data". This is a spelling error in the SQL comment.
| -- inset dummy data | |
| -- insert dummy data |
|
|
||
| const fetchProfileData = async () => { | ||
| try { | ||
| console.log('heelo'); |
Copilot
AI
Dec 28, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This console.log statement appears to be debug code that was left in. It should be removed before merging to production as it doesn't provide meaningful information and clutters the console output.
| console.log('heelo'); |
Backend/app.py
Outdated
|
|
||
| if __name__ == '__main__': | ||
| app.run(host='0.0.0.0', port=5000, debug=True) | ||
| app.run(host='0.0.0.0', port=5001, debug=True) |
Copilot
AI
Dec 28, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The port change from 5000 to 5001 should be coordinated with the Frontend/.env change on line 1. However, this creates a potential issue: if developers or deployment environments have configurations pointing to port 5000, they will break. Consider documenting this breaking change in the PR description or migration guide, or make the port configurable via environment variables to avoid hardcoding.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
♻️ Duplicate comments (1)
Backend/cache/context_default.json (1)
60-78: Symptoms dates are inconsistent with LMP.The symptom entries use dates (
2025-10-27) that predate the LMP (2025-12-03), which is logically impossible. The weight and medicine entries correctly use2026-02-11. This inconsistency was previously flagged.🔎 Proposed fix
{ "week": 10, "symptom": "Frequent Urination", "note": "Especially during the night", - "date": "2025-10-27 08:53:56" + "date": "2026-02-11 08:53:56" }, { "week": 9, "symptom": "Breast Tenderness", "note": "More sensitive than last week", - "date": "2025-10-27 08:53:56" + "date": "2026-02-04 08:53:56" }, { "week": 8, "symptom": "Morning Sickness", "note": "Worse after waking up", - "date": "2025-10-27 08:53:56" + "date": "2026-01-28 08:53:56" }
🧹 Nitpick comments (1)
Backend/schema.sql (1)
136-150: Seed appointment dates span inconsistent timeframes.The appointment dates mix years 2025 (February, June) in ways that don't follow a logical pregnancy timeline. For example, "Initial OB Appointment" is dated
2025-06-22(marked completed), but "Nutritional Counseling" is2025-02-05(pending) — chronologically earlier but not yet completed. Consider ordering dates consistently for realistic test data.
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
.gitignoreBackend/.envBackend/app.pyBackend/cache/context_default.jsonBackend/schema.sqlFrontend/src/Screens/SettingsScreen.jsx
🚧 Files skipped from review as they are similar to previous changes (2)
- Frontend/src/Screens/SettingsScreen.jsx
- .gitignore
🧰 Additional context used
🪛 ast-grep (0.40.3)
Backend/app.py
[warning] 190-190: Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.
Context: app.run(host='0.0.0.0', port=port, debug=True)
Note: [CWE-489] Active Debug Code. [REFERENCES]
- https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/
(debug-enabled-python)
🪛 Ruff (0.14.10)
Backend/app.py
191-191: Possible binding to all interfaces
(S104)
191-191: Use of debug=True in Flask app detected
(S201)
🔇 Additional comments (2)
Backend/app.py (1)
185-188: LGTM!The health check endpoint is clean and follows standard conventions for health probes.
Backend/schema.sql (1)
52-64: LGTM on profile table and foreign key additions.The
profiletable creation and subsequentALTER TABLEstatements withNOT NULL DEFAULT 1correctly address Issue #141's requirements. TheON DELETE CASCADEensures orphan records are cleaned up when profiles are deleted.
| FLASK_APP=app.py | ||
| FLASK_ENV=development |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
# Check if .env is in .gitignore files
echo "=== Checking .gitignore files for .env ==="
find . -name ".gitignore" -type f | xargs -I {} sh -c 'echo "File: {}"; cat {} | grep -E "\.env|\.env\*" || echo "No .env pattern found"'
echo ""
echo "=== Checking for .env files ==="
find . -maxdepth 3 -name ".env*" -type f
echo ""
echo "=== Checking git status of .env ==="
git ls-files | grep "\.env"Repository: AOSSIE-Org/BabyNest
Length of output: 446
Remove Backend/.env from version control and add .env to Backend/.gitignore.
The .env file should not be committed to version control. Create Backend/.env.example with the template content, add .env to Backend/.gitignore (similar to the Frontend setup), and remove the committed .env from git history using git rm --cached Backend/.env.
🤖 Prompt for AI Agents
In Backend/.env around lines 1-2 the committed .env contains sensitive dev
config and must be removed from version control; create Backend/.env.example
containing the same two lines as a template, add a line with ".env" to
Backend/.gitignore (mirroring Frontend), run git rm --cached Backend/.env to
untrack the file, commit the changes (add .env.example and updated .gitignore,
remove the tracked .env) and push so the .env is no longer in the repo while a
template remains.
| ALTER TABLE appointments | ||
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE tasks | ||
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE blood_pressure_logs | ||
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE discharge_logs | ||
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_weight | ||
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_medicine | ||
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; | ||
|
|
||
| ALTER TABLE weekly_symptoms | ||
| ADD COLUMN profile_id INTEGER NOT NULL DEFAULT 1 REFERENCES profile(id) ON DELETE CASCADE; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if foreign_keys pragma is set in db connection code
rg -n "foreign_keys" Backend/db/Repository: AOSSIE-Org/BabyNest
Length of output: 45
🏁 Script executed:
#!/bin/bash
# Check if PRAGMA foreign_keys is already in the schema file
rg -n "PRAGMA foreign_keys" Backend/schema.sqlRepository: AOSSIE-Org/BabyNest
Length of output: 45
🏁 Script executed:
#!/bin/bash
# Check the start of the schema.sql file
head -20 Backend/schema.sqlRepository: AOSSIE-Org/BabyNest
Length of output: 675
🏁 Script executed:
#!/bin/bash
# Check what files exist in Backend/db/
find Backend/db/ -type f -name "*.py" 2>/dev/null | head -20Repository: AOSSIE-Org/BabyNest
Length of output: 79
🏁 Script executed:
#!/bin/bash
# Check if there are any connection initialization files
ls -la Backend/db/ 2>/dev/null || ls -la Backend/ 2>/dev/null | head -30Repository: AOSSIE-Org/BabyNest
Length of output: 282
🏁 Script executed:
#!/bin/bash
# Read the db.py file to check connection setup
cat -n Backend/db/db.pyRepository: AOSSIE-Org/BabyNest
Length of output: 846
Enable foreign key enforcement with PRAGMA foreign_keys = ON.
SQLite does not enforce foreign key constraints by default. The schema defines ON DELETE CASCADE constraints but without PRAGMA foreign_keys = ON; at the start of schema.sql, these constraints are never enforced. Additionally, the pragma must be set in the application code (Backend/db/db.py) since it is a per-connection setting.
Add to the top of schema.sql:
+PRAGMA foreign_keys = ON;
+
DROP TABLE IF EXISTS users;And in Backend/db/db.py, enable the pragma after opening the connection:
def open_db():
if "db" not in g:
first_time_setup()
g.db = sqlite3.connect(DATABASE)
+ g.db.execute("PRAGMA foreign_keys = ON")
g.db.row_factory = sqlite3.Row
return g.dbCommittable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In Backend/schema.sql around lines 97 to 116 and in Backend/db/db.py, the schema
adds foreign keys with ON DELETE CASCADE but SQLite won’t enforce them unless
PRAGMA foreign_keys = ON is set per connection; add a line at the top of
Backend/schema.sql to enable foreign keys when loading the schema, and in
Backend/db/db.py enable the pragma immediately after opening each SQLite
connection (execute PRAGMA foreign_keys = ON on the connection) so foreign key
constraints are actually enforced at runtime.
|
@bhavik-mangla please review and merge |
Closes #141
📝 Description
This PR fixes the missing relational link between
profileand dependent tables.Previously, several tables stored data without referencing any
profile, leading to orphan records and making it impossible to fetch user-specific data safely.This PR introduces
profile_idforeign keys and updates all insertion/seed data to correctly associate records with a profile.🔧 Changes Made
profile_idcolumn to:profile(id)with:ON DELETE CASCADEto prevent orphan dataprofile_id📷 Screenshots or Visual Changes
N/A — backend/database update only.
🤝 Collaboration
Collaborated with: N/A
✅ Checklist
Summary by CodeRabbit
New Features
Data
Style
Chores
✏️ Tip: You can customize this high-level summary in your review settings.