database.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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: Add sliced_for_model column to print_archives for printer model from 3MF
  689. try:
  690. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)"))
  691. except Exception:
  692. pass
  693. # Migration: Add target_model column to print_queue for model-based assignment
  694. try:
  695. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)"))
  696. except Exception:
  697. pass
  698. # Migration: Add required_filament_types column to print_queue for filament validation
  699. try:
  700. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT"))
  701. except Exception:
  702. pass
  703. # Migration: Add waiting_reason column to print_queue for status feedback
  704. try:
  705. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT"))
  706. except Exception:
  707. pass
  708. # Migration: Add queue notification event columns to notification_providers
  709. queue_notification_columns = [
  710. ("on_queue_job_added", "BOOLEAN DEFAULT 0"),
  711. ("on_queue_job_assigned", "BOOLEAN DEFAULT 0"),
  712. ("on_queue_job_started", "BOOLEAN DEFAULT 0"),
  713. ("on_queue_job_waiting", "BOOLEAN DEFAULT 1"),
  714. ("on_queue_job_skipped", "BOOLEAN DEFAULT 1"),
  715. ("on_queue_job_failed", "BOOLEAN DEFAULT 1"),
  716. ("on_queue_completed", "BOOLEAN DEFAULT 0"),
  717. ]
  718. for col_name, col_def in queue_notification_columns:
  719. try:
  720. await conn.execute(text(f"ALTER TABLE notification_providers ADD COLUMN {col_name} {col_def}"))
  721. except Exception:
  722. pass
  723. # Migration: Create groups table for permission-based access control
  724. try:
  725. await conn.execute(
  726. text("""
  727. CREATE TABLE IF NOT EXISTS groups (
  728. id INTEGER PRIMARY KEY,
  729. name VARCHAR(100) NOT NULL UNIQUE,
  730. description VARCHAR(500),
  731. permissions JSON,
  732. is_system BOOLEAN NOT NULL DEFAULT 0,
  733. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  734. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  735. )
  736. """)
  737. )
  738. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  739. except Exception:
  740. pass
  741. # Migration: Create user_groups association table
  742. try:
  743. await conn.execute(
  744. text("""
  745. CREATE TABLE IF NOT EXISTS user_groups (
  746. user_id INTEGER NOT NULL,
  747. group_id INTEGER NOT NULL,
  748. PRIMARY KEY (user_id, group_id),
  749. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  750. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  751. )
  752. """)
  753. )
  754. except Exception:
  755. pass
  756. async def seed_notification_templates():
  757. """Seed default notification templates if they don't exist."""
  758. from sqlalchemy import select
  759. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  760. async with async_session() as session:
  761. # Get existing template event types
  762. result = await session.execute(select(NotificationTemplate.event_type))
  763. existing_types = {row[0] for row in result.fetchall()}
  764. if not existing_types:
  765. # No templates exist - insert all defaults
  766. for template_data in DEFAULT_TEMPLATES:
  767. template = NotificationTemplate(
  768. event_type=template_data["event_type"],
  769. name=template_data["name"],
  770. title_template=template_data["title_template"],
  771. body_template=template_data["body_template"],
  772. is_default=True,
  773. )
  774. session.add(template)
  775. else:
  776. # Templates exist - only add missing ones
  777. for template_data in DEFAULT_TEMPLATES:
  778. if template_data["event_type"] not in existing_types:
  779. template = NotificationTemplate(
  780. event_type=template_data["event_type"],
  781. name=template_data["name"],
  782. title_template=template_data["title_template"],
  783. body_template=template_data["body_template"],
  784. is_default=True,
  785. )
  786. session.add(template)
  787. await session.commit()
  788. async def seed_default_groups():
  789. """Seed default groups and migrate existing users to appropriate groups.
  790. Creates the default system groups (Administrators, Operators, Viewers) if they
  791. don't exist, then migrates existing users:
  792. - Users with role='admin' -> Administrators group
  793. - Users with role='user' -> Operators group
  794. """
  795. import logging
  796. from sqlalchemy import select
  797. from backend.app.core.permissions import DEFAULT_GROUPS
  798. from backend.app.models.group import Group
  799. from backend.app.models.user import User
  800. logger = logging.getLogger(__name__)
  801. async with async_session() as session:
  802. # Get existing groups
  803. result = await session.execute(select(Group.name))
  804. existing_groups = {row[0] for row in result.fetchall()}
  805. # Create default groups if they don't exist
  806. groups_created = []
  807. for group_name, group_config in DEFAULT_GROUPS.items():
  808. if group_name not in existing_groups:
  809. group = Group(
  810. name=group_name,
  811. description=group_config["description"],
  812. permissions=group_config["permissions"],
  813. is_system=group_config["is_system"],
  814. )
  815. session.add(group)
  816. groups_created.append(group_name)
  817. logger.info(f"Created default group: {group_name}")
  818. await session.commit()
  819. # Migrate existing users to groups if they're not already in any group
  820. if groups_created:
  821. # Get the groups we need
  822. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  823. admin_group = admin_result.scalar_one_or_none()
  824. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  825. operators_group = operators_result.scalar_one_or_none()
  826. # Get all users
  827. users_result = await session.execute(select(User))
  828. users = users_result.scalars().all()
  829. for user in users:
  830. # Skip if user already has groups
  831. if user.groups:
  832. continue
  833. if user.role == "admin" and admin_group:
  834. user.groups.append(admin_group)
  835. logger.info(f"Migrated admin user '{user.username}' to Administrators group")
  836. elif operators_group:
  837. user.groups.append(operators_group)
  838. logger.info(f"Migrated user '{user.username}' to Operators group")
  839. await session.commit()