database.py 34 KB

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