munch-ease-backend/tests/user_fixtures.py

47 lines
1.7 KiB
Python

from __future__ import annotations
import aiosqlite
async def seed_users_from_legacy_persons(conn: aiosqlite.Connection):
"""Seed User and HouseholdMember from legacy test persons if present.
This is a no-op if the Person table is empty or missing.
"""
# Ensure required tables exist
try:
await conn.execute("SELECT 1 FROM User LIMIT 1")
await conn.execute("SELECT 1 FROM Household LIMIT 1")
await conn.execute("SELECT 1 FROM HouseholdMember LIMIT 1")
except Exception:
return
# If any users exist already, do nothing
async with conn.execute("SELECT COUNT(1) FROM User") as c:
row = await c.fetchone()
if row and int(row[0]) > 0:
return
# Default household id (created by migration/bootstrap)
async with conn.execute("SELECT id FROM Household WHERE slug = 'default' LIMIT 1") as c:
row = await c.fetchone()
if not row:
return
hid = int(row[0])
# Copy over Person rows into User and create membership
try:
async with conn.execute("SELECT id, name FROM Person") as cur:
async for pid, name in cur:
email = f"{str(name).lower()}@example.com"
await conn.execute(
"INSERT OR IGNORE INTO User (id, email, display_name) VALUES (?, ?, ?)",
(int(pid), email, str(name)),
)
await conn.execute(
"INSERT OR IGNORE INTO HouseholdMember (user_id, household_id, role) VALUES (?, ?, 'admin')",
(int(pid), hid),
)
except Exception:
# Person table may not exist in some contexts; ignore
return