database.py 40 KB

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