82 lines
2.7 KiB
Python
82 lines
2.7 KiB
Python
"""
|
|
Database migration: Add support for multiple users per chore.
|
|
|
|
This creates a chore_assignments junction table to allow
|
|
multiple users to be assigned to a single chore.
|
|
"""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
|
|
from app.core.database import engine, SessionLocal
|
|
from sqlalchemy import text
|
|
|
|
def create_chore_assignments_table():
|
|
"""Create chore_assignments table for many-to-many relationship."""
|
|
db = SessionLocal()
|
|
|
|
try:
|
|
print("=" * 70)
|
|
print("MIGRATION: Add Multiple Users Per Chore Support")
|
|
print("=" * 70)
|
|
print()
|
|
|
|
# Check if table already exists
|
|
result = db.execute(text("SELECT name FROM sqlite_master WHERE type='table' AND name='chore_assignments'"))
|
|
if result.fetchone():
|
|
print("✅ chore_assignments table already exists. No migration needed.")
|
|
return
|
|
|
|
print("📋 Creating chore_assignments table...")
|
|
|
|
# Create junction table
|
|
db.execute(text("""
|
|
CREATE TABLE chore_assignments (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
chore_id INTEGER NOT NULL,
|
|
user_id INTEGER NOT NULL,
|
|
completed_at DATETIME,
|
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
FOREIGN KEY (chore_id) REFERENCES chores (id) ON DELETE CASCADE,
|
|
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
|
UNIQUE(chore_id, user_id)
|
|
)
|
|
"""))
|
|
|
|
print("✅ chore_assignments table created!")
|
|
print()
|
|
|
|
print("📋 Migrating existing chore assignments...")
|
|
|
|
# Migrate existing assigned_user_id data to new table
|
|
# For each chore with an assigned_user_id, create an assignment record
|
|
result = db.execute(text("""
|
|
INSERT INTO chore_assignments (chore_id, user_id, completed_at)
|
|
SELECT id, assigned_user_id, completed_at
|
|
FROM chores
|
|
WHERE assigned_user_id IS NOT NULL
|
|
"""))
|
|
|
|
migrated_count = result.rowcount
|
|
db.commit()
|
|
|
|
print(f"✅ Migrated {migrated_count} existing chore assignments!")
|
|
print()
|
|
print("⚠️ NOTE: The assigned_user_id column in chores table is now deprecated.")
|
|
print(" It will be kept for backwards compatibility but not used.")
|
|
print()
|
|
print("Migration complete!")
|
|
print()
|
|
|
|
except Exception as e:
|
|
print(f"❌ Migration failed: {e}")
|
|
db.rollback()
|
|
raise
|
|
finally:
|
|
db.close()
|
|
|
|
if __name__ == "__main__":
|
|
create_chore_assignments_table()
|