database.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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 # 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. async def seed_notification_templates():
  110. """Seed default notification templates if they don't exist."""
  111. from sqlalchemy import select
  112. from backend.app.models.notification_template import NotificationTemplate, DEFAULT_TEMPLATES
  113. async with async_session() as session:
  114. # Check if templates already exist
  115. result = await session.execute(select(NotificationTemplate).limit(1))
  116. if result.scalar_one_or_none() is not None:
  117. # Templates already seeded
  118. return
  119. # Insert default templates
  120. for template_data in DEFAULT_TEMPLATES:
  121. template = NotificationTemplate(
  122. event_type=template_data["event_type"],
  123. name=template_data["name"],
  124. title_template=template_data["title_template"],
  125. body_template=template_data["body_template"],
  126. is_default=True,
  127. )
  128. session.add(template)
  129. await session.commit()