database.py 64 KB

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