database.py 76 KB

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