database.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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 notes column to projects (Phase 2)
  255. try:
  256. await conn.execute(text("ALTER TABLE projects ADD COLUMN notes TEXT"))
  257. except Exception:
  258. pass
  259. # Migration: Add attachments column to projects (Phase 3)
  260. try:
  261. await conn.execute(text("ALTER TABLE projects ADD COLUMN attachments JSON"))
  262. except Exception:
  263. pass
  264. # Migration: Add tags column to projects (Phase 4)
  265. try:
  266. await conn.execute(text("ALTER TABLE projects ADD COLUMN tags TEXT"))
  267. except Exception:
  268. pass
  269. # Migration: Add due_date column to projects (Phase 5)
  270. try:
  271. await conn.execute(text("ALTER TABLE projects ADD COLUMN due_date DATETIME"))
  272. except Exception:
  273. pass
  274. # Migration: Add priority column to projects (Phase 5)
  275. try:
  276. await conn.execute(text("ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'"))
  277. except Exception:
  278. pass
  279. # Migration: Add budget column to projects (Phase 6)
  280. try:
  281. await conn.execute(text("ALTER TABLE projects ADD COLUMN budget REAL"))
  282. except Exception:
  283. pass
  284. # Migration: Add is_template column to projects (Phase 8)
  285. try:
  286. await conn.execute(text("ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0"))
  287. except Exception:
  288. pass
  289. # Migration: Add template_source_id column to projects (Phase 8)
  290. try:
  291. await conn.execute(text("ALTER TABLE projects ADD COLUMN template_source_id INTEGER"))
  292. except Exception:
  293. pass
  294. # Migration: Add parent_id column to projects (Phase 10)
  295. try:
  296. await conn.execute(
  297. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  298. )
  299. except Exception:
  300. pass
  301. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  302. try:
  303. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired"))
  304. except Exception:
  305. pass
  306. # Migration: Add unit_price column to project_bom_items
  307. try:
  308. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN unit_price REAL"))
  309. except Exception:
  310. pass
  311. # Migration: Add sourcing_url column to project_bom_items
  312. try:
  313. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)"))
  314. except Exception:
  315. pass
  316. # Migration: Rename notes to remarks in project_bom_items
  317. try:
  318. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks"))
  319. except Exception:
  320. pass
  321. # Migration: Add show_in_switchbar column to smart_plugs
  322. try:
  323. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0"))
  324. except Exception:
  325. pass
  326. # Migration: Add runtime tracking columns to printers
  327. try:
  328. await conn.execute(text("ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0"))
  329. except Exception:
  330. pass
  331. try:
  332. await conn.execute(text("ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME"))
  333. except Exception:
  334. pass
  335. # Migration: Add quantity column to print_archives for tracking item count
  336. try:
  337. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1"))
  338. except Exception:
  339. pass
  340. # Migration: Add manual_start column to print_queue for staged prints
  341. try:
  342. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0"))
  343. except Exception:
  344. pass
  345. # Migration: Add wiki_url column to maintenance_types for documentation links
  346. try:
  347. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)"))
  348. except Exception:
  349. pass
  350. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  351. try:
  352. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT"))
  353. except Exception:
  354. pass
  355. # Migration: Add target_parts_count column to projects for tracking total parts needed
  356. try:
  357. await conn.execute(text("ALTER TABLE projects ADD COLUMN target_parts_count INTEGER"))
  358. except Exception:
  359. pass
  360. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  361. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  362. try:
  363. # Check if printer_id is already nullable by trying to insert NULL
  364. # This is a safe check that won't affect existing data
  365. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  366. row = result.fetchone()
  367. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  368. # Need to migrate - printer_id is currently NOT NULL
  369. await conn.execute(
  370. text("""
  371. CREATE TABLE print_queue_new (
  372. id INTEGER PRIMARY KEY,
  373. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  374. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  375. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  376. position INTEGER DEFAULT 0,
  377. scheduled_time DATETIME,
  378. manual_start BOOLEAN DEFAULT 0,
  379. require_previous_success BOOLEAN DEFAULT 0,
  380. auto_off_after BOOLEAN DEFAULT 0,
  381. ams_mapping TEXT,
  382. status VARCHAR(20) DEFAULT 'pending',
  383. started_at DATETIME,
  384. completed_at DATETIME,
  385. error_message TEXT,
  386. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  387. )
  388. """)
  389. )
  390. await conn.execute(
  391. text("""
  392. INSERT INTO print_queue_new
  393. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  394. manual_start, require_previous_success, auto_off_after, ams_mapping,
  395. status, started_at, completed_at, error_message, created_at
  396. FROM print_queue
  397. """)
  398. )
  399. await conn.execute(text("DROP TABLE print_queue"))
  400. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  401. except Exception:
  402. pass
  403. # Migration: Add plug_type column to smart_plugs for HA integration
  404. try:
  405. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'"))
  406. except Exception:
  407. pass
  408. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  409. try:
  410. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)"))
  411. except Exception:
  412. pass
  413. # Migration: Add project_id column to library_folders for linking folders to projects
  414. try:
  415. await conn.execute(
  416. text("ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  417. )
  418. except Exception:
  419. pass
  420. # Migration: Add archive_id column to library_folders for linking folders to archives
  421. try:
  422. await conn.execute(
  423. text(
  424. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  425. )
  426. )
  427. except Exception:
  428. pass
  429. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  430. try:
  431. # Check if ip_address is currently NOT NULL
  432. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  433. row = result.fetchone()
  434. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  435. # Need to migrate - ip_address is currently NOT NULL
  436. await conn.execute(
  437. text("""
  438. CREATE TABLE smart_plugs_new (
  439. id INTEGER PRIMARY KEY,
  440. name VARCHAR(100) NOT NULL,
  441. ip_address VARCHAR(45),
  442. plug_type VARCHAR(20) DEFAULT 'tasmota',
  443. ha_entity_id VARCHAR(100),
  444. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  445. enabled BOOLEAN NOT NULL DEFAULT 1,
  446. auto_on BOOLEAN NOT NULL DEFAULT 1,
  447. auto_off BOOLEAN NOT NULL DEFAULT 1,
  448. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  449. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  450. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  451. username VARCHAR(50),
  452. password VARCHAR(100),
  453. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  454. power_alert_high FLOAT,
  455. power_alert_low FLOAT,
  456. power_alert_last_triggered DATETIME,
  457. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  458. schedule_on_time VARCHAR(5),
  459. schedule_off_time VARCHAR(5),
  460. show_in_switchbar BOOLEAN DEFAULT 0,
  461. last_state VARCHAR(10),
  462. last_checked DATETIME,
  463. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  464. auto_off_pending BOOLEAN DEFAULT 0,
  465. auto_off_pending_since DATETIME,
  466. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  467. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  468. )
  469. """)
  470. )
  471. await conn.execute(
  472. text("""
  473. INSERT INTO smart_plugs_new
  474. SELECT id, name, ip_address,
  475. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  476. enabled, auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  477. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  478. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  479. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  480. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  481. FROM smart_plugs
  482. """)
  483. )
  484. await conn.execute(text("DROP TABLE smart_plugs"))
  485. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  486. except Exception:
  487. pass
  488. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  489. try:
  490. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN plate_id INTEGER"))
  491. except Exception:
  492. pass
  493. # Migration: Add print options columns to print_queue
  494. try:
  495. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1"))
  496. except Exception:
  497. pass
  498. try:
  499. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0"))
  500. except Exception:
  501. pass
  502. try:
  503. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1"))
  504. except Exception:
  505. pass
  506. try:
  507. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0"))
  508. except Exception:
  509. pass
  510. try:
  511. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0"))
  512. except Exception:
  513. pass
  514. try:
  515. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1"))
  516. except Exception:
  517. pass
  518. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  519. # This allows queue items to reference library files directly (archive created at print start)
  520. try:
  521. await conn.execute(
  522. text(
  523. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  524. )
  525. )
  526. except Exception:
  527. pass
  528. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  529. try:
  530. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  531. row = result.fetchone()
  532. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  533. # Need to migrate - archive_id is currently NOT NULL
  534. await conn.execute(
  535. text("""
  536. CREATE TABLE print_queue_new2 (
  537. id INTEGER PRIMARY KEY,
  538. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  539. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  540. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  541. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  542. position INTEGER DEFAULT 0,
  543. scheduled_time DATETIME,
  544. manual_start BOOLEAN DEFAULT 0,
  545. require_previous_success BOOLEAN DEFAULT 0,
  546. auto_off_after BOOLEAN DEFAULT 0,
  547. ams_mapping TEXT,
  548. plate_id INTEGER,
  549. bed_levelling BOOLEAN DEFAULT 1,
  550. flow_cali BOOLEAN DEFAULT 0,
  551. vibration_cali BOOLEAN DEFAULT 1,
  552. layer_inspect BOOLEAN DEFAULT 0,
  553. timelapse BOOLEAN DEFAULT 0,
  554. use_ams BOOLEAN DEFAULT 1,
  555. status VARCHAR(20) DEFAULT 'pending',
  556. started_at DATETIME,
  557. completed_at DATETIME,
  558. error_message TEXT,
  559. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  560. )
  561. """)
  562. )
  563. await conn.execute(
  564. text("""
  565. INSERT INTO print_queue_new2
  566. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  567. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  568. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  569. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  570. status, started_at, completed_at, error_message, created_at
  571. FROM print_queue
  572. """)
  573. )
  574. await conn.execute(text("DROP TABLE print_queue"))
  575. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  576. except Exception:
  577. pass
  578. # Migration: Add HA energy sensor entity columns to smart_plugs
  579. try:
  580. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)"))
  581. except Exception:
  582. pass
  583. try:
  584. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)"))
  585. except Exception:
  586. pass
  587. try:
  588. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)"))
  589. except Exception:
  590. pass
  591. # Migration: Create users table for authentication
  592. try:
  593. await conn.execute(
  594. text("""
  595. CREATE TABLE IF NOT EXISTS users (
  596. id INTEGER PRIMARY KEY,
  597. username VARCHAR(100) NOT NULL UNIQUE,
  598. password_hash VARCHAR(255) NOT NULL,
  599. role VARCHAR(20) NOT NULL DEFAULT 'user',
  600. is_active BOOLEAN NOT NULL DEFAULT 1,
  601. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  602. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  603. )
  604. """)
  605. )
  606. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  607. except Exception:
  608. pass
  609. # Migration: Add external camera columns to printers
  610. try:
  611. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)"))
  612. except Exception:
  613. pass
  614. try:
  615. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)"))
  616. except Exception:
  617. pass
  618. try:
  619. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0"))
  620. except Exception:
  621. pass
  622. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  623. try:
  624. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)"))
  625. except Exception:
  626. pass
  627. # Migration: Add is_external column to library_files for external cloud files
  628. try:
  629. await conn.execute(text("ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  630. except Exception:
  631. pass
  632. # Migration: Add project_id column to library_files
  633. try:
  634. await conn.execute(
  635. text("ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  636. )
  637. except Exception:
  638. pass
  639. # Migration: Add is_external column to library_folders for external cloud folders
  640. try:
  641. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  642. except Exception:
  643. pass
  644. # Migration: Add external folder settings columns to library_folders
  645. try:
  646. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0"))
  647. except Exception:
  648. pass
  649. try:
  650. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0"))
  651. except Exception:
  652. pass
  653. try:
  654. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)"))
  655. except Exception:
  656. pass
  657. async def seed_notification_templates():
  658. """Seed default notification templates if they don't exist."""
  659. from sqlalchemy import select
  660. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  661. async with async_session() as session:
  662. # Check if templates already exist
  663. result = await session.execute(select(NotificationTemplate).limit(1))
  664. if result.scalar_one_or_none() is not None:
  665. # Templates already seeded
  666. return
  667. # Insert default templates
  668. for template_data in DEFAULT_TEMPLATES:
  669. template = NotificationTemplate(
  670. event_type=template_data["event_type"],
  671. name=template_data["name"],
  672. title_template=template_data["title_template"],
  673. body_template=template_data["body_template"],
  674. is_default=True,
  675. )
  676. session.add(template)
  677. await session.commit()