database.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  1. from sqlalchemy import event
  2. from sqlalchemy.exc import OperationalError
  3. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
  4. from sqlalchemy.orm import DeclarativeBase
  5. from backend.app.core.config import settings
  6. def _set_sqlite_pragmas(dbapi_conn, connection_record):
  7. """Set SQLite pragmas on each new connection for concurrency and performance."""
  8. cursor = dbapi_conn.cursor()
  9. # WAL mode allows concurrent readers + one writer (vs default DELETE mode which locks entirely)
  10. cursor.execute("PRAGMA journal_mode = WAL")
  11. # Wait up to 5 seconds when the database is locked instead of failing immediately
  12. cursor.execute("PRAGMA busy_timeout = 5000")
  13. cursor.execute("PRAGMA synchronous = NORMAL")
  14. cursor.close()
  15. engine = create_async_engine(
  16. settings.database_url,
  17. echo=settings.debug,
  18. )
  19. # Register the pragma listener on the underlying sync engine
  20. event.listen(engine.sync_engine, "connect", _set_sqlite_pragmas)
  21. async_session = async_sessionmaker(
  22. engine,
  23. class_=AsyncSession,
  24. expire_on_commit=False,
  25. )
  26. async def close_all_connections():
  27. """Close all database connections for backup/restore operations."""
  28. global engine
  29. await engine.dispose()
  30. async def reinitialize_database():
  31. """Reinitialize database connection after restore."""
  32. global engine, async_session
  33. engine = create_async_engine(
  34. settings.database_url,
  35. echo=settings.debug,
  36. )
  37. event.listen(engine.sync_engine, "connect", _set_sqlite_pragmas)
  38. async_session = async_sessionmaker(
  39. engine,
  40. class_=AsyncSession,
  41. expire_on_commit=False,
  42. )
  43. class Base(DeclarativeBase):
  44. pass
  45. async def get_db() -> AsyncSession:
  46. async with async_session() as session:
  47. try:
  48. yield session
  49. await session.commit()
  50. except Exception:
  51. await session.rollback()
  52. raise
  53. finally:
  54. await session.close()
  55. async def init_db():
  56. # Import models to register them with SQLAlchemy
  57. from backend.app.models import ( # noqa: F401
  58. active_print_spoolman,
  59. ams_history,
  60. api_key,
  61. archive,
  62. bug_report,
  63. color_catalog,
  64. external_link,
  65. filament,
  66. github_backup,
  67. group,
  68. kprofile_note,
  69. library,
  70. local_preset,
  71. maintenance,
  72. notification,
  73. notification_template,
  74. orca_base_cache,
  75. pending_upload,
  76. print_log,
  77. print_queue,
  78. printer,
  79. project,
  80. project_bom,
  81. settings,
  82. slot_preset,
  83. smart_plug,
  84. spool,
  85. spool_assignment,
  86. spool_catalog,
  87. spool_k_profile,
  88. spool_usage_history,
  89. spoolbuddy_device,
  90. user,
  91. virtual_printer,
  92. )
  93. async with engine.begin() as conn:
  94. await conn.run_sync(Base.metadata.create_all)
  95. # Run migrations for new columns (SQLite doesn't auto-add columns)
  96. await run_migrations(conn)
  97. # Seed default notification templates
  98. await seed_notification_templates()
  99. # Seed default groups and migrate existing users
  100. await seed_default_groups()
  101. # Seed default catalog entries
  102. await seed_spool_catalog()
  103. await seed_color_catalog()
  104. async def run_migrations(conn):
  105. """Add new columns to existing tables if they don't exist."""
  106. from sqlalchemy import text
  107. # Migration: Add is_favorite column to print_archives
  108. try:
  109. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0"))
  110. except OperationalError:
  111. # Column already exists
  112. pass
  113. # Migration: Add content_hash column to print_archives for duplicate detection
  114. try:
  115. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)"))
  116. except OperationalError:
  117. # Column already exists
  118. pass
  119. # Migration: Add auto_off_executed column to smart_plugs
  120. try:
  121. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0"))
  122. except OperationalError:
  123. # Column already exists
  124. pass
  125. # Migration: Add on_print_stopped column to notification_providers
  126. try:
  127. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1"))
  128. except OperationalError:
  129. # Column already exists
  130. pass
  131. # Migration: Add source_3mf_path column to print_archives
  132. try:
  133. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)"))
  134. except OperationalError:
  135. # Column already exists
  136. pass
  137. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  138. try:
  139. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)"))
  140. except OperationalError:
  141. # Column already exists
  142. pass
  143. # Migration: Add on_maintenance_due column to notification_providers
  144. try:
  145. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0"))
  146. except OperationalError:
  147. # Column already exists
  148. pass
  149. # Migration: Add location column to printers for grouping
  150. try:
  151. await conn.execute(text("ALTER TABLE printers ADD COLUMN location VARCHAR(100)"))
  152. except OperationalError:
  153. # Column already exists
  154. pass
  155. # Migration: Add interval_type column to maintenance_types
  156. try:
  157. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'"))
  158. except OperationalError:
  159. # Column already exists
  160. pass
  161. # Migration: Add is_deleted column to maintenance_types for soft-deletes
  162. try:
  163. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN is_deleted BOOLEAN DEFAULT 0"))
  164. except OperationalError:
  165. # Column already exists
  166. pass
  167. # Migration: Add custom_interval_type column to printer_maintenance
  168. try:
  169. await conn.execute(text("ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)"))
  170. except OperationalError:
  171. # Column already exists
  172. pass
  173. # Migration: Add power alert columns to smart_plugs
  174. try:
  175. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0"))
  176. except OperationalError:
  177. pass # Already applied
  178. try:
  179. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL"))
  180. except OperationalError:
  181. pass # Already applied
  182. try:
  183. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL"))
  184. except OperationalError:
  185. pass # Already applied
  186. try:
  187. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME"))
  188. except OperationalError:
  189. pass # Already applied
  190. # Migration: Add schedule columns to smart_plugs
  191. try:
  192. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0"))
  193. except OperationalError:
  194. pass # Already applied
  195. try:
  196. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)"))
  197. except OperationalError:
  198. pass # Already applied
  199. try:
  200. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)"))
  201. except OperationalError:
  202. pass # Already applied
  203. # Migration: Add daily digest columns to notification_providers
  204. try:
  205. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0"))
  206. except OperationalError:
  207. pass # Already applied
  208. try:
  209. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)"))
  210. except OperationalError:
  211. pass # Already applied
  212. # Migration: Add project_id column to print_archives
  213. try:
  214. await conn.execute(
  215. text("ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  216. )
  217. except OperationalError:
  218. pass # Already applied
  219. # Migration: Add project_id column to print_queue
  220. try:
  221. await conn.execute(
  222. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  223. )
  224. except OperationalError:
  225. pass # Already applied
  226. # Migration: Create FTS5 virtual table for archive full-text search
  227. try:
  228. await conn.execute(
  229. text("""
  230. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  231. print_name,
  232. filename,
  233. tags,
  234. notes,
  235. designer,
  236. filament_type,
  237. content='print_archives',
  238. content_rowid='id'
  239. )
  240. """)
  241. )
  242. except OperationalError:
  243. pass # Already applied
  244. # Migration: Create triggers to keep FTS index in sync
  245. try:
  246. await conn.execute(
  247. text("""
  248. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  249. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  250. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  251. END
  252. """)
  253. )
  254. except OperationalError:
  255. pass # Already applied
  256. try:
  257. await conn.execute(
  258. text("""
  259. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  260. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  261. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  262. END
  263. """)
  264. )
  265. except OperationalError:
  266. pass # Already applied
  267. try:
  268. await conn.execute(
  269. text("""
  270. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  271. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  272. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  273. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  274. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  275. END
  276. """)
  277. )
  278. except OperationalError:
  279. pass # Already applied
  280. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  281. try:
  282. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0"))
  283. except OperationalError:
  284. pass # Already applied
  285. try:
  286. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME"))
  287. except OperationalError:
  288. pass # Already applied
  289. # Migration: Add AMS alarm notification columns to notification_providers
  290. try:
  291. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0"))
  292. except OperationalError:
  293. pass # Already applied
  294. try:
  295. await conn.execute(
  296. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  297. )
  298. except OperationalError:
  299. pass # Already applied
  300. # Migration: Add AMS-HT alarm notification columns to notification_providers
  301. try:
  302. await conn.execute(
  303. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  304. )
  305. except OperationalError:
  306. pass # Already applied
  307. try:
  308. await conn.execute(
  309. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  310. )
  311. except OperationalError:
  312. pass # Already applied
  313. # Migration: Add plate not empty notification column to notification_providers
  314. try:
  315. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1"))
  316. except OperationalError:
  317. pass # Already applied
  318. # Migration: Add notes column to projects (Phase 2)
  319. try:
  320. await conn.execute(text("ALTER TABLE projects ADD COLUMN notes TEXT"))
  321. except OperationalError:
  322. pass # Already applied
  323. # Migration: Add attachments column to projects (Phase 3)
  324. try:
  325. await conn.execute(text("ALTER TABLE projects ADD COLUMN attachments JSON"))
  326. except OperationalError:
  327. pass # Already applied
  328. # Migration: Add tags column to projects (Phase 4)
  329. try:
  330. await conn.execute(text("ALTER TABLE projects ADD COLUMN tags TEXT"))
  331. except OperationalError:
  332. pass # Already applied
  333. # Migration: Add due_date column to projects (Phase 5)
  334. try:
  335. await conn.execute(text("ALTER TABLE projects ADD COLUMN due_date DATETIME"))
  336. except OperationalError:
  337. pass # Already applied
  338. # Migration: Add priority column to projects (Phase 5)
  339. try:
  340. await conn.execute(text("ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'"))
  341. except OperationalError:
  342. pass # Already applied
  343. # Migration: Add budget column to projects (Phase 6)
  344. try:
  345. await conn.execute(text("ALTER TABLE projects ADD COLUMN budget REAL"))
  346. except OperationalError:
  347. pass # Already applied
  348. # Migration: Add is_template column to projects (Phase 8)
  349. try:
  350. await conn.execute(text("ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0"))
  351. except OperationalError:
  352. pass # Already applied
  353. # Migration: Add template_source_id column to projects (Phase 8)
  354. try:
  355. await conn.execute(text("ALTER TABLE projects ADD COLUMN template_source_id INTEGER"))
  356. except OperationalError:
  357. pass # Already applied
  358. # Migration: Add parent_id column to projects (Phase 10)
  359. try:
  360. await conn.execute(
  361. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  362. )
  363. except OperationalError:
  364. pass # Already applied
  365. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  366. try:
  367. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired"))
  368. except OperationalError:
  369. pass # Already applied
  370. # Migration: Add unit_price column to project_bom_items
  371. try:
  372. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN unit_price REAL"))
  373. except OperationalError:
  374. pass # Already applied
  375. # Migration: Add sourcing_url column to project_bom_items
  376. try:
  377. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)"))
  378. except OperationalError:
  379. pass # Already applied
  380. # Migration: Rename notes to remarks in project_bom_items
  381. try:
  382. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks"))
  383. except OperationalError:
  384. pass # Already applied
  385. # Migration: Add show_in_switchbar column to smart_plugs
  386. try:
  387. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0"))
  388. except OperationalError:
  389. pass # Already applied
  390. # Migration: Add runtime tracking columns to printers
  391. try:
  392. await conn.execute(text("ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0"))
  393. except OperationalError:
  394. pass # Already applied
  395. try:
  396. await conn.execute(text("ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME"))
  397. except OperationalError:
  398. pass # Already applied
  399. # Migration: Add quantity column to print_archives for tracking item count
  400. try:
  401. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1"))
  402. except OperationalError:
  403. pass # Already applied
  404. # Migration: Add manual_start column to print_queue for staged prints
  405. try:
  406. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0"))
  407. except OperationalError:
  408. pass # Already applied
  409. # Migration: Add wiki_url column to maintenance_types for documentation links
  410. try:
  411. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)"))
  412. except OperationalError:
  413. pass # Already applied
  414. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  415. try:
  416. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT"))
  417. except OperationalError:
  418. pass # Already applied
  419. # Migration: Add target_parts_count column to projects for tracking total parts needed
  420. try:
  421. await conn.execute(text("ALTER TABLE projects ADD COLUMN target_parts_count INTEGER"))
  422. except OperationalError:
  423. pass # Already applied
  424. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  425. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  426. try:
  427. # Check if printer_id is already nullable by trying to insert NULL
  428. # This is a safe check that won't affect existing data
  429. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  430. row = result.fetchone()
  431. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  432. # Need to migrate - printer_id is currently NOT NULL
  433. await conn.execute(
  434. text("""
  435. CREATE TABLE print_queue_new (
  436. id INTEGER PRIMARY KEY,
  437. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  438. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  439. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  440. position INTEGER DEFAULT 0,
  441. scheduled_time DATETIME,
  442. manual_start BOOLEAN DEFAULT 0,
  443. require_previous_success BOOLEAN DEFAULT 0,
  444. auto_off_after BOOLEAN DEFAULT 0,
  445. ams_mapping TEXT,
  446. status VARCHAR(20) DEFAULT 'pending',
  447. started_at DATETIME,
  448. completed_at DATETIME,
  449. error_message TEXT,
  450. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  451. )
  452. """)
  453. )
  454. await conn.execute(
  455. text("""
  456. INSERT INTO print_queue_new
  457. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  458. manual_start, require_previous_success, auto_off_after, ams_mapping,
  459. status, started_at, completed_at, error_message, created_at
  460. FROM print_queue
  461. """)
  462. )
  463. await conn.execute(text("DROP TABLE print_queue"))
  464. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  465. except OperationalError:
  466. pass # Already applied
  467. # Migration: Add plug_type column to smart_plugs for HA integration
  468. try:
  469. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'"))
  470. except OperationalError:
  471. pass # Already applied
  472. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  473. try:
  474. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)"))
  475. except OperationalError:
  476. pass # Already applied
  477. # Migration: Add project_id column to library_folders for linking folders to projects
  478. try:
  479. await conn.execute(
  480. text("ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  481. )
  482. except OperationalError:
  483. pass # Already applied
  484. # Migration: Add archive_id column to library_folders for linking folders to archives
  485. try:
  486. await conn.execute(
  487. text(
  488. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  489. )
  490. )
  491. except OperationalError:
  492. pass # Already applied
  493. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  494. try:
  495. # Check if ip_address is currently NOT NULL
  496. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  497. row = result.fetchone()
  498. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  499. # Need to migrate - ip_address is currently NOT NULL
  500. await conn.execute(
  501. text("""
  502. CREATE TABLE smart_plugs_new (
  503. id INTEGER PRIMARY KEY,
  504. name VARCHAR(100) NOT NULL,
  505. ip_address VARCHAR(45),
  506. plug_type VARCHAR(20) DEFAULT 'tasmota',
  507. ha_entity_id VARCHAR(100),
  508. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  509. enabled BOOLEAN NOT NULL DEFAULT 1,
  510. auto_on BOOLEAN NOT NULL DEFAULT 1,
  511. auto_off BOOLEAN NOT NULL DEFAULT 1,
  512. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  513. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  514. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  515. username VARCHAR(50),
  516. password VARCHAR(100),
  517. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  518. power_alert_high FLOAT,
  519. power_alert_low FLOAT,
  520. power_alert_last_triggered DATETIME,
  521. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  522. schedule_on_time VARCHAR(5),
  523. schedule_off_time VARCHAR(5),
  524. show_in_switchbar BOOLEAN DEFAULT 0,
  525. last_state VARCHAR(10),
  526. last_checked DATETIME,
  527. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  528. auto_off_pending BOOLEAN DEFAULT 0,
  529. auto_off_pending_since DATETIME,
  530. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  531. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  532. )
  533. """)
  534. )
  535. await conn.execute(
  536. text("""
  537. INSERT INTO smart_plugs_new
  538. SELECT id, name, ip_address,
  539. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  540. enabled, auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  541. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  542. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  543. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  544. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  545. FROM smart_plugs
  546. """)
  547. )
  548. await conn.execute(text("DROP TABLE smart_plugs"))
  549. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  550. except OperationalError:
  551. pass # Already applied
  552. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  553. try:
  554. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN plate_id INTEGER"))
  555. except OperationalError:
  556. pass # Already applied
  557. # Migration: Add print options columns to print_queue
  558. try:
  559. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1"))
  560. except OperationalError:
  561. pass # Already applied
  562. try:
  563. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0"))
  564. except OperationalError:
  565. pass # Already applied
  566. try:
  567. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1"))
  568. except OperationalError:
  569. pass # Already applied
  570. try:
  571. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0"))
  572. except OperationalError:
  573. pass # Already applied
  574. try:
  575. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0"))
  576. except OperationalError:
  577. pass # Already applied
  578. try:
  579. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1"))
  580. except OperationalError:
  581. pass # Already applied
  582. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  583. # This allows queue items to reference library files directly (archive created at print start)
  584. try:
  585. await conn.execute(
  586. text(
  587. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  588. )
  589. )
  590. except OperationalError:
  591. pass # Already applied
  592. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  593. try:
  594. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  595. row = result.fetchone()
  596. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  597. # Need to migrate - archive_id is currently NOT NULL
  598. await conn.execute(
  599. text("""
  600. CREATE TABLE print_queue_new2 (
  601. id INTEGER PRIMARY KEY,
  602. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  603. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  604. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  605. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  606. position INTEGER DEFAULT 0,
  607. scheduled_time DATETIME,
  608. manual_start BOOLEAN DEFAULT 0,
  609. require_previous_success BOOLEAN DEFAULT 0,
  610. auto_off_after BOOLEAN DEFAULT 0,
  611. ams_mapping TEXT,
  612. plate_id INTEGER,
  613. bed_levelling BOOLEAN DEFAULT 1,
  614. flow_cali BOOLEAN DEFAULT 0,
  615. vibration_cali BOOLEAN DEFAULT 1,
  616. layer_inspect BOOLEAN DEFAULT 0,
  617. timelapse BOOLEAN DEFAULT 0,
  618. use_ams BOOLEAN DEFAULT 1,
  619. status VARCHAR(20) DEFAULT 'pending',
  620. started_at DATETIME,
  621. completed_at DATETIME,
  622. error_message TEXT,
  623. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  624. )
  625. """)
  626. )
  627. await conn.execute(
  628. text("""
  629. INSERT INTO print_queue_new2
  630. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  631. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  632. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  633. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  634. status, started_at, completed_at, error_message, created_at
  635. FROM print_queue
  636. """)
  637. )
  638. await conn.execute(text("DROP TABLE print_queue"))
  639. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  640. except OperationalError:
  641. pass # Already applied
  642. # Migration: Add HA energy sensor entity columns to smart_plugs
  643. try:
  644. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)"))
  645. except OperationalError:
  646. pass # Already applied
  647. try:
  648. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)"))
  649. except OperationalError:
  650. pass # Already applied
  651. try:
  652. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)"))
  653. except OperationalError:
  654. pass # Already applied
  655. # Migration: Create users table for authentication
  656. try:
  657. await conn.execute(
  658. text("""
  659. CREATE TABLE IF NOT EXISTS users (
  660. id INTEGER PRIMARY KEY,
  661. username VARCHAR(100) NOT NULL UNIQUE,
  662. password_hash VARCHAR(255) NOT NULL,
  663. role VARCHAR(20) NOT NULL DEFAULT 'user',
  664. is_active BOOLEAN NOT NULL DEFAULT 1,
  665. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  666. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  667. )
  668. """)
  669. )
  670. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  671. except OperationalError:
  672. pass # Already applied
  673. # Migration: Add external camera columns to printers
  674. try:
  675. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)"))
  676. except OperationalError:
  677. pass # Already applied
  678. try:
  679. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)"))
  680. except OperationalError:
  681. pass # Already applied
  682. try:
  683. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0"))
  684. except OperationalError:
  685. pass # Already applied
  686. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  687. try:
  688. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)"))
  689. except OperationalError:
  690. pass # Already applied
  691. # Migration: Add sliced_for_model column to print_archives for model-based queue assignment
  692. try:
  693. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)"))
  694. except OperationalError:
  695. pass # Already applied
  696. # Migration: Add is_external column to library_files for external cloud files
  697. try:
  698. await conn.execute(text("ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  699. except OperationalError:
  700. pass # Already applied
  701. # Migration: Add project_id column to library_files
  702. try:
  703. await conn.execute(
  704. text("ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  705. )
  706. except OperationalError:
  707. pass # Already applied
  708. # Migration: Add is_external column to library_folders for external cloud folders
  709. try:
  710. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  711. except OperationalError:
  712. pass # Already applied
  713. # Migration: Add external folder settings columns to library_folders
  714. try:
  715. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0"))
  716. except OperationalError:
  717. pass # Already applied
  718. try:
  719. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0"))
  720. except OperationalError:
  721. pass # Already applied
  722. try:
  723. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)"))
  724. except OperationalError:
  725. pass # Already applied
  726. # Migration: Add plate_detection_enabled column to printers
  727. try:
  728. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0"))
  729. except OperationalError:
  730. pass # Already applied
  731. # Migration: Add plate detection ROI columns to printers
  732. try:
  733. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL"))
  734. except OperationalError:
  735. pass # Already applied
  736. try:
  737. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL"))
  738. except OperationalError:
  739. pass # Already applied
  740. try:
  741. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL"))
  742. except OperationalError:
  743. pass # Already applied
  744. try:
  745. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL"))
  746. except OperationalError:
  747. pass # Already applied
  748. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  749. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  750. # SQLite requires table recreation to drop constraints
  751. try:
  752. # Check if we need to migrate (if UNIQUE constraint exists)
  753. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  754. row = result.fetchone()
  755. if row and "printer_id INTEGER UNIQUE" in (row[0] or ""):
  756. # Create new table without UNIQUE constraint on printer_id
  757. await conn.execute(
  758. text("""
  759. CREATE TABLE smart_plugs_temp (
  760. id INTEGER PRIMARY KEY,
  761. name VARCHAR(100) NOT NULL,
  762. ip_address VARCHAR(45),
  763. plug_type VARCHAR(20) DEFAULT 'tasmota',
  764. ha_entity_id VARCHAR(100),
  765. ha_power_entity VARCHAR(100),
  766. ha_energy_today_entity VARCHAR(100),
  767. ha_energy_total_entity VARCHAR(100),
  768. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  769. enabled BOOLEAN NOT NULL DEFAULT 1,
  770. auto_on BOOLEAN NOT NULL DEFAULT 1,
  771. auto_off BOOLEAN NOT NULL DEFAULT 1,
  772. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  773. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  774. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  775. username VARCHAR(50),
  776. password VARCHAR(100),
  777. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  778. power_alert_high FLOAT,
  779. power_alert_low FLOAT,
  780. power_alert_last_triggered DATETIME,
  781. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  782. schedule_on_time VARCHAR(5),
  783. schedule_off_time VARCHAR(5),
  784. show_in_switchbar BOOLEAN DEFAULT 0,
  785. last_state VARCHAR(10),
  786. last_checked DATETIME,
  787. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  788. auto_off_pending BOOLEAN DEFAULT 0,
  789. auto_off_pending_since DATETIME,
  790. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  791. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  792. )
  793. """)
  794. )
  795. # Copy data
  796. await conn.execute(
  797. text("""
  798. INSERT INTO smart_plugs_temp
  799. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  800. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  801. auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  802. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  803. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  804. show_in_switchbar, last_state, last_checked, auto_off_executed,
  805. auto_off_pending, auto_off_pending_since, created_at, updated_at
  806. FROM smart_plugs
  807. """)
  808. )
  809. # Drop old table and rename new one
  810. await conn.execute(text("DROP TABLE smart_plugs"))
  811. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  812. except OperationalError:
  813. pass # Already applied
  814. # Migration: Add show_on_printer_card column to smart_plugs
  815. try:
  816. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1"))
  817. except OperationalError:
  818. pass # Already applied
  819. # Migration: Add MQTT smart plug fields (legacy)
  820. try:
  821. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)"))
  822. except OperationalError:
  823. pass # Already applied
  824. try:
  825. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)"))
  826. except OperationalError:
  827. pass # Already applied
  828. try:
  829. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)"))
  830. except OperationalError:
  831. pass # Already applied
  832. try:
  833. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)"))
  834. except OperationalError:
  835. pass # Already applied
  836. try:
  837. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0"))
  838. except OperationalError:
  839. pass # Already applied
  840. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  841. try:
  842. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)"))
  843. except OperationalError:
  844. pass # Already applied
  845. try:
  846. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0"))
  847. except OperationalError:
  848. pass # Already applied
  849. try:
  850. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)"))
  851. except OperationalError:
  852. pass # Already applied
  853. try:
  854. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0"))
  855. except OperationalError:
  856. pass # Already applied
  857. try:
  858. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)"))
  859. except OperationalError:
  860. pass # Already applied
  861. try:
  862. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)"))
  863. except OperationalError:
  864. pass # Already applied
  865. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  866. try:
  867. await conn.execute(
  868. text("""
  869. UPDATE smart_plugs
  870. SET mqtt_power_topic = mqtt_topic,
  871. mqtt_power_multiplier = mqtt_multiplier
  872. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  873. """)
  874. )
  875. except OperationalError:
  876. pass # Already applied
  877. # Migration: Create groups table for permission-based access control
  878. try:
  879. await conn.execute(
  880. text("""
  881. CREATE TABLE IF NOT EXISTS groups (
  882. id INTEGER PRIMARY KEY,
  883. name VARCHAR(100) NOT NULL UNIQUE,
  884. description VARCHAR(500),
  885. permissions JSON,
  886. is_system BOOLEAN NOT NULL DEFAULT 0,
  887. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  888. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  889. )
  890. """)
  891. )
  892. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  893. except OperationalError:
  894. pass # Already applied
  895. # Migration: Create user_groups association table
  896. try:
  897. await conn.execute(
  898. text("""
  899. CREATE TABLE IF NOT EXISTS user_groups (
  900. user_id INTEGER NOT NULL,
  901. group_id INTEGER NOT NULL,
  902. PRIMARY KEY (user_id, group_id),
  903. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  904. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  905. )
  906. """)
  907. )
  908. except OperationalError:
  909. pass # Already applied
  910. # Migration: Add model-based queue assignment columns to print_queue
  911. try:
  912. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)"))
  913. except OperationalError:
  914. pass # Already applied
  915. try:
  916. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT"))
  917. except OperationalError:
  918. pass # Already applied
  919. try:
  920. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT"))
  921. except OperationalError:
  922. pass # Already applied
  923. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  924. try:
  925. await conn.execute(text("ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1"))
  926. except OperationalError:
  927. pass # Already applied
  928. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  929. try:
  930. await conn.execute(text("ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0"))
  931. except OperationalError:
  932. pass # Already applied
  933. # Migration: Add queue notification event columns to notification_providers
  934. try:
  935. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0"))
  936. except OperationalError:
  937. pass # Already applied
  938. try:
  939. await conn.execute(
  940. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  941. )
  942. except OperationalError:
  943. pass # Already applied
  944. try:
  945. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0"))
  946. except OperationalError:
  947. pass # Already applied
  948. try:
  949. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1"))
  950. except OperationalError:
  951. pass # Already applied
  952. try:
  953. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1"))
  954. except OperationalError:
  955. pass # Already applied
  956. try:
  957. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1"))
  958. except OperationalError:
  959. pass # Already applied
  960. try:
  961. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0"))
  962. except OperationalError:
  963. pass # Already applied
  964. # Migration: Add created_by_id column to print_archives for user tracking (Issue #206)
  965. try:
  966. await conn.execute(
  967. text("ALTER TABLE print_archives ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  968. )
  969. except OperationalError:
  970. pass # Already applied
  971. # Migration: Add created_by_id column to print_queue for user tracking (Issue #206)
  972. try:
  973. await conn.execute(
  974. text("ALTER TABLE print_queue ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  975. )
  976. except OperationalError:
  977. pass # Already applied
  978. # Migration: Add created_by_id column to library_files for user tracking (Issue #206)
  979. try:
  980. await conn.execute(
  981. text("ALTER TABLE library_files ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  982. )
  983. except OperationalError:
  984. pass # Already applied
  985. # Migration: Add target_location column to print_queue for location-based filtering (Issue #220)
  986. try:
  987. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_location VARCHAR(100)"))
  988. except OperationalError:
  989. pass # Already applied
  990. # Migration: Convert absolute paths to relative paths in library_files table
  991. # This ensures backup/restore portability across different installations
  992. try:
  993. base_dir_str = str(settings.base_dir)
  994. # Ensure we have a trailing slash for clean replacement
  995. if not base_dir_str.endswith("/"):
  996. base_dir_str += "/"
  997. # Update file_path - remove base_dir prefix from absolute paths
  998. await conn.execute(
  999. text("""
  1000. UPDATE library_files
  1001. SET file_path = SUBSTR(file_path, LENGTH(:base_dir) + 1)
  1002. WHERE file_path LIKE :pattern
  1003. """),
  1004. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1005. )
  1006. # Update thumbnail_path - remove base_dir prefix from absolute paths
  1007. await conn.execute(
  1008. text("""
  1009. UPDATE library_files
  1010. SET thumbnail_path = SUBSTR(thumbnail_path, LENGTH(:base_dir) + 1)
  1011. WHERE thumbnail_path LIKE :pattern
  1012. """),
  1013. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1014. )
  1015. except OperationalError:
  1016. pass # Already applied
  1017. # Create active_print_spoolman table for Spoolman per-filament tracking
  1018. try:
  1019. await conn.execute(
  1020. text("""
  1021. CREATE TABLE IF NOT EXISTS active_print_spoolman (
  1022. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1023. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  1024. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  1025. filament_usage TEXT NOT NULL,
  1026. ams_trays TEXT NOT NULL,
  1027. slot_to_tray TEXT,
  1028. layer_usage TEXT,
  1029. filament_properties TEXT,
  1030. UNIQUE(printer_id, archive_id)
  1031. )
  1032. """)
  1033. )
  1034. except OperationalError:
  1035. pass # Already applied
  1036. # Migration: Add preset_source column to slot_preset_mappings for local preset support
  1037. try:
  1038. await conn.execute(
  1039. text("ALTER TABLE slot_preset_mappings ADD COLUMN preset_source VARCHAR(20) DEFAULT 'cloud'")
  1040. )
  1041. except OperationalError:
  1042. pass # Already applied
  1043. # Migration: Add email column to users for Advanced Auth (PR #322)
  1044. try:
  1045. await conn.execute(text("ALTER TABLE users ADD COLUMN email VARCHAR(255)"))
  1046. except OperationalError:
  1047. pass # Already applied
  1048. # Migration: Add inventory spool tracking columns
  1049. try:
  1050. await conn.execute(text("ALTER TABLE spool ADD COLUMN added_full BOOLEAN"))
  1051. except OperationalError:
  1052. pass # Already applied
  1053. try:
  1054. await conn.execute(text("ALTER TABLE spool ADD COLUMN last_used DATETIME"))
  1055. except OperationalError:
  1056. pass # Already applied
  1057. try:
  1058. await conn.execute(text("ALTER TABLE spool ADD COLUMN encode_time DATETIME"))
  1059. except OperationalError:
  1060. pass # Already applied
  1061. # Migration: Add RFID tag matching columns to spool
  1062. try:
  1063. await conn.execute(text("ALTER TABLE spool ADD COLUMN tag_uid VARCHAR(16)"))
  1064. except OperationalError:
  1065. pass # Already applied
  1066. try:
  1067. await conn.execute(text("ALTER TABLE spool ADD COLUMN tray_uuid VARCHAR(32)"))
  1068. except OperationalError:
  1069. pass # Already applied
  1070. try:
  1071. await conn.execute(text("ALTER TABLE spool ADD COLUMN data_origin VARCHAR(20)"))
  1072. except OperationalError:
  1073. pass # Already applied
  1074. try:
  1075. await conn.execute(text("ALTER TABLE spool ADD COLUMN tag_type VARCHAR(20)"))
  1076. except OperationalError:
  1077. pass # Already applied
  1078. # Migration: Add core_weight_catalog_id to track which catalog entry was used for empty spool weight
  1079. try:
  1080. await conn.execute(text("ALTER TABLE spool ADD COLUMN core_weight_catalog_id INTEGER"))
  1081. except OperationalError:
  1082. pass # Already applied
  1083. # Migration: Create spool_usage_history table for filament consumption tracking
  1084. try:
  1085. await conn.execute(
  1086. text("""
  1087. CREATE TABLE IF NOT EXISTS spool_usage_history (
  1088. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1089. spool_id INTEGER NOT NULL REFERENCES spool(id) ON DELETE CASCADE,
  1090. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  1091. print_name VARCHAR(500),
  1092. weight_used REAL NOT NULL DEFAULT 0,
  1093. percent_used INTEGER NOT NULL DEFAULT 0,
  1094. status VARCHAR(20) NOT NULL DEFAULT 'completed',
  1095. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1096. )
  1097. """)
  1098. )
  1099. except OperationalError:
  1100. pass # Already applied
  1101. # Migration: Add open_in_new_tab column to external_links
  1102. try:
  1103. await conn.execute(text("ALTER TABLE external_links ADD COLUMN open_in_new_tab BOOLEAN DEFAULT 0"))
  1104. except OperationalError:
  1105. pass # Already applied
  1106. # Migration: Add bed cooled notification column to notification_providers
  1107. try:
  1108. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_bed_cooled BOOLEAN DEFAULT 0"))
  1109. except OperationalError:
  1110. pass # Already applied
  1111. # Migration: Add weight_locked flag to spool table (skip AMS auto-sync for manually-entered weights)
  1112. try:
  1113. await conn.execute(text("ALTER TABLE spool ADD COLUMN weight_locked BOOLEAN DEFAULT 0"))
  1114. except OperationalError:
  1115. pass # Already applied
  1116. # Migration: Add SpoolBuddy scale weight tracking columns to spool table
  1117. try:
  1118. await conn.execute(text("ALTER TABLE spool ADD COLUMN last_scale_weight INTEGER"))
  1119. except OperationalError:
  1120. pass # Already applied
  1121. try:
  1122. await conn.execute(text("ALTER TABLE spool ADD COLUMN last_weighed_at DATETIME"))
  1123. except OperationalError:
  1124. pass # Already applied
  1125. # Migration: Add cost tracking fields to spool table
  1126. try:
  1127. await conn.execute(text("ALTER TABLE spool ADD COLUMN cost_per_kg REAL"))
  1128. except OperationalError:
  1129. pass # Already applied
  1130. # Migration: Add cost field to spool_usage_history table
  1131. try:
  1132. await conn.execute(text("ALTER TABLE spool_usage_history ADD COLUMN cost REAL"))
  1133. except OperationalError:
  1134. pass # Already applied
  1135. # Migration: Add archive_id field to spool_usage_history table
  1136. try:
  1137. await conn.execute(
  1138. text("ALTER TABLE spool_usage_history ADD COLUMN archive_id INTEGER REFERENCES print_archives(id)")
  1139. )
  1140. except OperationalError:
  1141. pass # Already applied
  1142. # Migration: Migrate single virtual printer key-value settings to virtual_printers table
  1143. try:
  1144. # Check if virtual_printers table has any rows
  1145. result = await conn.execute(text("SELECT COUNT(*) FROM virtual_printers"))
  1146. count = result.scalar() or 0
  1147. if count == 0:
  1148. # Check if old key-value settings exist
  1149. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_enabled'"))
  1150. row = result.fetchone()
  1151. if row:
  1152. # Old settings exist — migrate to first virtual printer row
  1153. old_enabled = row[0] == "true" if row[0] else False
  1154. result = await conn.execute(
  1155. text("SELECT value FROM settings WHERE key = 'virtual_printer_access_code'")
  1156. )
  1157. row = result.fetchone()
  1158. old_access_code = row[0] if row else None
  1159. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_mode'"))
  1160. row = result.fetchone()
  1161. old_mode = row[0] if row else "immediate"
  1162. if old_mode == "queue":
  1163. old_mode = "review"
  1164. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_model'"))
  1165. row = result.fetchone()
  1166. old_model = row[0] if row else "3DPrinter-X1-Carbon"
  1167. result = await conn.execute(
  1168. text("SELECT value FROM settings WHERE key = 'virtual_printer_target_printer_id'")
  1169. )
  1170. row = result.fetchone()
  1171. old_target_id = int(row[0]) if row and row[0] else None
  1172. result = await conn.execute(
  1173. text("SELECT value FROM settings WHERE key = 'virtual_printer_remote_interface_ip'")
  1174. )
  1175. row = result.fetchone()
  1176. old_remote_iface = row[0] if row else None
  1177. await conn.execute(
  1178. text("""
  1179. INSERT INTO virtual_printers
  1180. (name, enabled, mode, model, access_code, target_printer_id,
  1181. bind_ip, remote_interface_ip, serial_suffix, position)
  1182. VALUES
  1183. (:name, :enabled, :mode, :model, :access_code, :target_id,
  1184. NULL, :remote_iface, '391800001', 0)
  1185. """),
  1186. {
  1187. "name": "Bambuddy",
  1188. "enabled": old_enabled,
  1189. "mode": old_mode or "immediate",
  1190. "model": old_model,
  1191. "access_code": old_access_code,
  1192. "target_id": old_target_id,
  1193. "remote_iface": old_remote_iface,
  1194. },
  1195. )
  1196. except OperationalError:
  1197. pass # Table may not exist yet on first run
  1198. # Migration: Add filament_overrides column to print_queue for filament override in model-based assignment
  1199. try:
  1200. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN filament_overrides TEXT"))
  1201. except OperationalError:
  1202. pass # Already applied
  1203. # Migration: Add NFC reader and display control columns to spoolbuddy_devices
  1204. try:
  1205. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_reader_type VARCHAR(20)"))
  1206. except OperationalError:
  1207. pass # Already applied
  1208. try:
  1209. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_connection VARCHAR(20)"))
  1210. except OperationalError:
  1211. pass # Already applied
  1212. try:
  1213. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN display_brightness INTEGER DEFAULT 100"))
  1214. except OperationalError:
  1215. pass # Already applied
  1216. try:
  1217. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN display_blank_timeout INTEGER DEFAULT 0"))
  1218. except OperationalError:
  1219. pass # Already applied
  1220. try:
  1221. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN has_backlight BOOLEAN DEFAULT 0"))
  1222. except OperationalError:
  1223. pass # Already applied
  1224. try:
  1225. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN last_calibrated_at DATETIME"))
  1226. except OperationalError:
  1227. pass # Already applied
  1228. # Migration: Add NFC tag write payload column to spoolbuddy_devices
  1229. try:
  1230. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN pending_write_payload TEXT"))
  1231. except OperationalError:
  1232. pass # Already applied
  1233. # Cleanup: Remove obsolete settings keys that are no longer used
  1234. obsolete_keys = ["slicer_binary_path"]
  1235. for key in obsolete_keys:
  1236. await conn.execute(text("DELETE FROM settings WHERE key = :key"), {"key": key})
  1237. async def seed_notification_templates():
  1238. """Seed default notification templates if they don't exist."""
  1239. from sqlalchemy import select
  1240. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  1241. async with async_session() as session:
  1242. # Get existing template event types
  1243. result = await session.execute(select(NotificationTemplate.event_type))
  1244. existing_types = {row[0] for row in result.fetchall()}
  1245. if not existing_types:
  1246. # No templates exist - insert all defaults
  1247. for template_data in DEFAULT_TEMPLATES:
  1248. template = NotificationTemplate(
  1249. event_type=template_data["event_type"],
  1250. name=template_data["name"],
  1251. title_template=template_data["title_template"],
  1252. body_template=template_data["body_template"],
  1253. is_default=True,
  1254. )
  1255. session.add(template)
  1256. else:
  1257. # Templates exist - only add missing ones
  1258. for template_data in DEFAULT_TEMPLATES:
  1259. if template_data["event_type"] not in existing_types:
  1260. template = NotificationTemplate(
  1261. event_type=template_data["event_type"],
  1262. name=template_data["name"],
  1263. title_template=template_data["title_template"],
  1264. body_template=template_data["body_template"],
  1265. is_default=True,
  1266. )
  1267. session.add(template)
  1268. await session.commit()
  1269. async def seed_default_groups():
  1270. """Seed default groups and migrate existing users to appropriate groups.
  1271. Creates the default system groups (Administrators, Operators, Viewers) if they
  1272. don't exist, then migrates existing users:
  1273. - Users with role='admin' -> Administrators group
  1274. - Users with role='user' -> Operators group
  1275. Also migrates old permissions to new ownership-based permissions (Issue #205).
  1276. """
  1277. import logging
  1278. from sqlalchemy import select
  1279. from backend.app.core.permissions import DEFAULT_GROUPS
  1280. from backend.app.models.group import Group
  1281. from backend.app.models.user import User
  1282. logger = logging.getLogger(__name__)
  1283. # Map old permissions to new ones for migration
  1284. # Administrators get *_all permissions, Operators get *_own permissions
  1285. PERMISSION_MIGRATION_ALL = {
  1286. "queue:update": "queue:update_all",
  1287. "queue:delete": "queue:delete_all",
  1288. "archives:update": "archives:update_all",
  1289. "archives:delete": "archives:delete_all",
  1290. "archives:reprint": "archives:reprint_all",
  1291. "library:update": "library:update_all",
  1292. "library:delete": "library:delete_all",
  1293. }
  1294. PERMISSION_MIGRATION_OWN = {
  1295. "queue:update": "queue:update_own",
  1296. "queue:delete": "queue:delete_own",
  1297. "archives:update": "archives:update_own",
  1298. "archives:delete": "archives:delete_own",
  1299. "archives:reprint": "archives:reprint_own",
  1300. "library:update": "library:update_own",
  1301. "library:delete": "library:delete_own",
  1302. }
  1303. async with async_session() as session:
  1304. # Get existing groups
  1305. result = await session.execute(select(Group))
  1306. existing_groups = {group.name: group for group in result.scalars().all()}
  1307. # Create default groups if they don't exist
  1308. groups_created = []
  1309. for group_name, group_config in DEFAULT_GROUPS.items():
  1310. if group_name not in existing_groups:
  1311. group = Group(
  1312. name=group_name,
  1313. description=group_config["description"],
  1314. permissions=group_config["permissions"],
  1315. is_system=group_config["is_system"],
  1316. )
  1317. session.add(group)
  1318. groups_created.append(group_name)
  1319. logger.info("Created default group: %s", group_name)
  1320. else:
  1321. # Migrate existing group's permissions from old to new format
  1322. group = existing_groups[group_name]
  1323. if group.permissions:
  1324. updated = False
  1325. new_permissions = list(group.permissions)
  1326. # Determine which migration map to use based on group
  1327. migration_map = (
  1328. PERMISSION_MIGRATION_ALL if group_name == "Administrators" else PERMISSION_MIGRATION_OWN
  1329. )
  1330. for old_perm, new_perm in migration_map.items():
  1331. if old_perm in new_permissions:
  1332. new_permissions.remove(old_perm)
  1333. if new_perm not in new_permissions:
  1334. new_permissions.append(new_perm)
  1335. updated = True
  1336. logger.info(
  1337. "Migrated permission '%s' to '%s' in group '%s'", old_perm, new_perm, group_name
  1338. )
  1339. # For Administrators, also ensure they get *_all permissions if they have any new *_own
  1340. if group_name == "Administrators":
  1341. for _own_perm, all_perm in [
  1342. ("queue:update_own", "queue:update_all"),
  1343. ("queue:delete_own", "queue:delete_all"),
  1344. ("archives:update_own", "archives:update_all"),
  1345. ("archives:delete_own", "archives:delete_all"),
  1346. ("archives:reprint_own", "archives:reprint_all"),
  1347. ("library:update_own", "library:update_all"),
  1348. ("library:delete_own", "library:delete_all"),
  1349. ]:
  1350. # Add *_all if not present
  1351. if all_perm not in new_permissions:
  1352. new_permissions.append(all_perm)
  1353. updated = True
  1354. if updated:
  1355. group.permissions = new_permissions
  1356. await session.commit()
  1357. # Migrate new permissions: grant printers:clear_plate to all groups with printers:control
  1358. result = await session.execute(select(Group))
  1359. all_groups = result.scalars().all()
  1360. for group in all_groups:
  1361. if (
  1362. group.permissions
  1363. and "printers:control" in group.permissions
  1364. and "printers:clear_plate" not in group.permissions
  1365. ):
  1366. group.permissions = [*group.permissions, "printers:clear_plate"]
  1367. logger.info("Added printers:clear_plate to group '%s' (has printers:control)", group.name)
  1368. await session.commit()
  1369. # Migrate existing users to groups if they're not already in any group
  1370. if groups_created:
  1371. # Refresh to get newly created groups
  1372. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  1373. admin_group = admin_result.scalar_one_or_none()
  1374. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  1375. operators_group = operators_result.scalar_one_or_none()
  1376. # Get all users
  1377. users_result = await session.execute(select(User))
  1378. users = users_result.scalars().all()
  1379. for user in users:
  1380. # Skip if user already has groups
  1381. if user.groups:
  1382. continue
  1383. if user.role == "admin" and admin_group:
  1384. user.groups.append(admin_group)
  1385. logger.info("Migrated admin user '%s' to Administrators group", user.username)
  1386. elif operators_group:
  1387. user.groups.append(operators_group)
  1388. logger.info("Migrated user '%s' to Operators group", user.username)
  1389. await session.commit()
  1390. async def seed_spool_catalog():
  1391. """Seed the spool catalog with default entries if empty."""
  1392. import logging
  1393. from sqlalchemy import func, select
  1394. from backend.app.core.catalog_defaults import DEFAULT_SPOOL_CATALOG
  1395. from backend.app.models.spool_catalog import SpoolCatalogEntry
  1396. logger = logging.getLogger(__name__)
  1397. async with async_session() as session:
  1398. result = await session.execute(select(func.count()).select_from(SpoolCatalogEntry))
  1399. count = result.scalar() or 0
  1400. if count > 0:
  1401. return # Already seeded
  1402. for name, weight in DEFAULT_SPOOL_CATALOG:
  1403. session.add(SpoolCatalogEntry(name=name, weight=weight, is_default=True))
  1404. await session.commit()
  1405. logger.info("Seeded %d default spool catalog entries", len(DEFAULT_SPOOL_CATALOG))
  1406. async def seed_color_catalog():
  1407. """Seed the color catalog with default entries if empty."""
  1408. import logging
  1409. from sqlalchemy import func, select
  1410. from backend.app.core.catalog_defaults import DEFAULT_COLOR_CATALOG
  1411. from backend.app.models.color_catalog import ColorCatalogEntry
  1412. logger = logging.getLogger(__name__)
  1413. async with async_session() as session:
  1414. result = await session.execute(select(func.count()).select_from(ColorCatalogEntry))
  1415. count = result.scalar() or 0
  1416. if count > 0:
  1417. return # Already seeded
  1418. for manufacturer, color_name, hex_color, material in DEFAULT_COLOR_CATALOG:
  1419. session.add(
  1420. ColorCatalogEntry(
  1421. manufacturer=manufacturer,
  1422. color_name=color_name,
  1423. hex_color=hex_color,
  1424. material=material,
  1425. is_default=True,
  1426. )
  1427. )
  1428. await session.commit()
  1429. logger.info("Seeded %d default color catalog entries", len(DEFAULT_COLOR_CATALOG))