database.py 58 KB

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