synapticpush commited on
Commit
93ed57e
·
1 Parent(s): 39eada6

db-init: Implement database initialization and seeding

Browse files
Backend/database/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .connection import engine, async_session_factory, get_db, get_db_context, init_db, close_db
2
+ from .models import Base, Issue, IssueImage, Classification, IssueEvent, Department, Member, Escalation
Backend/database/init_db.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from sqlalchemy.ext.asyncio import create_async_engine
4
+ from Backend.core.config import settings
5
+ from Backend.database.models import Base
6
+ from Backend.database.seed import seed_data
7
+
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger(__name__)
10
+
11
+ async def init_models():
12
+ """Drops and recreates all tables, then seeds initial data."""
13
+ logger.info("Initializing database...")
14
+
15
+
16
+ database_url = settings.database_url.replace("port=6543", "port=5432").replace("postgresql://", "postgresql+asyncpg://")
17
+ engine = create_async_engine(
18
+ database_url,
19
+ echo=True,
20
+ connect_args={
21
+ "statement_cache_size": 0,
22
+ "prepared_statement_cache_size": 0,
23
+ }
24
+ )
25
+
26
+ async with engine.begin() as conn:
27
+ logger.info("Dropping existing tables...")
28
+
29
+
30
+
31
+
32
+ logger.info("Creating new tables...")
33
+ await conn.run_sync(Base.metadata.create_all)
34
+
35
+ logger.info("Schema initialized. Seeding data...")
36
+ try:
37
+ await seed_data(engine)
38
+ logger.info("Seeding completed successfully!")
39
+ except Exception as e:
40
+ logger.error(f"Seeding failed: {e}")
41
+
42
+ await engine.dispose()
43
+ logger.info("Database initialization finished.")
44
+
45
+ if __name__ == "__main__":
46
+ asyncio.run(init_models())
Backend/database/seed.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import uuid
3
+ from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
4
+ from sqlalchemy.orm import sessionmaker
5
+ from Backend.database.models import Department, Member
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ async def seed_data(engine: AsyncEngine):
10
+ async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
11
+
12
+ async with async_session() as session:
13
+
14
+ pwd_id = uuid.uuid4()
15
+ sanitation_id = uuid.uuid4()
16
+ traffic_id = uuid.uuid4()
17
+
18
+ departments = [
19
+ Department(
20
+ id=pwd_id,
21
+ name="Public Works Department",
22
+ code="PWD",
23
+ description="Roads, Potholes, Infrastructure",
24
+ default_sla_hours=48,
25
+ escalation_email="pwd_head@city.gov"
26
+ ),
27
+ Department(
28
+ id=sanitation_id,
29
+ name="Sanitation Department",
30
+ code="SANITATION",
31
+ description="Garbage, Cleaning, Waste",
32
+ default_sla_hours=24,
33
+ escalation_email="sanitation_head@city.gov"
34
+ ),
35
+ Department(
36
+ id=traffic_id,
37
+ name="Traffic Department",
38
+ code="TRAFFIC",
39
+ description="Signals, Signs, Illegal Parking",
40
+ default_sla_hours=12,
41
+ escalation_email="traffic_head@city.gov"
42
+ )
43
+ ]
44
+
45
+ for dept in departments:
46
+ session.add(dept)
47
+
48
+
49
+ members = [
50
+ Member(
51
+ department_id=pwd_id,
52
+ name="Ramesh Kumar",
53
+ email="ramesh.pwd@city.gov",
54
+ role="officer",
55
+ city="New Delhi",
56
+ locality="Connaught Place",
57
+ max_workload=10
58
+ ),
59
+ Member(
60
+ department_id=sanitation_id,
61
+ name="Suresh Singh",
62
+ email="suresh.sanitation@city.gov",
63
+ role="officer",
64
+ city="New Delhi",
65
+ locality="Karol Bagh",
66
+ max_workload=15
67
+ ),
68
+ Member(
69
+ department_id=traffic_id,
70
+ name="Priya Sharma",
71
+ email="priya.traffic@city.gov",
72
+ role="officer",
73
+ city="New Delhi",
74
+ locality="Lajpat Nagar",
75
+ max_workload=12
76
+ )
77
+ ]
78
+
79
+ for member in members:
80
+ session.add(member)
81
+
82
+ await session.commit()
83
+ logger.info("Seeded 3 departments and 3 members.")