database.py 56 KB

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