database.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
  2. from sqlalchemy.orm import DeclarativeBase
  3. from backend.app.core.config import settings
  4. engine = create_async_engine(
  5. settings.database_url,
  6. echo=settings.debug,
  7. )
  8. async_session = async_sessionmaker(
  9. engine,
  10. class_=AsyncSession,
  11. expire_on_commit=False,
  12. )
  13. class Base(DeclarativeBase):
  14. pass
  15. async def get_db() -> AsyncSession:
  16. async with async_session() as session:
  17. try:
  18. yield session
  19. await session.commit()
  20. except Exception:
  21. await session.rollback()
  22. raise
  23. finally:
  24. await session.close()
  25. async def init_db():
  26. # Import models to register them with SQLAlchemy
  27. from backend.app.models import printer, archive, filament, settings, smart_plug, print_queue, notification, maintenance, kprofile_note, notification_template, external_link # noqa: F401
  28. async with engine.begin() as conn:
  29. await conn.run_sync(Base.metadata.create_all)
  30. # Run migrations for new columns (SQLite doesn't auto-add columns)
  31. await run_migrations(conn)
  32. # Seed default notification templates
  33. await seed_notification_templates()
  34. async def run_migrations(conn):
  35. """Add new columns to existing tables if they don't exist."""
  36. from sqlalchemy import text
  37. # Migration: Add is_favorite column to print_archives
  38. try:
  39. await conn.execute(text(
  40. "ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0"
  41. ))
  42. except Exception:
  43. # Column already exists
  44. pass
  45. # Migration: Add content_hash column to print_archives for duplicate detection
  46. try:
  47. await conn.execute(text(
  48. "ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)"
  49. ))
  50. except Exception:
  51. # Column already exists
  52. pass
  53. # Migration: Add auto_off_executed column to smart_plugs
  54. try:
  55. await conn.execute(text(
  56. "ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0"
  57. ))
  58. except Exception:
  59. # Column already exists
  60. pass
  61. # Migration: Add on_print_stopped column to notification_providers
  62. try:
  63. await conn.execute(text(
  64. "ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1"
  65. ))
  66. except Exception:
  67. # Column already exists
  68. pass
  69. # Migration: Add source_3mf_path column to print_archives
  70. try:
  71. await conn.execute(text(
  72. "ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)"
  73. ))
  74. except Exception:
  75. # Column already exists
  76. pass
  77. # Migration: Add on_maintenance_due column to notification_providers
  78. try:
  79. await conn.execute(text(
  80. "ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0"
  81. ))
  82. except Exception:
  83. # Column already exists
  84. pass
  85. # Migration: Add location column to printers for grouping
  86. try:
  87. await conn.execute(text(
  88. "ALTER TABLE printers ADD COLUMN location VARCHAR(100)"
  89. ))
  90. except Exception:
  91. # Column already exists
  92. pass
  93. # Migration: Add interval_type column to maintenance_types
  94. try:
  95. await conn.execute(text(
  96. "ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'"
  97. ))
  98. except Exception:
  99. # Column already exists
  100. pass
  101. # Migration: Add custom_interval_type column to printer_maintenance
  102. try:
  103. await conn.execute(text(
  104. "ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)"
  105. ))
  106. except Exception:
  107. # Column already exists
  108. pass
  109. # Migration: Add power alert columns to smart_plugs
  110. try:
  111. await conn.execute(text(
  112. "ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0"
  113. ))
  114. except Exception:
  115. pass
  116. try:
  117. await conn.execute(text(
  118. "ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL"
  119. ))
  120. except Exception:
  121. pass
  122. try:
  123. await conn.execute(text(
  124. "ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL"
  125. ))
  126. except Exception:
  127. pass
  128. try:
  129. await conn.execute(text(
  130. "ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME"
  131. ))
  132. except Exception:
  133. pass
  134. # Migration: Add schedule columns to smart_plugs
  135. try:
  136. await conn.execute(text(
  137. "ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0"
  138. ))
  139. except Exception:
  140. pass
  141. try:
  142. await conn.execute(text(
  143. "ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)"
  144. ))
  145. except Exception:
  146. pass
  147. try:
  148. await conn.execute(text(
  149. "ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)"
  150. ))
  151. except Exception:
  152. pass
  153. # Migration: Add daily digest columns to notification_providers
  154. try:
  155. await conn.execute(text(
  156. "ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0"
  157. ))
  158. except Exception:
  159. pass
  160. try:
  161. await conn.execute(text(
  162. "ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)"
  163. ))
  164. except Exception:
  165. pass
  166. async def seed_notification_templates():
  167. """Seed default notification templates if they don't exist."""
  168. from sqlalchemy import select
  169. from backend.app.models.notification_template import NotificationTemplate, DEFAULT_TEMPLATES
  170. async with async_session() as session:
  171. # Check if templates already exist
  172. result = await session.execute(select(NotificationTemplate).limit(1))
  173. if result.scalar_one_or_none() is not None:
  174. # Templates already seeded
  175. return
  176. # Insert default templates
  177. for template_data in DEFAULT_TEMPLATES:
  178. template = NotificationTemplate(
  179. event_type=template_data["event_type"],
  180. name=template_data["name"],
  181. title_template=template_data["title_template"],
  182. body_template=template_data["body_template"],
  183. is_default=True,
  184. )
  185. session.add(template)
  186. await session.commit()