database.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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. kprofile_note,
  33. library,
  34. maintenance,
  35. notification,
  36. notification_template,
  37. print_queue,
  38. printer,
  39. project,
  40. project_bom,
  41. settings,
  42. smart_plug,
  43. user,
  44. )
  45. async with engine.begin() as conn:
  46. await conn.run_sync(Base.metadata.create_all)
  47. # Run migrations for new columns (SQLite doesn't auto-add columns)
  48. await run_migrations(conn)
  49. # Seed default notification templates
  50. await seed_notification_templates()
  51. async def run_migrations(conn):
  52. """Add new columns to existing tables if they don't exist."""
  53. from sqlalchemy import text
  54. # Migration: Add is_favorite column to print_archives
  55. try:
  56. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0"))
  57. except Exception:
  58. # Column already exists
  59. pass
  60. # Migration: Add content_hash column to print_archives for duplicate detection
  61. try:
  62. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)"))
  63. except Exception:
  64. # Column already exists
  65. pass
  66. # Migration: Add auto_off_executed column to smart_plugs
  67. try:
  68. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0"))
  69. except Exception:
  70. # Column already exists
  71. pass
  72. # Migration: Add on_print_stopped column to notification_providers
  73. try:
  74. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1"))
  75. except Exception:
  76. # Column already exists
  77. pass
  78. # Migration: Add source_3mf_path column to print_archives
  79. try:
  80. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)"))
  81. except Exception:
  82. # Column already exists
  83. pass
  84. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  85. try:
  86. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)"))
  87. except Exception:
  88. # Column already exists
  89. pass
  90. # Migration: Add on_maintenance_due column to notification_providers
  91. try:
  92. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0"))
  93. except Exception:
  94. # Column already exists
  95. pass
  96. # Migration: Add location column to printers for grouping
  97. try:
  98. await conn.execute(text("ALTER TABLE printers ADD COLUMN location VARCHAR(100)"))
  99. except Exception:
  100. # Column already exists
  101. pass
  102. # Migration: Add interval_type column to maintenance_types
  103. try:
  104. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'"))
  105. except Exception:
  106. # Column already exists
  107. pass
  108. # Migration: Add custom_interval_type column to printer_maintenance
  109. try:
  110. await conn.execute(text("ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)"))
  111. except Exception:
  112. # Column already exists
  113. pass
  114. # Migration: Add power alert columns to smart_plugs
  115. try:
  116. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0"))
  117. except Exception:
  118. pass
  119. try:
  120. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL"))
  121. except Exception:
  122. pass
  123. try:
  124. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL"))
  125. except Exception:
  126. pass
  127. try:
  128. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME"))
  129. except Exception:
  130. pass
  131. # Migration: Add schedule columns to smart_plugs
  132. try:
  133. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0"))
  134. except Exception:
  135. pass
  136. try:
  137. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)"))
  138. except Exception:
  139. pass
  140. try:
  141. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)"))
  142. except Exception:
  143. pass
  144. # Migration: Add daily digest columns to notification_providers
  145. try:
  146. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0"))
  147. except Exception:
  148. pass
  149. try:
  150. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)"))
  151. except Exception:
  152. pass
  153. # Migration: Add project_id column to print_archives
  154. try:
  155. await conn.execute(
  156. text("ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  157. )
  158. except Exception:
  159. pass
  160. # Migration: Add project_id column to print_queue
  161. try:
  162. await conn.execute(
  163. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  164. )
  165. except Exception:
  166. pass
  167. # Migration: Create FTS5 virtual table for archive full-text search
  168. try:
  169. await conn.execute(
  170. text("""
  171. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  172. print_name,
  173. filename,
  174. tags,
  175. notes,
  176. designer,
  177. filament_type,
  178. content='print_archives',
  179. content_rowid='id'
  180. )
  181. """)
  182. )
  183. except Exception:
  184. pass
  185. # Migration: Create triggers to keep FTS index in sync
  186. try:
  187. await conn.execute(
  188. text("""
  189. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  190. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  191. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  192. END
  193. """)
  194. )
  195. except Exception:
  196. pass
  197. try:
  198. await conn.execute(
  199. text("""
  200. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  201. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  202. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  203. END
  204. """)
  205. )
  206. except Exception:
  207. pass
  208. try:
  209. await conn.execute(
  210. text("""
  211. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  212. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  213. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  214. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  215. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  216. END
  217. """)
  218. )
  219. except Exception:
  220. pass
  221. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  222. try:
  223. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0"))
  224. except Exception:
  225. pass
  226. try:
  227. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME"))
  228. except Exception:
  229. pass
  230. # Migration: Add AMS alarm notification columns to notification_providers
  231. try:
  232. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0"))
  233. except Exception:
  234. pass
  235. try:
  236. await conn.execute(
  237. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  238. )
  239. except Exception:
  240. pass
  241. # Migration: Add AMS-HT alarm notification columns to notification_providers
  242. try:
  243. await conn.execute(
  244. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  245. )
  246. except Exception:
  247. pass
  248. try:
  249. await conn.execute(
  250. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  251. )
  252. except Exception:
  253. pass
  254. # Migration: Add plate not empty notification column to notification_providers
  255. try:
  256. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1"))
  257. except Exception:
  258. pass
  259. # Migration: Add notes column to projects (Phase 2)
  260. try:
  261. await conn.execute(text("ALTER TABLE projects ADD COLUMN notes TEXT"))
  262. except Exception:
  263. pass
  264. # Migration: Add attachments column to projects (Phase 3)
  265. try:
  266. await conn.execute(text("ALTER TABLE projects ADD COLUMN attachments JSON"))
  267. except Exception:
  268. pass
  269. # Migration: Add tags column to projects (Phase 4)
  270. try:
  271. await conn.execute(text("ALTER TABLE projects ADD COLUMN tags TEXT"))
  272. except Exception:
  273. pass
  274. # Migration: Add due_date column to projects (Phase 5)
  275. try:
  276. await conn.execute(text("ALTER TABLE projects ADD COLUMN due_date DATETIME"))
  277. except Exception:
  278. pass
  279. # Migration: Add priority column to projects (Phase 5)
  280. try:
  281. await conn.execute(text("ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'"))
  282. except Exception:
  283. pass
  284. # Migration: Add budget column to projects (Phase 6)
  285. try:
  286. await conn.execute(text("ALTER TABLE projects ADD COLUMN budget REAL"))
  287. except Exception:
  288. pass
  289. # Migration: Add is_template column to projects (Phase 8)
  290. try:
  291. await conn.execute(text("ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0"))
  292. except Exception:
  293. pass
  294. # Migration: Add template_source_id column to projects (Phase 8)
  295. try:
  296. await conn.execute(text("ALTER TABLE projects ADD COLUMN template_source_id INTEGER"))
  297. except Exception:
  298. pass
  299. # Migration: Add parent_id column to projects (Phase 10)
  300. try:
  301. await conn.execute(
  302. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  303. )
  304. except Exception:
  305. pass
  306. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  307. try:
  308. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired"))
  309. except Exception:
  310. pass
  311. # Migration: Add unit_price column to project_bom_items
  312. try:
  313. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN unit_price REAL"))
  314. except Exception:
  315. pass
  316. # Migration: Add sourcing_url column to project_bom_items
  317. try:
  318. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)"))
  319. except Exception:
  320. pass
  321. # Migration: Rename notes to remarks in project_bom_items
  322. try:
  323. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks"))
  324. except Exception:
  325. pass
  326. # Migration: Add show_in_switchbar column to smart_plugs
  327. try:
  328. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0"))
  329. except Exception:
  330. pass
  331. # Migration: Add runtime tracking columns to printers
  332. try:
  333. await conn.execute(text("ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0"))
  334. except Exception:
  335. pass
  336. try:
  337. await conn.execute(text("ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME"))
  338. except Exception:
  339. pass
  340. # Migration: Add quantity column to print_archives for tracking item count
  341. try:
  342. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1"))
  343. except Exception:
  344. pass
  345. # Migration: Add manual_start column to print_queue for staged prints
  346. try:
  347. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0"))
  348. except Exception:
  349. pass
  350. # Migration: Add wiki_url column to maintenance_types for documentation links
  351. try:
  352. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)"))
  353. except Exception:
  354. pass
  355. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  356. try:
  357. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT"))
  358. except Exception:
  359. pass
  360. # Migration: Add target_parts_count column to projects for tracking total parts needed
  361. try:
  362. await conn.execute(text("ALTER TABLE projects ADD COLUMN target_parts_count INTEGER"))
  363. except Exception:
  364. pass
  365. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  366. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  367. try:
  368. # Check if printer_id is already nullable by trying to insert NULL
  369. # This is a safe check that won't affect existing data
  370. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  371. row = result.fetchone()
  372. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  373. # Need to migrate - printer_id is currently NOT NULL
  374. await conn.execute(
  375. text("""
  376. CREATE TABLE print_queue_new (
  377. id INTEGER PRIMARY KEY,
  378. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  379. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  380. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  381. position INTEGER DEFAULT 0,
  382. scheduled_time DATETIME,
  383. manual_start BOOLEAN DEFAULT 0,
  384. require_previous_success BOOLEAN DEFAULT 0,
  385. auto_off_after BOOLEAN DEFAULT 0,
  386. ams_mapping TEXT,
  387. status VARCHAR(20) DEFAULT 'pending',
  388. started_at DATETIME,
  389. completed_at DATETIME,
  390. error_message TEXT,
  391. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  392. )
  393. """)
  394. )
  395. await conn.execute(
  396. text("""
  397. INSERT INTO print_queue_new
  398. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  399. manual_start, require_previous_success, auto_off_after, ams_mapping,
  400. status, started_at, completed_at, error_message, created_at
  401. FROM print_queue
  402. """)
  403. )
  404. await conn.execute(text("DROP TABLE print_queue"))
  405. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  406. except Exception:
  407. pass
  408. # Migration: Add plug_type column to smart_plugs for HA integration
  409. try:
  410. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'"))
  411. except Exception:
  412. pass
  413. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  414. try:
  415. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)"))
  416. except Exception:
  417. pass
  418. # Migration: Add project_id column to library_folders for linking folders to projects
  419. try:
  420. await conn.execute(
  421. text("ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  422. )
  423. except Exception:
  424. pass
  425. # Migration: Add archive_id column to library_folders for linking folders to archives
  426. try:
  427. await conn.execute(
  428. text(
  429. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  430. )
  431. )
  432. except Exception:
  433. pass
  434. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  435. try:
  436. # Check if ip_address is currently NOT NULL
  437. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  438. row = result.fetchone()
  439. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  440. # Need to migrate - ip_address is currently NOT NULL
  441. await conn.execute(
  442. text("""
  443. CREATE TABLE smart_plugs_new (
  444. id INTEGER PRIMARY KEY,
  445. name VARCHAR(100) NOT NULL,
  446. ip_address VARCHAR(45),
  447. plug_type VARCHAR(20) DEFAULT 'tasmota',
  448. ha_entity_id VARCHAR(100),
  449. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  450. enabled BOOLEAN NOT NULL DEFAULT 1,
  451. auto_on BOOLEAN NOT NULL DEFAULT 1,
  452. auto_off BOOLEAN NOT NULL DEFAULT 1,
  453. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  454. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  455. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  456. username VARCHAR(50),
  457. password VARCHAR(100),
  458. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  459. power_alert_high FLOAT,
  460. power_alert_low FLOAT,
  461. power_alert_last_triggered DATETIME,
  462. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  463. schedule_on_time VARCHAR(5),
  464. schedule_off_time VARCHAR(5),
  465. show_in_switchbar BOOLEAN DEFAULT 0,
  466. last_state VARCHAR(10),
  467. last_checked DATETIME,
  468. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  469. auto_off_pending BOOLEAN DEFAULT 0,
  470. auto_off_pending_since DATETIME,
  471. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  472. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  473. )
  474. """)
  475. )
  476. await conn.execute(
  477. text("""
  478. INSERT INTO smart_plugs_new
  479. SELECT id, name, ip_address,
  480. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  481. enabled, auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  482. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  483. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  484. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  485. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  486. FROM smart_plugs
  487. """)
  488. )
  489. await conn.execute(text("DROP TABLE smart_plugs"))
  490. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  491. except Exception:
  492. pass
  493. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  494. try:
  495. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN plate_id INTEGER"))
  496. except Exception:
  497. pass
  498. # Migration: Add print options columns to print_queue
  499. try:
  500. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1"))
  501. except Exception:
  502. pass
  503. try:
  504. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0"))
  505. except Exception:
  506. pass
  507. try:
  508. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1"))
  509. except Exception:
  510. pass
  511. try:
  512. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0"))
  513. except Exception:
  514. pass
  515. try:
  516. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0"))
  517. except Exception:
  518. pass
  519. try:
  520. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1"))
  521. except Exception:
  522. pass
  523. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  524. # This allows queue items to reference library files directly (archive created at print start)
  525. try:
  526. await conn.execute(
  527. text(
  528. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  529. )
  530. )
  531. except Exception:
  532. pass
  533. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  534. try:
  535. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  536. row = result.fetchone()
  537. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  538. # Need to migrate - archive_id is currently NOT NULL
  539. await conn.execute(
  540. text("""
  541. CREATE TABLE print_queue_new2 (
  542. id INTEGER PRIMARY KEY,
  543. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  544. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  545. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  546. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  547. position INTEGER DEFAULT 0,
  548. scheduled_time DATETIME,
  549. manual_start BOOLEAN DEFAULT 0,
  550. require_previous_success BOOLEAN DEFAULT 0,
  551. auto_off_after BOOLEAN DEFAULT 0,
  552. ams_mapping TEXT,
  553. plate_id INTEGER,
  554. bed_levelling BOOLEAN DEFAULT 1,
  555. flow_cali BOOLEAN DEFAULT 0,
  556. vibration_cali BOOLEAN DEFAULT 1,
  557. layer_inspect BOOLEAN DEFAULT 0,
  558. timelapse BOOLEAN DEFAULT 0,
  559. use_ams BOOLEAN DEFAULT 1,
  560. status VARCHAR(20) DEFAULT 'pending',
  561. started_at DATETIME,
  562. completed_at DATETIME,
  563. error_message TEXT,
  564. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  565. )
  566. """)
  567. )
  568. await conn.execute(
  569. text("""
  570. INSERT INTO print_queue_new2
  571. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  572. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  573. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  574. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  575. status, started_at, completed_at, error_message, created_at
  576. FROM print_queue
  577. """)
  578. )
  579. await conn.execute(text("DROP TABLE print_queue"))
  580. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  581. except Exception:
  582. pass
  583. # Migration: Add HA energy sensor entity columns to smart_plugs
  584. try:
  585. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)"))
  586. except Exception:
  587. pass
  588. try:
  589. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)"))
  590. except Exception:
  591. pass
  592. try:
  593. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)"))
  594. except Exception:
  595. pass
  596. # Migration: Create users table for authentication
  597. try:
  598. await conn.execute(
  599. text("""
  600. CREATE TABLE IF NOT EXISTS users (
  601. id INTEGER PRIMARY KEY,
  602. username VARCHAR(100) NOT NULL UNIQUE,
  603. password_hash VARCHAR(255) NOT NULL,
  604. role VARCHAR(20) NOT NULL DEFAULT 'user',
  605. is_active BOOLEAN NOT NULL DEFAULT 1,
  606. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  607. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  608. )
  609. """)
  610. )
  611. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  612. except Exception:
  613. pass
  614. # Migration: Add external camera columns to printers
  615. try:
  616. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)"))
  617. except Exception:
  618. pass
  619. try:
  620. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)"))
  621. except Exception:
  622. pass
  623. try:
  624. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0"))
  625. except Exception:
  626. pass
  627. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  628. try:
  629. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)"))
  630. except Exception:
  631. pass
  632. # Migration: Add is_external column to library_files for external cloud files
  633. try:
  634. await conn.execute(text("ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  635. except Exception:
  636. pass
  637. # Migration: Add project_id column to library_files
  638. try:
  639. await conn.execute(
  640. text("ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  641. )
  642. except Exception:
  643. pass
  644. # Migration: Add is_external column to library_folders for external cloud folders
  645. try:
  646. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  647. except Exception:
  648. pass
  649. # Migration: Add external folder settings columns to library_folders
  650. try:
  651. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0"))
  652. except Exception:
  653. pass
  654. try:
  655. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0"))
  656. except Exception:
  657. pass
  658. try:
  659. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)"))
  660. except Exception:
  661. pass
  662. # Migration: Add plate_detection_enabled column to printers
  663. try:
  664. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0"))
  665. except Exception:
  666. pass
  667. # Migration: Add plate detection ROI columns to printers
  668. try:
  669. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL"))
  670. except Exception:
  671. pass
  672. try:
  673. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL"))
  674. except Exception:
  675. pass
  676. try:
  677. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL"))
  678. except Exception:
  679. pass
  680. try:
  681. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL"))
  682. except Exception:
  683. pass
  684. async def seed_notification_templates():
  685. """Seed default notification templates if they don't exist."""
  686. from sqlalchemy import select
  687. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  688. async with async_session() as session:
  689. # Get existing template event types
  690. result = await session.execute(select(NotificationTemplate.event_type))
  691. existing_types = {row[0] for row in result.fetchall()}
  692. if not existing_types:
  693. # No templates exist - insert all defaults
  694. for template_data in DEFAULT_TEMPLATES:
  695. template = NotificationTemplate(
  696. event_type=template_data["event_type"],
  697. name=template_data["name"],
  698. title_template=template_data["title_template"],
  699. body_template=template_data["body_template"],
  700. is_default=True,
  701. )
  702. session.add(template)
  703. else:
  704. # Templates exist - only add missing ones
  705. for template_data in DEFAULT_TEMPLATES:
  706. if template_data["event_type"] not in existing_types:
  707. template = NotificationTemplate(
  708. event_type=template_data["event_type"],
  709. name=template_data["name"],
  710. title_template=template_data["title_template"],
  711. body_template=template_data["body_template"],
  712. is_default=True,
  713. )
  714. session.add(template)
  715. await session.commit()