database.py 63 KB

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