database.py 57 KB

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