database.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
  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. async def close_all_connections():
  14. """Close all database connections for backup/restore operations."""
  15. global engine
  16. await engine.dispose()
  17. async def reinitialize_database():
  18. """Reinitialize database connection after restore."""
  19. global engine, async_session
  20. engine = create_async_engine(
  21. settings.database_url,
  22. echo=settings.debug,
  23. )
  24. async_session = async_sessionmaker(
  25. engine,
  26. class_=AsyncSession,
  27. expire_on_commit=False,
  28. )
  29. class Base(DeclarativeBase):
  30. pass
  31. async def get_db() -> AsyncSession:
  32. async with async_session() as session:
  33. try:
  34. yield session
  35. await session.commit()
  36. except Exception:
  37. await session.rollback()
  38. raise
  39. finally:
  40. await session.close()
  41. async def init_db():
  42. # Import models to register them with SQLAlchemy
  43. from backend.app.models import ( # noqa: F401
  44. ams_history,
  45. api_key,
  46. archive,
  47. external_link,
  48. filament,
  49. github_backup,
  50. group,
  51. kprofile_note,
  52. library,
  53. maintenance,
  54. notification,
  55. notification_template,
  56. pending_upload,
  57. print_queue,
  58. printer,
  59. project,
  60. project_bom,
  61. settings,
  62. slot_preset,
  63. smart_plug,
  64. user,
  65. )
  66. async with engine.begin() as conn:
  67. await conn.run_sync(Base.metadata.create_all)
  68. # Run migrations for new columns (SQLite doesn't auto-add columns)
  69. await run_migrations(conn)
  70. # Seed default notification templates
  71. await seed_notification_templates()
  72. # Seed default groups and migrate existing users
  73. await seed_default_groups()
  74. async def run_migrations(conn):
  75. """Add new columns to existing tables if they don't exist."""
  76. from sqlalchemy import text
  77. # Migration: Add is_favorite column to print_archives
  78. try:
  79. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0"))
  80. except Exception:
  81. # Column already exists
  82. pass
  83. # Migration: Add content_hash column to print_archives for duplicate detection
  84. try:
  85. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)"))
  86. except Exception:
  87. # Column already exists
  88. pass
  89. # Migration: Add auto_off_executed column to smart_plugs
  90. try:
  91. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0"))
  92. except Exception:
  93. # Column already exists
  94. pass
  95. # Migration: Add on_print_stopped column to notification_providers
  96. try:
  97. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1"))
  98. except Exception:
  99. # Column already exists
  100. pass
  101. # Migration: Add source_3mf_path column to print_archives
  102. try:
  103. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)"))
  104. except Exception:
  105. # Column already exists
  106. pass
  107. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  108. try:
  109. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)"))
  110. except Exception:
  111. # Column already exists
  112. pass
  113. # Migration: Add on_maintenance_due column to notification_providers
  114. try:
  115. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0"))
  116. except Exception:
  117. # Column already exists
  118. pass
  119. # Migration: Add location column to printers for grouping
  120. try:
  121. await conn.execute(text("ALTER TABLE printers ADD COLUMN location VARCHAR(100)"))
  122. except Exception:
  123. # Column already exists
  124. pass
  125. # Migration: Add interval_type column to maintenance_types
  126. try:
  127. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'"))
  128. except Exception:
  129. # Column already exists
  130. pass
  131. # Migration: Add custom_interval_type column to printer_maintenance
  132. try:
  133. await conn.execute(text("ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)"))
  134. except Exception:
  135. # Column already exists
  136. pass
  137. # Migration: Add power alert columns to smart_plugs
  138. try:
  139. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0"))
  140. except Exception:
  141. pass
  142. try:
  143. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL"))
  144. except Exception:
  145. pass
  146. try:
  147. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL"))
  148. except Exception:
  149. pass
  150. try:
  151. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME"))
  152. except Exception:
  153. pass
  154. # Migration: Add schedule columns to smart_plugs
  155. try:
  156. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0"))
  157. except Exception:
  158. pass
  159. try:
  160. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)"))
  161. except Exception:
  162. pass
  163. try:
  164. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)"))
  165. except Exception:
  166. pass
  167. # Migration: Add daily digest columns to notification_providers
  168. try:
  169. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0"))
  170. except Exception:
  171. pass
  172. try:
  173. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)"))
  174. except Exception:
  175. pass
  176. # Migration: Add project_id column to print_archives
  177. try:
  178. await conn.execute(
  179. text("ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  180. )
  181. except Exception:
  182. pass
  183. # Migration: Add project_id column to print_queue
  184. try:
  185. await conn.execute(
  186. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  187. )
  188. except Exception:
  189. pass
  190. # Migration: Create FTS5 virtual table for archive full-text search
  191. try:
  192. await conn.execute(
  193. text("""
  194. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  195. print_name,
  196. filename,
  197. tags,
  198. notes,
  199. designer,
  200. filament_type,
  201. content='print_archives',
  202. content_rowid='id'
  203. )
  204. """)
  205. )
  206. except Exception:
  207. pass
  208. # Migration: Create triggers to keep FTS index in sync
  209. try:
  210. await conn.execute(
  211. text("""
  212. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  213. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  214. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  215. END
  216. """)
  217. )
  218. except Exception:
  219. pass
  220. try:
  221. await conn.execute(
  222. text("""
  223. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  224. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  225. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  226. END
  227. """)
  228. )
  229. except Exception:
  230. pass
  231. try:
  232. await conn.execute(
  233. text("""
  234. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  235. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  236. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  237. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  238. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  239. END
  240. """)
  241. )
  242. except Exception:
  243. pass
  244. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  245. try:
  246. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0"))
  247. except Exception:
  248. pass
  249. try:
  250. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME"))
  251. except Exception:
  252. pass
  253. # Migration: Add AMS alarm notification columns to notification_providers
  254. try:
  255. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0"))
  256. except Exception:
  257. pass
  258. try:
  259. await conn.execute(
  260. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  261. )
  262. except Exception:
  263. pass
  264. # Migration: Add AMS-HT alarm notification columns to notification_providers
  265. try:
  266. await conn.execute(
  267. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  268. )
  269. except Exception:
  270. pass
  271. try:
  272. await conn.execute(
  273. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  274. )
  275. except Exception:
  276. pass
  277. # Migration: Add plate not empty notification column to notification_providers
  278. try:
  279. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1"))
  280. except Exception:
  281. pass
  282. # Migration: Add notes column to projects (Phase 2)
  283. try:
  284. await conn.execute(text("ALTER TABLE projects ADD COLUMN notes TEXT"))
  285. except Exception:
  286. pass
  287. # Migration: Add attachments column to projects (Phase 3)
  288. try:
  289. await conn.execute(text("ALTER TABLE projects ADD COLUMN attachments JSON"))
  290. except Exception:
  291. pass
  292. # Migration: Add tags column to projects (Phase 4)
  293. try:
  294. await conn.execute(text("ALTER TABLE projects ADD COLUMN tags TEXT"))
  295. except Exception:
  296. pass
  297. # Migration: Add due_date column to projects (Phase 5)
  298. try:
  299. await conn.execute(text("ALTER TABLE projects ADD COLUMN due_date DATETIME"))
  300. except Exception:
  301. pass
  302. # Migration: Add priority column to projects (Phase 5)
  303. try:
  304. await conn.execute(text("ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'"))
  305. except Exception:
  306. pass
  307. # Migration: Add budget column to projects (Phase 6)
  308. try:
  309. await conn.execute(text("ALTER TABLE projects ADD COLUMN budget REAL"))
  310. except Exception:
  311. pass
  312. # Migration: Add is_template column to projects (Phase 8)
  313. try:
  314. await conn.execute(text("ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0"))
  315. except Exception:
  316. pass
  317. # Migration: Add template_source_id column to projects (Phase 8)
  318. try:
  319. await conn.execute(text("ALTER TABLE projects ADD COLUMN template_source_id INTEGER"))
  320. except Exception:
  321. pass
  322. # Migration: Add parent_id column to projects (Phase 10)
  323. try:
  324. await conn.execute(
  325. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  326. )
  327. except Exception:
  328. pass
  329. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  330. try:
  331. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired"))
  332. except Exception:
  333. pass
  334. # Migration: Add unit_price column to project_bom_items
  335. try:
  336. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN unit_price REAL"))
  337. except Exception:
  338. pass
  339. # Migration: Add sourcing_url column to project_bom_items
  340. try:
  341. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)"))
  342. except Exception:
  343. pass
  344. # Migration: Rename notes to remarks in project_bom_items
  345. try:
  346. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks"))
  347. except Exception:
  348. pass
  349. # Migration: Add show_in_switchbar column to smart_plugs
  350. try:
  351. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0"))
  352. except Exception:
  353. pass
  354. # Migration: Add runtime tracking columns to printers
  355. try:
  356. await conn.execute(text("ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0"))
  357. except Exception:
  358. pass
  359. try:
  360. await conn.execute(text("ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME"))
  361. except Exception:
  362. pass
  363. # Migration: Add quantity column to print_archives for tracking item count
  364. try:
  365. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1"))
  366. except Exception:
  367. pass
  368. # Migration: Add manual_start column to print_queue for staged prints
  369. try:
  370. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0"))
  371. except Exception:
  372. pass
  373. # Migration: Add wiki_url column to maintenance_types for documentation links
  374. try:
  375. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)"))
  376. except Exception:
  377. pass
  378. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  379. try:
  380. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT"))
  381. except Exception:
  382. pass
  383. # Migration: Add target_parts_count column to projects for tracking total parts needed
  384. try:
  385. await conn.execute(text("ALTER TABLE projects ADD COLUMN target_parts_count INTEGER"))
  386. except Exception:
  387. pass
  388. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  389. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  390. try:
  391. # Check if printer_id is already nullable by trying to insert NULL
  392. # This is a safe check that won't affect existing data
  393. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  394. row = result.fetchone()
  395. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  396. # Need to migrate - printer_id is currently NOT NULL
  397. await conn.execute(
  398. text("""
  399. CREATE TABLE print_queue_new (
  400. id INTEGER PRIMARY KEY,
  401. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  402. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  403. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  404. position INTEGER DEFAULT 0,
  405. scheduled_time DATETIME,
  406. manual_start BOOLEAN DEFAULT 0,
  407. require_previous_success BOOLEAN DEFAULT 0,
  408. auto_off_after BOOLEAN DEFAULT 0,
  409. ams_mapping TEXT,
  410. status VARCHAR(20) DEFAULT 'pending',
  411. started_at DATETIME,
  412. completed_at DATETIME,
  413. error_message TEXT,
  414. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  415. )
  416. """)
  417. )
  418. await conn.execute(
  419. text("""
  420. INSERT INTO print_queue_new
  421. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  422. manual_start, require_previous_success, auto_off_after, ams_mapping,
  423. status, started_at, completed_at, error_message, created_at
  424. FROM print_queue
  425. """)
  426. )
  427. await conn.execute(text("DROP TABLE print_queue"))
  428. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  429. except Exception:
  430. pass
  431. # Migration: Add plug_type column to smart_plugs for HA integration
  432. try:
  433. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'"))
  434. except Exception:
  435. pass
  436. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  437. try:
  438. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)"))
  439. except Exception:
  440. pass
  441. # Migration: Add project_id column to library_folders for linking folders to projects
  442. try:
  443. await conn.execute(
  444. text("ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  445. )
  446. except Exception:
  447. pass
  448. # Migration: Add archive_id column to library_folders for linking folders to archives
  449. try:
  450. await conn.execute(
  451. text(
  452. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  453. )
  454. )
  455. except Exception:
  456. pass
  457. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  458. try:
  459. # Check if ip_address is currently NOT NULL
  460. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  461. row = result.fetchone()
  462. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  463. # Need to migrate - ip_address is currently NOT NULL
  464. await conn.execute(
  465. text("""
  466. CREATE TABLE smart_plugs_new (
  467. id INTEGER PRIMARY KEY,
  468. name VARCHAR(100) NOT NULL,
  469. ip_address VARCHAR(45),
  470. plug_type VARCHAR(20) DEFAULT 'tasmota',
  471. ha_entity_id VARCHAR(100),
  472. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  473. enabled BOOLEAN NOT NULL DEFAULT 1,
  474. auto_on BOOLEAN NOT NULL DEFAULT 1,
  475. auto_off BOOLEAN NOT NULL DEFAULT 1,
  476. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  477. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  478. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  479. username VARCHAR(50),
  480. password VARCHAR(100),
  481. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  482. power_alert_high FLOAT,
  483. power_alert_low FLOAT,
  484. power_alert_last_triggered DATETIME,
  485. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  486. schedule_on_time VARCHAR(5),
  487. schedule_off_time VARCHAR(5),
  488. show_in_switchbar BOOLEAN DEFAULT 0,
  489. last_state VARCHAR(10),
  490. last_checked DATETIME,
  491. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  492. auto_off_pending BOOLEAN DEFAULT 0,
  493. auto_off_pending_since DATETIME,
  494. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  495. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  496. )
  497. """)
  498. )
  499. await conn.execute(
  500. text("""
  501. INSERT INTO smart_plugs_new
  502. SELECT id, name, ip_address,
  503. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  504. enabled, auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  505. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  506. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  507. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  508. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  509. FROM smart_plugs
  510. """)
  511. )
  512. await conn.execute(text("DROP TABLE smart_plugs"))
  513. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  514. except Exception:
  515. pass
  516. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  517. try:
  518. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN plate_id INTEGER"))
  519. except Exception:
  520. pass
  521. # Migration: Add print options columns to print_queue
  522. try:
  523. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1"))
  524. except Exception:
  525. pass
  526. try:
  527. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0"))
  528. except Exception:
  529. pass
  530. try:
  531. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1"))
  532. except Exception:
  533. pass
  534. try:
  535. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0"))
  536. except Exception:
  537. pass
  538. try:
  539. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0"))
  540. except Exception:
  541. pass
  542. try:
  543. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1"))
  544. except Exception:
  545. pass
  546. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  547. # This allows queue items to reference library files directly (archive created at print start)
  548. try:
  549. await conn.execute(
  550. text(
  551. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  552. )
  553. )
  554. except Exception:
  555. pass
  556. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  557. try:
  558. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  559. row = result.fetchone()
  560. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  561. # Need to migrate - archive_id is currently NOT NULL
  562. await conn.execute(
  563. text("""
  564. CREATE TABLE print_queue_new2 (
  565. id INTEGER PRIMARY KEY,
  566. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  567. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  568. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  569. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  570. position INTEGER DEFAULT 0,
  571. scheduled_time DATETIME,
  572. manual_start BOOLEAN DEFAULT 0,
  573. require_previous_success BOOLEAN DEFAULT 0,
  574. auto_off_after BOOLEAN DEFAULT 0,
  575. ams_mapping TEXT,
  576. plate_id INTEGER,
  577. bed_levelling BOOLEAN DEFAULT 1,
  578. flow_cali BOOLEAN DEFAULT 0,
  579. vibration_cali BOOLEAN DEFAULT 1,
  580. layer_inspect BOOLEAN DEFAULT 0,
  581. timelapse BOOLEAN DEFAULT 0,
  582. use_ams BOOLEAN DEFAULT 1,
  583. status VARCHAR(20) DEFAULT 'pending',
  584. started_at DATETIME,
  585. completed_at DATETIME,
  586. error_message TEXT,
  587. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  588. )
  589. """)
  590. )
  591. await conn.execute(
  592. text("""
  593. INSERT INTO print_queue_new2
  594. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  595. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  596. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  597. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  598. status, started_at, completed_at, error_message, created_at
  599. FROM print_queue
  600. """)
  601. )
  602. await conn.execute(text("DROP TABLE print_queue"))
  603. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  604. except Exception:
  605. pass
  606. # Migration: Add HA energy sensor entity columns to smart_plugs
  607. try:
  608. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)"))
  609. except Exception:
  610. pass
  611. try:
  612. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)"))
  613. except Exception:
  614. pass
  615. try:
  616. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)"))
  617. except Exception:
  618. pass
  619. # Migration: Create users table for authentication
  620. try:
  621. await conn.execute(
  622. text("""
  623. CREATE TABLE IF NOT EXISTS users (
  624. id INTEGER PRIMARY KEY,
  625. username VARCHAR(100) NOT NULL UNIQUE,
  626. password_hash VARCHAR(255) NOT NULL,
  627. role VARCHAR(20) NOT NULL DEFAULT 'user',
  628. is_active BOOLEAN NOT NULL DEFAULT 1,
  629. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  630. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  631. )
  632. """)
  633. )
  634. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  635. except Exception:
  636. pass
  637. # Migration: Add external camera columns to printers
  638. try:
  639. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)"))
  640. except Exception:
  641. pass
  642. try:
  643. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)"))
  644. except Exception:
  645. pass
  646. try:
  647. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0"))
  648. except Exception:
  649. pass
  650. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  651. try:
  652. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)"))
  653. except Exception:
  654. pass
  655. # Migration: Add is_external column to library_files for external cloud files
  656. try:
  657. await conn.execute(text("ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  658. except Exception:
  659. pass
  660. # Migration: Add project_id column to library_files
  661. try:
  662. await conn.execute(
  663. text("ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  664. )
  665. except Exception:
  666. pass
  667. # Migration: Add is_external column to library_folders for external cloud folders
  668. try:
  669. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  670. except Exception:
  671. pass
  672. # Migration: Add external folder settings columns to library_folders
  673. try:
  674. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0"))
  675. except Exception:
  676. pass
  677. try:
  678. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0"))
  679. except Exception:
  680. pass
  681. try:
  682. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)"))
  683. except Exception:
  684. pass
  685. # Migration: Add plate_detection_enabled column to printers
  686. try:
  687. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0"))
  688. except Exception:
  689. pass
  690. # Migration: Add plate detection ROI columns to printers
  691. try:
  692. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL"))
  693. except Exception:
  694. pass
  695. try:
  696. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL"))
  697. except Exception:
  698. pass
  699. try:
  700. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL"))
  701. except Exception:
  702. pass
  703. try:
  704. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL"))
  705. except Exception:
  706. pass
  707. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  708. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  709. # SQLite requires table recreation to drop constraints
  710. try:
  711. # Check if we need to migrate (if UNIQUE constraint exists)
  712. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  713. row = result.fetchone()
  714. if row and "printer_id INTEGER UNIQUE" in (row[0] or ""):
  715. # Create new table without UNIQUE constraint on printer_id
  716. await conn.execute(
  717. text("""
  718. CREATE TABLE smart_plugs_temp (
  719. id INTEGER PRIMARY KEY,
  720. name VARCHAR(100) NOT NULL,
  721. ip_address VARCHAR(45),
  722. plug_type VARCHAR(20) DEFAULT 'tasmota',
  723. ha_entity_id VARCHAR(100),
  724. ha_power_entity VARCHAR(100),
  725. ha_energy_today_entity VARCHAR(100),
  726. ha_energy_total_entity VARCHAR(100),
  727. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  728. enabled BOOLEAN NOT NULL DEFAULT 1,
  729. auto_on BOOLEAN NOT NULL DEFAULT 1,
  730. auto_off BOOLEAN NOT NULL DEFAULT 1,
  731. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  732. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  733. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  734. username VARCHAR(50),
  735. password VARCHAR(100),
  736. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  737. power_alert_high FLOAT,
  738. power_alert_low FLOAT,
  739. power_alert_last_triggered DATETIME,
  740. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  741. schedule_on_time VARCHAR(5),
  742. schedule_off_time VARCHAR(5),
  743. show_in_switchbar BOOLEAN DEFAULT 0,
  744. last_state VARCHAR(10),
  745. last_checked DATETIME,
  746. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  747. auto_off_pending BOOLEAN DEFAULT 0,
  748. auto_off_pending_since DATETIME,
  749. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  750. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  751. )
  752. """)
  753. )
  754. # Copy data
  755. await conn.execute(
  756. text("""
  757. INSERT INTO smart_plugs_temp
  758. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  759. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  760. auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  761. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  762. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  763. show_in_switchbar, last_state, last_checked, auto_off_executed,
  764. auto_off_pending, auto_off_pending_since, created_at, updated_at
  765. FROM smart_plugs
  766. """)
  767. )
  768. # Drop old table and rename new one
  769. await conn.execute(text("DROP TABLE smart_plugs"))
  770. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  771. except Exception:
  772. pass
  773. # Migration: Add show_on_printer_card column to smart_plugs
  774. try:
  775. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1"))
  776. except Exception:
  777. pass
  778. # Migration: Add MQTT smart plug fields (legacy)
  779. try:
  780. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)"))
  781. except Exception:
  782. pass
  783. try:
  784. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)"))
  785. except Exception:
  786. pass
  787. try:
  788. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)"))
  789. except Exception:
  790. pass
  791. try:
  792. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)"))
  793. except Exception:
  794. pass
  795. try:
  796. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0"))
  797. except Exception:
  798. pass
  799. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  800. try:
  801. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)"))
  802. except Exception:
  803. pass
  804. try:
  805. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0"))
  806. except Exception:
  807. pass
  808. try:
  809. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)"))
  810. except Exception:
  811. pass
  812. try:
  813. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0"))
  814. except Exception:
  815. pass
  816. try:
  817. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)"))
  818. except Exception:
  819. pass
  820. try:
  821. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)"))
  822. except Exception:
  823. pass
  824. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  825. try:
  826. await conn.execute(
  827. text("""
  828. UPDATE smart_plugs
  829. SET mqtt_power_topic = mqtt_topic,
  830. mqtt_power_multiplier = mqtt_multiplier
  831. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  832. """)
  833. )
  834. except Exception:
  835. pass
  836. # Migration: Create groups table for permission-based access control
  837. try:
  838. await conn.execute(
  839. text("""
  840. CREATE TABLE IF NOT EXISTS groups (
  841. id INTEGER PRIMARY KEY,
  842. name VARCHAR(100) NOT NULL UNIQUE,
  843. description VARCHAR(500),
  844. permissions JSON,
  845. is_system BOOLEAN NOT NULL DEFAULT 0,
  846. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  847. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  848. )
  849. """)
  850. )
  851. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  852. except Exception:
  853. pass
  854. # Migration: Create user_groups association table
  855. try:
  856. await conn.execute(
  857. text("""
  858. CREATE TABLE IF NOT EXISTS user_groups (
  859. user_id INTEGER NOT NULL,
  860. group_id INTEGER NOT NULL,
  861. PRIMARY KEY (user_id, group_id),
  862. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  863. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  864. )
  865. """)
  866. )
  867. except Exception:
  868. pass
  869. # Migration: Add model-based queue assignment columns to print_queue
  870. try:
  871. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)"))
  872. except Exception:
  873. pass
  874. try:
  875. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT"))
  876. except Exception:
  877. pass
  878. try:
  879. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT"))
  880. except Exception:
  881. pass
  882. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  883. try:
  884. await conn.execute(text("ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1"))
  885. except Exception:
  886. pass
  887. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  888. try:
  889. await conn.execute(text("ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0"))
  890. except Exception:
  891. pass
  892. # Migration: Add queue notification event columns to notification_providers
  893. try:
  894. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0"))
  895. except Exception:
  896. pass
  897. try:
  898. await conn.execute(
  899. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  900. )
  901. except Exception:
  902. pass
  903. try:
  904. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0"))
  905. except Exception:
  906. pass
  907. try:
  908. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1"))
  909. except Exception:
  910. pass
  911. try:
  912. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1"))
  913. except Exception:
  914. pass
  915. try:
  916. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1"))
  917. except Exception:
  918. pass
  919. try:
  920. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0"))
  921. except Exception:
  922. pass
  923. # Migration: Convert absolute paths to relative paths in library_files table
  924. # This ensures backup/restore portability across different installations
  925. try:
  926. base_dir_str = str(settings.base_dir)
  927. # Ensure we have a trailing slash for clean replacement
  928. if not base_dir_str.endswith("/"):
  929. base_dir_str += "/"
  930. # Update file_path - remove base_dir prefix from absolute paths
  931. await conn.execute(
  932. text("""
  933. UPDATE library_files
  934. SET file_path = SUBSTR(file_path, LENGTH(:base_dir) + 1)
  935. WHERE file_path LIKE :pattern
  936. """),
  937. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  938. )
  939. # Update thumbnail_path - remove base_dir prefix from absolute paths
  940. await conn.execute(
  941. text("""
  942. UPDATE library_files
  943. SET thumbnail_path = SUBSTR(thumbnail_path, LENGTH(:base_dir) + 1)
  944. WHERE thumbnail_path LIKE :pattern
  945. """),
  946. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  947. )
  948. except Exception:
  949. pass
  950. async def seed_notification_templates():
  951. """Seed default notification templates if they don't exist."""
  952. from sqlalchemy import select
  953. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  954. async with async_session() as session:
  955. # Get existing template event types
  956. result = await session.execute(select(NotificationTemplate.event_type))
  957. existing_types = {row[0] for row in result.fetchall()}
  958. if not existing_types:
  959. # No templates exist - insert all defaults
  960. for template_data in DEFAULT_TEMPLATES:
  961. template = NotificationTemplate(
  962. event_type=template_data["event_type"],
  963. name=template_data["name"],
  964. title_template=template_data["title_template"],
  965. body_template=template_data["body_template"],
  966. is_default=True,
  967. )
  968. session.add(template)
  969. else:
  970. # Templates exist - only add missing ones
  971. for template_data in DEFAULT_TEMPLATES:
  972. if template_data["event_type"] not in existing_types:
  973. template = NotificationTemplate(
  974. event_type=template_data["event_type"],
  975. name=template_data["name"],
  976. title_template=template_data["title_template"],
  977. body_template=template_data["body_template"],
  978. is_default=True,
  979. )
  980. session.add(template)
  981. await session.commit()
  982. async def seed_default_groups():
  983. """Seed default groups and migrate existing users to appropriate groups.
  984. Creates the default system groups (Administrators, Operators, Viewers) if they
  985. don't exist, then migrates existing users:
  986. - Users with role='admin' -> Administrators group
  987. - Users with role='user' -> Operators group
  988. """
  989. import logging
  990. from sqlalchemy import select
  991. from backend.app.core.permissions import DEFAULT_GROUPS
  992. from backend.app.models.group import Group
  993. from backend.app.models.user import User
  994. logger = logging.getLogger(__name__)
  995. async with async_session() as session:
  996. # Get existing groups
  997. result = await session.execute(select(Group.name))
  998. existing_groups = {row[0] for row in result.fetchall()}
  999. # Create default groups if they don't exist
  1000. groups_created = []
  1001. for group_name, group_config in DEFAULT_GROUPS.items():
  1002. if group_name not in existing_groups:
  1003. group = Group(
  1004. name=group_name,
  1005. description=group_config["description"],
  1006. permissions=group_config["permissions"],
  1007. is_system=group_config["is_system"],
  1008. )
  1009. session.add(group)
  1010. groups_created.append(group_name)
  1011. logger.info(f"Created default group: {group_name}")
  1012. await session.commit()
  1013. # Migrate existing users to groups if they're not already in any group
  1014. if groups_created:
  1015. # Get the groups we need
  1016. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  1017. admin_group = admin_result.scalar_one_or_none()
  1018. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  1019. operators_group = operators_result.scalar_one_or_none()
  1020. # Get all users
  1021. users_result = await session.execute(select(User))
  1022. users = users_result.scalars().all()
  1023. for user in users:
  1024. # Skip if user already has groups
  1025. if user.groups:
  1026. continue
  1027. if user.role == "admin" and admin_group:
  1028. user.groups.append(admin_group)
  1029. logger.info(f"Migrated admin user '{user.username}' to Administrators group")
  1030. elif operators_group:
  1031. user.groups.append(operators_group)
  1032. logger.info(f"Migrated user '{user.username}' to Operators group")
  1033. await session.commit()