database.py 61 KB

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