database.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. from sqlalchemy.exc import OperationalError
  2. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
  3. from sqlalchemy.orm import DeclarativeBase
  4. from backend.app.core.config import settings
  5. engine = create_async_engine(
  6. settings.database_url,
  7. echo=settings.debug,
  8. )
  9. async_session = async_sessionmaker(
  10. engine,
  11. class_=AsyncSession,
  12. expire_on_commit=False,
  13. )
  14. async def close_all_connections():
  15. """Close all database connections for backup/restore operations."""
  16. global engine
  17. await engine.dispose()
  18. async def reinitialize_database():
  19. """Reinitialize database connection after restore."""
  20. global engine, async_session
  21. engine = create_async_engine(
  22. settings.database_url,
  23. echo=settings.debug,
  24. )
  25. async_session = async_sessionmaker(
  26. engine,
  27. class_=AsyncSession,
  28. expire_on_commit=False,
  29. )
  30. class Base(DeclarativeBase):
  31. pass
  32. async def get_db() -> AsyncSession:
  33. async with async_session() as session:
  34. try:
  35. yield session
  36. await session.commit()
  37. except Exception:
  38. await session.rollback()
  39. raise
  40. finally:
  41. await session.close()
  42. async def init_db():
  43. # Import models to register them with SQLAlchemy
  44. from backend.app.models import ( # noqa: F401
  45. active_print_spoolman,
  46. ams_history,
  47. api_key,
  48. archive,
  49. external_link,
  50. filament,
  51. github_backup,
  52. group,
  53. kprofile_note,
  54. library,
  55. local_preset,
  56. maintenance,
  57. notification,
  58. notification_template,
  59. orca_base_cache,
  60. pending_upload,
  61. print_queue,
  62. printer,
  63. project,
  64. project_bom,
  65. settings,
  66. slot_preset,
  67. smart_plug,
  68. user,
  69. )
  70. async with engine.begin() as conn:
  71. await conn.run_sync(Base.metadata.create_all)
  72. # Run migrations for new columns (SQLite doesn't auto-add columns)
  73. await run_migrations(conn)
  74. # Seed default notification templates
  75. await seed_notification_templates()
  76. # Seed default groups and migrate existing users
  77. await seed_default_groups()
  78. async def run_migrations(conn):
  79. """Add new columns to existing tables if they don't exist."""
  80. from sqlalchemy import text
  81. # Migration: Add is_favorite column to print_archives
  82. try:
  83. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0"))
  84. except OperationalError:
  85. # Column already exists
  86. pass
  87. # Migration: Add content_hash column to print_archives for duplicate detection
  88. try:
  89. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)"))
  90. except OperationalError:
  91. # Column already exists
  92. pass
  93. # Migration: Add auto_off_executed column to smart_plugs
  94. try:
  95. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0"))
  96. except OperationalError:
  97. # Column already exists
  98. pass
  99. # Migration: Add on_print_stopped column to notification_providers
  100. try:
  101. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1"))
  102. except OperationalError:
  103. # Column already exists
  104. pass
  105. # Migration: Add source_3mf_path column to print_archives
  106. try:
  107. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)"))
  108. except OperationalError:
  109. # Column already exists
  110. pass
  111. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  112. try:
  113. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)"))
  114. except OperationalError:
  115. # Column already exists
  116. pass
  117. # Migration: Add on_maintenance_due column to notification_providers
  118. try:
  119. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0"))
  120. except OperationalError:
  121. # Column already exists
  122. pass
  123. # Migration: Add location column to printers for grouping
  124. try:
  125. await conn.execute(text("ALTER TABLE printers ADD COLUMN location VARCHAR(100)"))
  126. except OperationalError:
  127. # Column already exists
  128. pass
  129. # Migration: Add interval_type column to maintenance_types
  130. try:
  131. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'"))
  132. except OperationalError:
  133. # Column already exists
  134. pass
  135. # Migration: Add custom_interval_type column to printer_maintenance
  136. try:
  137. await conn.execute(text("ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)"))
  138. except OperationalError:
  139. # Column already exists
  140. pass
  141. # Migration: Add power alert columns to smart_plugs
  142. try:
  143. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0"))
  144. except OperationalError:
  145. pass # Already applied
  146. try:
  147. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL"))
  148. except OperationalError:
  149. pass # Already applied
  150. try:
  151. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL"))
  152. except OperationalError:
  153. pass # Already applied
  154. try:
  155. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME"))
  156. except OperationalError:
  157. pass # Already applied
  158. # Migration: Add schedule columns to smart_plugs
  159. try:
  160. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0"))
  161. except OperationalError:
  162. pass # Already applied
  163. try:
  164. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)"))
  165. except OperationalError:
  166. pass # Already applied
  167. try:
  168. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)"))
  169. except OperationalError:
  170. pass # Already applied
  171. # Migration: Add daily digest columns to notification_providers
  172. try:
  173. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0"))
  174. except OperationalError:
  175. pass # Already applied
  176. try:
  177. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)"))
  178. except OperationalError:
  179. pass # Already applied
  180. # Migration: Add project_id column to print_archives
  181. try:
  182. await conn.execute(
  183. text("ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  184. )
  185. except OperationalError:
  186. pass # Already applied
  187. # Migration: Add project_id column to print_queue
  188. try:
  189. await conn.execute(
  190. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  191. )
  192. except OperationalError:
  193. pass # Already applied
  194. # Migration: Create FTS5 virtual table for archive full-text search
  195. try:
  196. await conn.execute(
  197. text("""
  198. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  199. print_name,
  200. filename,
  201. tags,
  202. notes,
  203. designer,
  204. filament_type,
  205. content='print_archives',
  206. content_rowid='id'
  207. )
  208. """)
  209. )
  210. except OperationalError:
  211. pass # Already applied
  212. # Migration: Create triggers to keep FTS index in sync
  213. try:
  214. await conn.execute(
  215. text("""
  216. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  217. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  218. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  219. END
  220. """)
  221. )
  222. except OperationalError:
  223. pass # Already applied
  224. try:
  225. await conn.execute(
  226. text("""
  227. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  228. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  229. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  230. END
  231. """)
  232. )
  233. except OperationalError:
  234. pass # Already applied
  235. try:
  236. await conn.execute(
  237. text("""
  238. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  239. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  240. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  241. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  242. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  243. END
  244. """)
  245. )
  246. except OperationalError:
  247. pass # Already applied
  248. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  249. try:
  250. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0"))
  251. except OperationalError:
  252. pass # Already applied
  253. try:
  254. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME"))
  255. except OperationalError:
  256. pass # Already applied
  257. # Migration: Add AMS alarm notification columns to notification_providers
  258. try:
  259. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0"))
  260. except OperationalError:
  261. pass # Already applied
  262. try:
  263. await conn.execute(
  264. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  265. )
  266. except OperationalError:
  267. pass # Already applied
  268. # Migration: Add AMS-HT alarm notification columns to notification_providers
  269. try:
  270. await conn.execute(
  271. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  272. )
  273. except OperationalError:
  274. pass # Already applied
  275. try:
  276. await conn.execute(
  277. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  278. )
  279. except OperationalError:
  280. pass # Already applied
  281. # Migration: Add plate not empty notification column to notification_providers
  282. try:
  283. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1"))
  284. except OperationalError:
  285. pass # Already applied
  286. # Migration: Add notes column to projects (Phase 2)
  287. try:
  288. await conn.execute(text("ALTER TABLE projects ADD COLUMN notes TEXT"))
  289. except OperationalError:
  290. pass # Already applied
  291. # Migration: Add attachments column to projects (Phase 3)
  292. try:
  293. await conn.execute(text("ALTER TABLE projects ADD COLUMN attachments JSON"))
  294. except OperationalError:
  295. pass # Already applied
  296. # Migration: Add tags column to projects (Phase 4)
  297. try:
  298. await conn.execute(text("ALTER TABLE projects ADD COLUMN tags TEXT"))
  299. except OperationalError:
  300. pass # Already applied
  301. # Migration: Add due_date column to projects (Phase 5)
  302. try:
  303. await conn.execute(text("ALTER TABLE projects ADD COLUMN due_date DATETIME"))
  304. except OperationalError:
  305. pass # Already applied
  306. # Migration: Add priority column to projects (Phase 5)
  307. try:
  308. await conn.execute(text("ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'"))
  309. except OperationalError:
  310. pass # Already applied
  311. # Migration: Add budget column to projects (Phase 6)
  312. try:
  313. await conn.execute(text("ALTER TABLE projects ADD COLUMN budget REAL"))
  314. except OperationalError:
  315. pass # Already applied
  316. # Migration: Add is_template column to projects (Phase 8)
  317. try:
  318. await conn.execute(text("ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0"))
  319. except OperationalError:
  320. pass # Already applied
  321. # Migration: Add template_source_id column to projects (Phase 8)
  322. try:
  323. await conn.execute(text("ALTER TABLE projects ADD COLUMN template_source_id INTEGER"))
  324. except OperationalError:
  325. pass # Already applied
  326. # Migration: Add parent_id column to projects (Phase 10)
  327. try:
  328. await conn.execute(
  329. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  330. )
  331. except OperationalError:
  332. pass # Already applied
  333. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  334. try:
  335. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired"))
  336. except OperationalError:
  337. pass # Already applied
  338. # Migration: Add unit_price column to project_bom_items
  339. try:
  340. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN unit_price REAL"))
  341. except OperationalError:
  342. pass # Already applied
  343. # Migration: Add sourcing_url column to project_bom_items
  344. try:
  345. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)"))
  346. except OperationalError:
  347. pass # Already applied
  348. # Migration: Rename notes to remarks in project_bom_items
  349. try:
  350. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks"))
  351. except OperationalError:
  352. pass # Already applied
  353. # Migration: Add show_in_switchbar column to smart_plugs
  354. try:
  355. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0"))
  356. except OperationalError:
  357. pass # Already applied
  358. # Migration: Add runtime tracking columns to printers
  359. try:
  360. await conn.execute(text("ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0"))
  361. except OperationalError:
  362. pass # Already applied
  363. try:
  364. await conn.execute(text("ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME"))
  365. except OperationalError:
  366. pass # Already applied
  367. # Migration: Add quantity column to print_archives for tracking item count
  368. try:
  369. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1"))
  370. except OperationalError:
  371. pass # Already applied
  372. # Migration: Add manual_start column to print_queue for staged prints
  373. try:
  374. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0"))
  375. except OperationalError:
  376. pass # Already applied
  377. # Migration: Add wiki_url column to maintenance_types for documentation links
  378. try:
  379. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)"))
  380. except OperationalError:
  381. pass # Already applied
  382. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  383. try:
  384. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT"))
  385. except OperationalError:
  386. pass # Already applied
  387. # Migration: Add target_parts_count column to projects for tracking total parts needed
  388. try:
  389. await conn.execute(text("ALTER TABLE projects ADD COLUMN target_parts_count INTEGER"))
  390. except OperationalError:
  391. pass # Already applied
  392. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  393. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  394. try:
  395. # Check if printer_id is already nullable by trying to insert NULL
  396. # This is a safe check that won't affect existing data
  397. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  398. row = result.fetchone()
  399. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  400. # Need to migrate - printer_id is currently NOT NULL
  401. await conn.execute(
  402. text("""
  403. CREATE TABLE print_queue_new (
  404. id INTEGER PRIMARY KEY,
  405. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  406. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  407. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  408. position INTEGER DEFAULT 0,
  409. scheduled_time DATETIME,
  410. manual_start BOOLEAN DEFAULT 0,
  411. require_previous_success BOOLEAN DEFAULT 0,
  412. auto_off_after BOOLEAN DEFAULT 0,
  413. ams_mapping TEXT,
  414. status VARCHAR(20) DEFAULT 'pending',
  415. started_at DATETIME,
  416. completed_at DATETIME,
  417. error_message TEXT,
  418. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  419. )
  420. """)
  421. )
  422. await conn.execute(
  423. text("""
  424. INSERT INTO print_queue_new
  425. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  426. manual_start, require_previous_success, auto_off_after, ams_mapping,
  427. status, started_at, completed_at, error_message, created_at
  428. FROM print_queue
  429. """)
  430. )
  431. await conn.execute(text("DROP TABLE print_queue"))
  432. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  433. except OperationalError:
  434. pass # Already applied
  435. # Migration: Add plug_type column to smart_plugs for HA integration
  436. try:
  437. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'"))
  438. except OperationalError:
  439. pass # Already applied
  440. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  441. try:
  442. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)"))
  443. except OperationalError:
  444. pass # Already applied
  445. # Migration: Add project_id column to library_folders for linking folders to projects
  446. try:
  447. await conn.execute(
  448. text("ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  449. )
  450. except OperationalError:
  451. pass # Already applied
  452. # Migration: Add archive_id column to library_folders for linking folders to archives
  453. try:
  454. await conn.execute(
  455. text(
  456. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  457. )
  458. )
  459. except OperationalError:
  460. pass # Already applied
  461. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  462. try:
  463. # Check if ip_address is currently NOT NULL
  464. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  465. row = result.fetchone()
  466. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  467. # Need to migrate - ip_address is currently NOT NULL
  468. await conn.execute(
  469. text("""
  470. CREATE TABLE smart_plugs_new (
  471. id INTEGER PRIMARY KEY,
  472. name VARCHAR(100) NOT NULL,
  473. ip_address VARCHAR(45),
  474. plug_type VARCHAR(20) DEFAULT 'tasmota',
  475. ha_entity_id VARCHAR(100),
  476. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  477. enabled BOOLEAN NOT NULL DEFAULT 1,
  478. auto_on BOOLEAN NOT NULL DEFAULT 1,
  479. auto_off BOOLEAN NOT NULL DEFAULT 1,
  480. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  481. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  482. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  483. username VARCHAR(50),
  484. password VARCHAR(100),
  485. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  486. power_alert_high FLOAT,
  487. power_alert_low FLOAT,
  488. power_alert_last_triggered DATETIME,
  489. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  490. schedule_on_time VARCHAR(5),
  491. schedule_off_time VARCHAR(5),
  492. show_in_switchbar BOOLEAN DEFAULT 0,
  493. last_state VARCHAR(10),
  494. last_checked DATETIME,
  495. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  496. auto_off_pending BOOLEAN DEFAULT 0,
  497. auto_off_pending_since DATETIME,
  498. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  499. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  500. )
  501. """)
  502. )
  503. await conn.execute(
  504. text("""
  505. INSERT INTO smart_plugs_new
  506. SELECT id, name, ip_address,
  507. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  508. enabled, auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  509. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  510. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  511. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  512. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  513. FROM smart_plugs
  514. """)
  515. )
  516. await conn.execute(text("DROP TABLE smart_plugs"))
  517. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  518. except OperationalError:
  519. pass # Already applied
  520. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  521. try:
  522. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN plate_id INTEGER"))
  523. except OperationalError:
  524. pass # Already applied
  525. # Migration: Add print options columns to print_queue
  526. try:
  527. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1"))
  528. except OperationalError:
  529. pass # Already applied
  530. try:
  531. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0"))
  532. except OperationalError:
  533. pass # Already applied
  534. try:
  535. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1"))
  536. except OperationalError:
  537. pass # Already applied
  538. try:
  539. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0"))
  540. except OperationalError:
  541. pass # Already applied
  542. try:
  543. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0"))
  544. except OperationalError:
  545. pass # Already applied
  546. try:
  547. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1"))
  548. except OperationalError:
  549. pass # Already applied
  550. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  551. # This allows queue items to reference library files directly (archive created at print start)
  552. try:
  553. await conn.execute(
  554. text(
  555. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  556. )
  557. )
  558. except OperationalError:
  559. pass # Already applied
  560. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  561. try:
  562. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  563. row = result.fetchone()
  564. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  565. # Need to migrate - archive_id is currently NOT NULL
  566. await conn.execute(
  567. text("""
  568. CREATE TABLE print_queue_new2 (
  569. id INTEGER PRIMARY KEY,
  570. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  571. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  572. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  573. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  574. position INTEGER DEFAULT 0,
  575. scheduled_time DATETIME,
  576. manual_start BOOLEAN DEFAULT 0,
  577. require_previous_success BOOLEAN DEFAULT 0,
  578. auto_off_after BOOLEAN DEFAULT 0,
  579. ams_mapping TEXT,
  580. plate_id INTEGER,
  581. bed_levelling BOOLEAN DEFAULT 1,
  582. flow_cali BOOLEAN DEFAULT 0,
  583. vibration_cali BOOLEAN DEFAULT 1,
  584. layer_inspect BOOLEAN DEFAULT 0,
  585. timelapse BOOLEAN DEFAULT 0,
  586. use_ams BOOLEAN DEFAULT 1,
  587. status VARCHAR(20) DEFAULT 'pending',
  588. started_at DATETIME,
  589. completed_at DATETIME,
  590. error_message TEXT,
  591. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  592. )
  593. """)
  594. )
  595. await conn.execute(
  596. text("""
  597. INSERT INTO print_queue_new2
  598. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  599. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  600. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  601. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  602. status, started_at, completed_at, error_message, created_at
  603. FROM print_queue
  604. """)
  605. )
  606. await conn.execute(text("DROP TABLE print_queue"))
  607. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  608. except OperationalError:
  609. pass # Already applied
  610. # Migration: Add HA energy sensor entity columns to smart_plugs
  611. try:
  612. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)"))
  613. except OperationalError:
  614. pass # Already applied
  615. try:
  616. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)"))
  617. except OperationalError:
  618. pass # Already applied
  619. try:
  620. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)"))
  621. except OperationalError:
  622. pass # Already applied
  623. # Migration: Create users table for authentication
  624. try:
  625. await conn.execute(
  626. text("""
  627. CREATE TABLE IF NOT EXISTS users (
  628. id INTEGER PRIMARY KEY,
  629. username VARCHAR(100) NOT NULL UNIQUE,
  630. password_hash VARCHAR(255) NOT NULL,
  631. role VARCHAR(20) NOT NULL DEFAULT 'user',
  632. is_active BOOLEAN NOT NULL DEFAULT 1,
  633. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  634. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  635. )
  636. """)
  637. )
  638. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  639. except OperationalError:
  640. pass # Already applied
  641. # Migration: Add external camera columns to printers
  642. try:
  643. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)"))
  644. except OperationalError:
  645. pass # Already applied
  646. try:
  647. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)"))
  648. except OperationalError:
  649. pass # Already applied
  650. try:
  651. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0"))
  652. except OperationalError:
  653. pass # Already applied
  654. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  655. try:
  656. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)"))
  657. except OperationalError:
  658. pass # Already applied
  659. # Migration: Add sliced_for_model column to print_archives for model-based queue assignment
  660. try:
  661. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)"))
  662. except OperationalError:
  663. pass # Already applied
  664. # Migration: Add is_external column to library_files for external cloud files
  665. try:
  666. await conn.execute(text("ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  667. except OperationalError:
  668. pass # Already applied
  669. # Migration: Add project_id column to library_files
  670. try:
  671. await conn.execute(
  672. text("ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  673. )
  674. except OperationalError:
  675. pass # Already applied
  676. # Migration: Add is_external column to library_folders for external cloud folders
  677. try:
  678. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  679. except OperationalError:
  680. pass # Already applied
  681. # Migration: Add external folder settings columns to library_folders
  682. try:
  683. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0"))
  684. except OperationalError:
  685. pass # Already applied
  686. try:
  687. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0"))
  688. except OperationalError:
  689. pass # Already applied
  690. try:
  691. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)"))
  692. except OperationalError:
  693. pass # Already applied
  694. # Migration: Add plate_detection_enabled column to printers
  695. try:
  696. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0"))
  697. except OperationalError:
  698. pass # Already applied
  699. # Migration: Add plate detection ROI columns to printers
  700. try:
  701. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL"))
  702. except OperationalError:
  703. pass # Already applied
  704. try:
  705. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL"))
  706. except OperationalError:
  707. pass # Already applied
  708. try:
  709. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL"))
  710. except OperationalError:
  711. pass # Already applied
  712. try:
  713. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL"))
  714. except OperationalError:
  715. pass # Already applied
  716. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  717. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  718. # SQLite requires table recreation to drop constraints
  719. try:
  720. # Check if we need to migrate (if UNIQUE constraint exists)
  721. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  722. row = result.fetchone()
  723. if row and "printer_id INTEGER UNIQUE" in (row[0] or ""):
  724. # Create new table without UNIQUE constraint on printer_id
  725. await conn.execute(
  726. text("""
  727. CREATE TABLE smart_plugs_temp (
  728. id INTEGER PRIMARY KEY,
  729. name VARCHAR(100) NOT NULL,
  730. ip_address VARCHAR(45),
  731. plug_type VARCHAR(20) DEFAULT 'tasmota',
  732. ha_entity_id VARCHAR(100),
  733. ha_power_entity VARCHAR(100),
  734. ha_energy_today_entity VARCHAR(100),
  735. ha_energy_total_entity VARCHAR(100),
  736. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  737. enabled BOOLEAN NOT NULL DEFAULT 1,
  738. auto_on BOOLEAN NOT NULL DEFAULT 1,
  739. auto_off BOOLEAN NOT NULL DEFAULT 1,
  740. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  741. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  742. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  743. username VARCHAR(50),
  744. password VARCHAR(100),
  745. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  746. power_alert_high FLOAT,
  747. power_alert_low FLOAT,
  748. power_alert_last_triggered DATETIME,
  749. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  750. schedule_on_time VARCHAR(5),
  751. schedule_off_time VARCHAR(5),
  752. show_in_switchbar BOOLEAN DEFAULT 0,
  753. last_state VARCHAR(10),
  754. last_checked DATETIME,
  755. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  756. auto_off_pending BOOLEAN DEFAULT 0,
  757. auto_off_pending_since DATETIME,
  758. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  759. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  760. )
  761. """)
  762. )
  763. # Copy data
  764. await conn.execute(
  765. text("""
  766. INSERT INTO smart_plugs_temp
  767. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  768. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  769. auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  770. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  771. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  772. show_in_switchbar, last_state, last_checked, auto_off_executed,
  773. auto_off_pending, auto_off_pending_since, created_at, updated_at
  774. FROM smart_plugs
  775. """)
  776. )
  777. # Drop old table and rename new one
  778. await conn.execute(text("DROP TABLE smart_plugs"))
  779. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  780. except OperationalError:
  781. pass # Already applied
  782. # Migration: Add show_on_printer_card column to smart_plugs
  783. try:
  784. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1"))
  785. except OperationalError:
  786. pass # Already applied
  787. # Migration: Add MQTT smart plug fields (legacy)
  788. try:
  789. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)"))
  790. except OperationalError:
  791. pass # Already applied
  792. try:
  793. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)"))
  794. except OperationalError:
  795. pass # Already applied
  796. try:
  797. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)"))
  798. except OperationalError:
  799. pass # Already applied
  800. try:
  801. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)"))
  802. except OperationalError:
  803. pass # Already applied
  804. try:
  805. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0"))
  806. except OperationalError:
  807. pass # Already applied
  808. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  809. try:
  810. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)"))
  811. except OperationalError:
  812. pass # Already applied
  813. try:
  814. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0"))
  815. except OperationalError:
  816. pass # Already applied
  817. try:
  818. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)"))
  819. except OperationalError:
  820. pass # Already applied
  821. try:
  822. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0"))
  823. except OperationalError:
  824. pass # Already applied
  825. try:
  826. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)"))
  827. except OperationalError:
  828. pass # Already applied
  829. try:
  830. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)"))
  831. except OperationalError:
  832. pass # Already applied
  833. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  834. try:
  835. await conn.execute(
  836. text("""
  837. UPDATE smart_plugs
  838. SET mqtt_power_topic = mqtt_topic,
  839. mqtt_power_multiplier = mqtt_multiplier
  840. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  841. """)
  842. )
  843. except OperationalError:
  844. pass # Already applied
  845. # Migration: Create groups table for permission-based access control
  846. try:
  847. await conn.execute(
  848. text("""
  849. CREATE TABLE IF NOT EXISTS groups (
  850. id INTEGER PRIMARY KEY,
  851. name VARCHAR(100) NOT NULL UNIQUE,
  852. description VARCHAR(500),
  853. permissions JSON,
  854. is_system BOOLEAN NOT NULL DEFAULT 0,
  855. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  856. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  857. )
  858. """)
  859. )
  860. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  861. except OperationalError:
  862. pass # Already applied
  863. # Migration: Create user_groups association table
  864. try:
  865. await conn.execute(
  866. text("""
  867. CREATE TABLE IF NOT EXISTS user_groups (
  868. user_id INTEGER NOT NULL,
  869. group_id INTEGER NOT NULL,
  870. PRIMARY KEY (user_id, group_id),
  871. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  872. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  873. )
  874. """)
  875. )
  876. except OperationalError:
  877. pass # Already applied
  878. # Migration: Add model-based queue assignment columns to print_queue
  879. try:
  880. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)"))
  881. except OperationalError:
  882. pass # Already applied
  883. try:
  884. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT"))
  885. except OperationalError:
  886. pass # Already applied
  887. try:
  888. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT"))
  889. except OperationalError:
  890. pass # Already applied
  891. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  892. try:
  893. await conn.execute(text("ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1"))
  894. except OperationalError:
  895. pass # Already applied
  896. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  897. try:
  898. await conn.execute(text("ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0"))
  899. except OperationalError:
  900. pass # Already applied
  901. # Migration: Add queue notification event columns to notification_providers
  902. try:
  903. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0"))
  904. except OperationalError:
  905. pass # Already applied
  906. try:
  907. await conn.execute(
  908. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  909. )
  910. except OperationalError:
  911. pass # Already applied
  912. try:
  913. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0"))
  914. except OperationalError:
  915. pass # Already applied
  916. try:
  917. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1"))
  918. except OperationalError:
  919. pass # Already applied
  920. try:
  921. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1"))
  922. except OperationalError:
  923. pass # Already applied
  924. try:
  925. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1"))
  926. except OperationalError:
  927. pass # Already applied
  928. try:
  929. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0"))
  930. except OperationalError:
  931. pass # Already applied
  932. # Migration: Add created_by_id column to print_archives for user tracking (Issue #206)
  933. try:
  934. await conn.execute(
  935. text("ALTER TABLE print_archives ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  936. )
  937. except OperationalError:
  938. pass # Already applied
  939. # Migration: Add created_by_id column to print_queue for user tracking (Issue #206)
  940. try:
  941. await conn.execute(
  942. text("ALTER TABLE print_queue ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  943. )
  944. except OperationalError:
  945. pass # Already applied
  946. # Migration: Add created_by_id column to library_files for user tracking (Issue #206)
  947. try:
  948. await conn.execute(
  949. text("ALTER TABLE library_files ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  950. )
  951. except OperationalError:
  952. pass # Already applied
  953. # Migration: Add target_location column to print_queue for location-based filtering (Issue #220)
  954. try:
  955. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_location VARCHAR(100)"))
  956. except OperationalError:
  957. pass # Already applied
  958. # Migration: Convert absolute paths to relative paths in library_files table
  959. # This ensures backup/restore portability across different installations
  960. try:
  961. base_dir_str = str(settings.base_dir)
  962. # Ensure we have a trailing slash for clean replacement
  963. if not base_dir_str.endswith("/"):
  964. base_dir_str += "/"
  965. # Update file_path - remove base_dir prefix from absolute paths
  966. await conn.execute(
  967. text("""
  968. UPDATE library_files
  969. SET file_path = SUBSTR(file_path, LENGTH(:base_dir) + 1)
  970. WHERE file_path LIKE :pattern
  971. """),
  972. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  973. )
  974. # Update thumbnail_path - remove base_dir prefix from absolute paths
  975. await conn.execute(
  976. text("""
  977. UPDATE library_files
  978. SET thumbnail_path = SUBSTR(thumbnail_path, LENGTH(:base_dir) + 1)
  979. WHERE thumbnail_path LIKE :pattern
  980. """),
  981. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  982. )
  983. except OperationalError:
  984. pass # Already applied
  985. # Create active_print_spoolman table for Spoolman per-filament tracking
  986. try:
  987. await conn.execute(
  988. text("""
  989. CREATE TABLE IF NOT EXISTS active_print_spoolman (
  990. id INTEGER PRIMARY KEY AUTOINCREMENT,
  991. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  992. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  993. filament_usage TEXT NOT NULL,
  994. ams_trays TEXT NOT NULL,
  995. slot_to_tray TEXT,
  996. layer_usage TEXT,
  997. filament_properties TEXT,
  998. UNIQUE(printer_id, archive_id)
  999. )
  1000. """)
  1001. )
  1002. except OperationalError:
  1003. pass # Already applied
  1004. # Migration: Add preset_source column to slot_preset_mappings for local preset support
  1005. try:
  1006. await conn.execute(
  1007. text("ALTER TABLE slot_preset_mappings ADD COLUMN preset_source VARCHAR(20) DEFAULT 'cloud'")
  1008. )
  1009. except OperationalError:
  1010. pass # Already applied
  1011. # Migration: Add email column to users for Advanced Auth (PR #322)
  1012. try:
  1013. await conn.execute(text("ALTER TABLE users ADD COLUMN email VARCHAR(255)"))
  1014. except OperationalError:
  1015. pass # Already applied
  1016. async def seed_notification_templates():
  1017. """Seed default notification templates if they don't exist."""
  1018. from sqlalchemy import select
  1019. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  1020. async with async_session() as session:
  1021. # Get existing template event types
  1022. result = await session.execute(select(NotificationTemplate.event_type))
  1023. existing_types = {row[0] for row in result.fetchall()}
  1024. if not existing_types:
  1025. # No templates exist - insert all defaults
  1026. for template_data in DEFAULT_TEMPLATES:
  1027. template = NotificationTemplate(
  1028. event_type=template_data["event_type"],
  1029. name=template_data["name"],
  1030. title_template=template_data["title_template"],
  1031. body_template=template_data["body_template"],
  1032. is_default=True,
  1033. )
  1034. session.add(template)
  1035. else:
  1036. # Templates exist - only add missing ones
  1037. for template_data in DEFAULT_TEMPLATES:
  1038. if template_data["event_type"] not in existing_types:
  1039. template = NotificationTemplate(
  1040. event_type=template_data["event_type"],
  1041. name=template_data["name"],
  1042. title_template=template_data["title_template"],
  1043. body_template=template_data["body_template"],
  1044. is_default=True,
  1045. )
  1046. session.add(template)
  1047. await session.commit()
  1048. async def seed_default_groups():
  1049. """Seed default groups and migrate existing users to appropriate groups.
  1050. Creates the default system groups (Administrators, Operators, Viewers) if they
  1051. don't exist, then migrates existing users:
  1052. - Users with role='admin' -> Administrators group
  1053. - Users with role='user' -> Operators group
  1054. Also migrates old permissions to new ownership-based permissions (Issue #205).
  1055. """
  1056. import logging
  1057. from sqlalchemy import select
  1058. from backend.app.core.permissions import DEFAULT_GROUPS
  1059. from backend.app.models.group import Group
  1060. from backend.app.models.user import User
  1061. logger = logging.getLogger(__name__)
  1062. # Map old permissions to new ones for migration
  1063. # Administrators get *_all permissions, Operators get *_own permissions
  1064. PERMISSION_MIGRATION_ALL = {
  1065. "queue:update": "queue:update_all",
  1066. "queue:delete": "queue:delete_all",
  1067. "archives:update": "archives:update_all",
  1068. "archives:delete": "archives:delete_all",
  1069. "archives:reprint": "archives:reprint_all",
  1070. "library:update": "library:update_all",
  1071. "library:delete": "library:delete_all",
  1072. }
  1073. PERMISSION_MIGRATION_OWN = {
  1074. "queue:update": "queue:update_own",
  1075. "queue:delete": "queue:delete_own",
  1076. "archives:update": "archives:update_own",
  1077. "archives:delete": "archives:delete_own",
  1078. "archives:reprint": "archives:reprint_own",
  1079. "library:update": "library:update_own",
  1080. "library:delete": "library:delete_own",
  1081. }
  1082. async with async_session() as session:
  1083. # Get existing groups
  1084. result = await session.execute(select(Group))
  1085. existing_groups = {group.name: group for group in result.scalars().all()}
  1086. # Create default groups if they don't exist
  1087. groups_created = []
  1088. for group_name, group_config in DEFAULT_GROUPS.items():
  1089. if group_name not in existing_groups:
  1090. group = Group(
  1091. name=group_name,
  1092. description=group_config["description"],
  1093. permissions=group_config["permissions"],
  1094. is_system=group_config["is_system"],
  1095. )
  1096. session.add(group)
  1097. groups_created.append(group_name)
  1098. logger.info("Created default group: %s", group_name)
  1099. else:
  1100. # Migrate existing group's permissions from old to new format
  1101. group = existing_groups[group_name]
  1102. if group.permissions:
  1103. updated = False
  1104. new_permissions = list(group.permissions)
  1105. # Determine which migration map to use based on group
  1106. migration_map = (
  1107. PERMISSION_MIGRATION_ALL if group_name == "Administrators" else PERMISSION_MIGRATION_OWN
  1108. )
  1109. for old_perm, new_perm in migration_map.items():
  1110. if old_perm in new_permissions:
  1111. new_permissions.remove(old_perm)
  1112. if new_perm not in new_permissions:
  1113. new_permissions.append(new_perm)
  1114. updated = True
  1115. logger.info(
  1116. "Migrated permission '%s' to '%s' in group '%s'", old_perm, new_perm, group_name
  1117. )
  1118. # For Administrators, also ensure they get *_all permissions if they have any new *_own
  1119. if group_name == "Administrators":
  1120. for _own_perm, all_perm in [
  1121. ("queue:update_own", "queue:update_all"),
  1122. ("queue:delete_own", "queue:delete_all"),
  1123. ("archives:update_own", "archives:update_all"),
  1124. ("archives:delete_own", "archives:delete_all"),
  1125. ("archives:reprint_own", "archives:reprint_all"),
  1126. ("library:update_own", "library:update_all"),
  1127. ("library:delete_own", "library:delete_all"),
  1128. ]:
  1129. # Add *_all if not present
  1130. if all_perm not in new_permissions:
  1131. new_permissions.append(all_perm)
  1132. updated = True
  1133. if updated:
  1134. group.permissions = new_permissions
  1135. await session.commit()
  1136. # Migrate existing users to groups if they're not already in any group
  1137. if groups_created:
  1138. # Refresh to get newly created groups
  1139. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  1140. admin_group = admin_result.scalar_one_or_none()
  1141. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  1142. operators_group = operators_result.scalar_one_or_none()
  1143. # Get all users
  1144. users_result = await session.execute(select(User))
  1145. users = users_result.scalars().all()
  1146. for user in users:
  1147. # Skip if user already has groups
  1148. if user.groups:
  1149. continue
  1150. if user.role == "admin" and admin_group:
  1151. user.groups.append(admin_group)
  1152. logger.info("Migrated admin user '%s' to Administrators group", user.username)
  1153. elif operators_group:
  1154. user.groups.append(operators_group)
  1155. logger.info("Migrated user '%s' to Operators group", user.username)
  1156. await session.commit()